问:
Trying to execute through Hive a Select count(*) in a view with 3936 columns we are getting the error Map operator initialization failed
We are running a SAS job into an AWS EMR using TEZ engine and when it is executing this query through hive:

```<code>SELECT COUNT(*) AS count FROM forv03141228160142_1672177412007
</code>```

Then we are getting this error in hive-server2.log:

```2023-01-03T21:32:16,280 INFO  [HiveServer2-Background-Pool: Thread-94([])]: SessionState (:()) - Map 1: 0(+0,-4)/1  Reducer 2: 0/1
2023-01-03T21:32:16,280 ERROR [HiveServer2-Background-Pool: Thread-94([])]: SessionState (:()) - Status: Failed
2023-01-03T21:32:16,283 ERROR [HiveServer2-Background-Pool: Thread-94([])]: SessionState (:()) -**Vertex failed, vertexName=Map 1, vertexId=vertex_1666383011400_0273_1_00, diagnostics=[Task failed, taskId=task_1666383011400_0273_1_00_000000, diagnostics=[TaskAttempt 0 failed, info=[Error: Error while running task ( failure ) : attempt_1666383011400_0273_1_00_000000_0:java.lang.RuntimeException: java.lang.RuntimeException: Map operator initialization failed**
    at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.initializeAndRunProcessor(TezProcessor.java:217)
    at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.run(TezProcessor.java:171)
    at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask.run(LogicalIOProcessorRuntimeTask.java:374)
    at org.apache.tez.runtime.task.TaskRunner2Callable$1.run(TaskRunner2Callable.java:73)
    at org.apache.tez.runtime.task.TaskRunner2Callable$1.run(TaskRunner2Callable.java:61)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1926)
    at org.apache.tez.runtime.task.TaskRunner2Callable.callInternal(TaskRunner2Callable.java:61)
    at org.apache.tez.runtime.task.TaskRunner2Callable.callInternal(TaskRunner2Callable.java:37)
    at org.apache.tez.common.CallableWithNdc.call(CallableWithNdc.java:36)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:750)
**Caused by: java.lang.RuntimeException: Map operator initialization failed**
    at org.apache.hadoop.hive.ql.exec.tez.MapRecordProcessor.init(MapRecordProcessor.java:354)
    at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.initializeAndRunProcessor(TezProcessor.java:188)
    ... 14 more
Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: java.util.regex.PatternSyntaxException: Stack overflow during pattern compilation near index 26400
(.{10})(.{10})...(.{10})(.{10})(.{10})(.{10})(.{10})(.{10})
                                                         ^

    at org.apache.hadoop.hive.ql.exec.MapOperator.getConvertedOI(MapOperator.java:328)
    at org.apache.hadoop.hive.ql.exec.MapOperator.setChildren(MapOperator.java:423)
    at org.apache.hadoop.hive.ql.exec.tez.MapRecordProcessor.init(MapRecordProcessor.java:286)
    ... 15 more
```

This is what SAS is receiving:

Return codes from Hive ( SYSDBRC=-1 SYSDBMSG=HADOOP: ERROR: Prepare error: Buffer overflowSQL statement: SELECT COUNT() AS
count FROM forv03141228160142_1672177412007 SQLXMSG=ERROR: Prepare error: Buffer overflowSQL statement: SELECT COUNT() AS count

We tried increasing the HADOOP_HEAPSIZE, setting the jar commons-httpclient-3.1.jar into the HIVE_AUX_JARS_PATH and setting the variables: hive.vectorized.execution and hive.vectorized.execution.enabled as false, but nothing has worked

Body:
We are running a SAS job into an AWS EMR using TEZ engine and when it is executing this query through hive:

SELECT COUNT(*) AS count FROM forv03141228160142_1672177412007

Then we are getting this error in hive-server2.log:

2023-01-03T21:32:16,280 INFO  [HiveServer2-Background-Pool: Thread-94([])]: SessionState (:()) - Map 1: 0(+0,-4)/1  Reducer 2: 0/1
2023-01-03T21:32:16,280 ERROR [HiveServer2-Background-Pool: Thread-94([])]: SessionState (:()) - Status: Failed
2023-01-03T21:32:16,283 ERROR [HiveServer2-Background-Pool: Thread-94([])]: SessionState (:()) -**Vertex failed, vertexName=Map 1, vertexId=vertex_1666383011400_0273_1_00, diagnostics=[Task failed, taskId=task_1666383011400_0273_1_00_000000, diagnostics=[TaskAttempt 0 failed, info=[Error: Error while running task ( failure ) : attempt_1666383011400_0273_1_00_000000_0:java.lang.RuntimeException: java.lang.RuntimeException: Map operator initialization failed**
    at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.initializeAndRunProcessor(TezProcessor.java:217)
    at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.run(TezProcessor.java:171)
    at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask.run(LogicalIOProcessorRuntimeTask.java:374)
    at org.apache.tez.runtime.task.TaskRunner2Callable$1.run(TaskRunner2Callable.java:73)
    at org.apache.tez.runtime.task.TaskRunner2Callable$1.run(TaskRunner2Callable.java:61)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1926)
    at org.apache.tez.runtime.task.TaskRunner2Callable.callInternal(TaskRunner2Callable.java:61)
    at org.apache.tez.runtime.task.TaskRunner2Callable.callInternal(TaskRunner2Callable.java:37)
    at org.apache.tez.common.CallableWithNdc.call(CallableWithNdc.java:36)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:750)
**Caused by: java.lang.RuntimeException: Map operator initialization failed**
    at org.apache.hadoop.hive.ql.exec.tez.MapRecordProcessor.init(MapRecordProcessor.java:354)
    at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.initializeAndRunProcessor(TezProcessor.java:188)
    ... 14 more
Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: java.util.regex.PatternSyntaxException: Stack overflow during pattern compilation near index 26400
(.{10})(.{10})...(.{10})(.{10})(.{10})(.{10})(.{10})(.{10})
                                                         ^

    at org.apache.hadoop.hive.ql.exec.MapOperator.getConvertedOI(MapOperator.java:328)
    at org.apache.hadoop.hive.ql.exec.MapOperator.setChildren(MapOperator.java:423)
    at org.apache.hadoop.hive.ql.exec.tez.MapRecordProcessor.init(MapRecordProcessor.java:286)
    ... 15 more

This is what SAS is receiving:

Return codes from Hive ( SYSDBRC=-1 SYSDBMSG=HADOOP: ERROR: Prepare error: Buffer overflowSQL statement: SELECT COUNT() AS
count FROM forv03141228160142_1672177412007 SQLXMSG=ERROR: Prepare error: Buffer overflowSQL statement: SELECT COUNT() AS count

We tried increasing the HADOOP_HEAPSIZE, setting the jar commons-httpclient-3.1.jar into the HIVE_AUX_JARS_PATH and setting the variables: hive.vectorized.execution and hive.vectorized.execution.enabled as false, but nothing has worked


来源: stackexchange

问:
Cant see widgets in QMainWindow pyqt6
I've created a window that should theoretically behave as a splash screen for my application. I've designed the layout using designer, but when trying to launch it the right way all I get is a blank screen.

None of the widgets are rendered.

import sys
from PyQt6 import QtCore, QtWidgets, QtGui
from thinclient.ui.launcher.splashScreen import Ui_MainWindow as splashScreen_MainWindow
import time

class SplashScreen(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.ui = splashScreen_MainWindow()
        self.ui.setupUi(self)
        self.show()

        for i in range(20,101,20):
            # self.ui.progressBar.setValue(i)
            time.sleep(2)
```
<p>This is the pyuic generated file that works fine when launched standalone but weird when launching by a submodule in the python package.</p>
<pre class="lang-py prettyprint-override"><code># Form implementation generated from reading ui file 'ui/splashScreen.ui'
#
# Created by: PyQt6 UI code generator 6.4.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt6 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(140, 380, 67, 17))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "TextLabel"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec())

</code>```

ContentLicense: CC BY-SA 4.0

Title: Cant see widgets in QMainWindow pyqt6

Body:
I've created a window that should theoretically behave as a splash screen for my application. I've designed the layout using designer, but when trying to launch it the right way all I get is a blank screen.

None of the widgets are rendered.

import sys
from PyQt6 import QtCore, QtWidgets, QtGui
from thinclient.ui.launcher.splashScreen import Ui_MainWindow as splashScreen_MainWindow
import time

class SplashScreen(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.ui = splashScreen_MainWindow()
        self.ui.setupUi(self)
        self.show()

        for i in range(20,101,20):
            # self.ui.progressBar.setValue(i)
            time.sleep(2)

This is the pyuic generated file that works fine when launched standalone but weird when launching by a submodule in the python package.

# Form implementation generated from reading ui file 'ui/splashScreen.ui'
#
# Created by: PyQt6 UI code generator 6.4.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt6 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(140, 380, 67, 17))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "TextLabel"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec())


问:
What would be a good RTMP client for my desktop kotlin app?
I need an RTMP client for a desktop Kotlin app. It must be open source and Linux compatible.

I have looked at red5 and there wasn't any info on how to actually put it in my code. Most of the other stuff out there is for Android. VLC won't work as I don't want the video to be in a separate window.


问:
transform.scale breaks the image PyGame
Python. PyGame.

I have 660x660 image. When i load it as 660x660 everything is fine.

But if i resize image to 210x210(i can`t use another size) throw pygame.transform.scale and load it, image breaks.

My way to resize the image:

transform.scale(image.load("grid.png").convert_alpha(), (210, 210))
```
<p><strong>Can i fix the resized picture throw the code, to keep the sticks of my grid symmetric</strong>(without making new image with new size)?</p>
<p>All code:</p>
<pre class="lang-py prettyprint-override"><code>import sys

import pygame as pg
from pygame import image
from pygame import transform

pg.init()

screen = pg.display.set_mode((660, 660))
screen.blit(transform.scale(image.load("grid.png").convert_alpha(), (210, 210)), (0, 0))

while True:
    for e in pg.event.get():
        if e.type == pg.QUIT:
            sys.exit()

    pg.display.flip()

</code>```

Title: transform.scale breaks the image PyGame

Body:
Python. PyGame.

I have 660x660 image. When i load it as 660x660 everything is fine.

But if i resize image to 210x210(i can`t use another size) throw pygame.transform.scale and load it, image breaks.

My way to resize the image:

transform.scale(image.load("grid.png").convert_alpha(), (210, 210))

Can i fix the resized picture throw the code, to keep the sticks of my grid symmetric(without making new image with new size)?

All code:

import sys

import pygame as pg
from pygame import image
from pygame import transform

pg.init()

screen = pg.display.set_mode((660, 660))
screen.blit(transform.scale(image.load("grid.png").convert_alpha(), (210, 210)), (0, 0))

while True:
    for e in pg.event.get():
        if e.type == pg.QUIT:
            sys.exit()

    pg.display.flip()


问:
Normalising counted values by group
I have a table of data in which companies have differing numbers of locations with different values for each key.

Key
Company
Value
Location

Start
Burgers
Monday
Sydney

Start
Burgers
Sunday
Brisbane

Start
Donuts
Monday
Sydney

I want to count the different values but normalised so that companies with multiple locations don't skew things. The output i'm hoping for is something like this:

Value
Count

Monday
1.5

Sunday
0.5

Keep banging my head against how to approach this so any help is greatly appreciated.

Title: Normalising counted values by group


问:
Create a connection using a wallet name in OCCI
I'm attempting to use the occi environment to create a connection using a wallet with the following credentials: (connectstring: TestDB, username: TestName, pass: TestPass). The connect string is an associated TNSName. I've verified with sql plus that I can connect to the database using the wallet and the associated connectstring.

I've searched oracle's documentation but I'm unsure as to how to structure the Environment::CreateConnection({username}, {password}, {connection string}) function call with only the wallet connect string.

I've tried:
CreateConnection("", "", "/@TestDB") CreateConnection("", "", "TestDB") CreateConnection("", "", "DATA SOURCE={walletname};USER ID=/;” )
with no success. Any help please?


问:
Steam get inventory of user returns 429 after few requests
I need to obtain a users csgo-steam-inventory by a given steamId via this endpoint:

https://steamcommunity.com/inventory/<STEAMID64>/730/2?l=english&count=5000

This has worked well for some time, but recently, I feel like there has been a massive increase in rate-limitation, because now, even when trying in the browser, if I reload the page 5 times each time with 1-2 seconds pause inbetween, i soon get a ´429 Too many requests´.

Is there any way to avoid this, or is there a way by using existing libraries?

I have tried using proxies (public ones, which might have been blacklisted i guess), but this does not work properly. I still get 429ed. What would the proper way to do this via proxies, if not using public ones? Buying multiple servers with different IP's is too expensive.

I also tried increasing the delay between requests up to 5 seconds, but still I get blocked.


问:
Google maps api DirectionsResult object is not getting updating on dragging the route in reactjs
I have a web application in react where I am creating a route between an origin and destination. I have made the route to be draggable. When I drag the starting or destination points the new route is rendered automatically from google's side however the directionsResult object is not getting updated. When I try to console.log the markers longitude and latitude that I just dragged in the onDirectionsChanged event handler it is still showing the initial value that it had. Any idea why?

my app.js code :

```<code>import {
  Box,
  Button,
  ButtonGroup,
  Flex,
  HStack,
  IconButton,
  Input,
  SkeletonText,
  Text,
} from '@chakra-ui/react'
import { FaLocationArrow, FaTimes } from 'react-icons/fa'

import {
  useJsApiLoader,
  GoogleMap,
  Marker,
  Autocomplete,
  DirectionsRenderer,
} from '@react-google-maps/api'
import { useRef, useState } from 'react'

const center = { lat: 48.8584, lng: 2.2945 }

function App() {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
    libraries: ['places'],
  })

  const [map, setMap] = useState(/** @type google.maps.Map */ (null))
  const [directionsResponse, setDirectionsResponse] = useState(null)
  const [distance, setDistance] = useState('')
  const [duration, setDuration] = useState('')

  /** @type React.MutableRefObject<HTMLInputElement> */
  const originRef = useRef()
  /** @type React.MutableRefObject<HTMLInputElement> */
  const destiantionRef = useRef()

  if (!isLoaded) {
    return <SkeletonText />
  }

  async function calculateRoute() {
    if (originRef.current.value === '' || destiantionRef.current.value === '') {
      return
    }
    // eslint-disable-next-line no-undef
    const directionsService = new google.maps.DirectionsService()
    const results = await directionsService.route({
      origin: originRef.current.value,
      destination: destiantionRef.current.value,
      // eslint-disable-next-line no-undef
      travelMode: google.maps.TravelMode.DRIVING,
    })
    setDirectionsResponse(results)
    setDistance(results.routes[0].legs[0].distance.text)
    setDuration(results.routes[0].legs[0].duration.text)
  }

  function clearRoute() {
    setDirectionsResponse(null)
    setDistance('')
    setDuration('')
    originRef.current.value = ''
    destiantionRef.current.value = ''
  }

  return (
    <Flex
      position='relative'
      flexDirection='column'
      alignItems='center'
      h='100vh'
      w='100vw'
    >
      <Box position='absolute' left={0} top={0} h='100%' w='100%'>
        {/* Google Map Box */}
        <GoogleMap
          center={center}
          zoom={15}
          mapContainerStyle={{ width: '100%', height: '100%' }}
          options={{
            zoomControl: false,
            streetViewControl: false,
            mapTypeControl: false,
            fullscreenControl: false,
          }}
          onLoad={map => setMap(map)}
        >
          <Marker position={center} />
          {directionsResponse && (
            <DirectionsRenderer directions={directionsResponse} options={{
              draggable:true,
              polylineOptions: {
                strokeOpacity: 12,
                strokeColor: "#1641a6",
                strokeWeight: 12,
              },
            }}
            onDirectionsChanged = {() => {
              console.log("Start latitiude ",directionsResponse.routes[0].legs[0].start_location.lat())
              console.log("Start longitude ",directionsResponse.routes[0].legs[0].start_location.lng())
            }} />

          )}
        </GoogleMap>
      </Box>
      <Box
        p={4}
        borderRadius='lg'
        m={4}
        bgColor='white'
        shadow='base'
        minW='container.md'
        zIndex='1'
      >
        <HStack spacing={2} justifyContent='space-between'>
          <Box flexGrow={1}>
            <Autocomplete>
              <Input type='text' placeholder='Origin' ref={originRef} />
            </Autocomplete>
          </Box>
          <Box flexGrow={1}>
            <Autocomplete>
              <Input
                type='text'
                placeholder='Destination'
                ref={destiantionRef}
              />
            </Autocomplete>
          </Box>

          <ButtonGroup>
            <Button colorScheme='pink' type='submit' onClick={calculateRoute}>
              Calculate Route
            </Button>
            <IconButton
              aria-label='center back'
              icon={<FaTimes />}
              onClick={clearRoute}
            />
          </ButtonGroup>
        </HStack>
        <HStack spacing={4} mt={4} justifyContent='space-between'>
          <Text>Distance: {distance} </Text>
          <Text>Duration: {duration} </Text>
          <IconButton
            aria-label='center back'
            icon={<FaLocationArrow />}
            isRound
            onClick={() => {
              map.panTo(center)
              map.setZoom(15)
            }}
          />
        </HStack>
      </Box>
    </Flex>
  )
}

export default App

</code>```

Body:
I have a web application in react where I am creating a route between an origin and destination. I have made the route to be draggable. When I drag the starting or destination points the new route is rendered automatically from google's side however the directionsResult object is not getting updated. When I try to console.log the markers longitude and latitude that I just dragged in the onDirectionsChanged event handler it is still showing the initial value that it had. Any idea why?

my app.js code :

import {
  Box,
  Button,
  ButtonGroup,
  Flex,
  HStack,
  IconButton,
  Input,
  SkeletonText,
  Text,
} from '@chakra-ui/react'
import { FaLocationArrow, FaTimes } from 'react-icons/fa'

import {
  useJsApiLoader,
  GoogleMap,
  Marker,
  Autocomplete,
  DirectionsRenderer,
} from '@react-google-maps/api'
import { useRef, useState } from 'react'

const center = { lat: 48.8584, lng: 2.2945 }

function App() {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
    libraries: ['places'],
  })

  const [map, setMap] = useState(/** @type google.maps.Map */ (null))
  const [directionsResponse, setDirectionsResponse] = useState(null)
  const [distance, setDistance] = useState('')
  const [duration, setDuration] = useState('')

  /** @type React.MutableRefObject<HTMLInputElement> */
  const originRef = useRef()
  /** @type React.MutableRefObject<HTMLInputElement> */
  const destiantionRef = useRef()

  if (!isLoaded) {
    return <SkeletonText />
  }

  async function calculateRoute() {
    if (originRef.current.value === '' || destiantionRef.current.value === '') {
      return
    }
    // eslint-disable-next-line no-undef
    const directionsService = new google.maps.DirectionsService()
    const results = await directionsService.route({
      origin: originRef.current.value,
      destination: destiantionRef.current.value,
      // eslint-disable-next-line no-undef
      travelMode: google.maps.TravelMode.DRIVING,
    })
    setDirectionsResponse(results)
    setDistance(results.routes[0].legs[0].distance.text)
    setDuration(results.routes[0].legs[0].duration.text)
  }

  function clearRoute() {
    setDirectionsResponse(null)
    setDistance('')
    setDuration('')
    originRef.current.value = ''
    destiantionRef.current.value = ''
  }

  return (
    <Flex
      position='relative'
      flexDirection='column'
      alignItems='center'
      h='100vh'
      w='100vw'
    >
      <Box position='absolute' left={0} top={0} h='100%' w='100%'>
        {/* Google Map Box */}
        <GoogleMap
          center={center}
          zoom={15}
          mapContainerStyle={{ width: '100%', height: '100%' }}
          options={{
            zoomControl: false,
            streetViewControl: false,
            mapTypeControl: false,
            fullscreenControl: false,
          }}
          onLoad={map => setMap(map)}
        >
          <Marker position={center} />
          {directionsResponse && (
            <DirectionsRenderer directions={directionsResponse} options={{
              draggable:true,
              polylineOptions: {
                strokeOpacity: 12,
                strokeColor: "#1641a6",
                strokeWeight: 12,
              },
            }}
            onDirectionsChanged = {() => {
              console.log("Start latitiude ",directionsResponse.routes[0].legs[0].start_location.lat())
              console.log("Start longitude ",directionsResponse.routes[0].legs[0].start_location.lng())
            }} />

          )}
        </GoogleMap>
      </Box>
      <Box
        p={4}
        borderRadius='lg'
        m={4}
        bgColor='white'
        shadow='base'
        minW='container.md'
        zIndex='1'
      >
        <HStack spacing={2} justifyContent='space-between'>
          <Box flexGrow={1}>
            <Autocomplete>
              <Input type='text' placeholder='Origin' ref={originRef} />
            </Autocomplete>
          </Box>
          <Box flexGrow={1}>
            <Autocomplete>
              <Input
                type='text'
                placeholder='Destination'
                ref={destiantionRef}
              />
            </Autocomplete>
          </Box>

          <ButtonGroup>
            <Button colorScheme='pink' type='submit' onClick={calculateRoute}>
              Calculate Route
            </Button>
            <IconButton
              aria-label='center back'
              icon={<FaTimes />}
              onClick={clearRoute}
            />
          </ButtonGroup>
        </HStack>
        <HStack spacing={4} mt={4} justifyContent='space-between'>
          <Text>Distance: {distance} </Text>
          <Text>Duration: {duration} </Text>
          <IconButton
            aria-label='center back'
            icon={<FaLocationArrow />}
            isRound
            onClick={() => {
              map.panTo(center)
              map.setZoom(15)
            }}
          />
        </HStack>
      </Box>
    </Flex>
  )
}

export default App


问:
Spring beans creation
What is the difference between @Component and @Beans in @Configuration classes? Which one should I use?

I tried both ways: in any way I can get singleton beans or bean factories (e.g. prototype scope). The app works correctly in any solution, so i guess this question is a matter of architecture.

Title: Spring beans creation


问:
Dynamic Progress Bar
I have a dynamic progress bar function I made to use in a debugging application. Everything works as intended but I need help condensing the code to be more efficient.

```<code>def progress_bar(current_value, **kwargs):
    top_left_border = u'\u2554'.encode('utf-8')
    top_right_border = u'\u2557'.encode('utf-8')
    bottom_left_border = u'\u255A'.encode('utf-8')
    bottom_right_border = u'\u255D'.encode('utf-8')
    horizontal_border = u'\u2550'.encode('utf-8')
    vertical_border = u'\u2551'.encode('utf-8')
    color_border = '\33[38;5;3m'
    color_fg = '\33[38;5;4m'
    color_bg = '\33[48;5;4m'
    color_inverted_fg = '\33[38;5;0m'
    color_end = '\33[0m'

    b_val = int(current_value)
    b_width = 50
    b_max = 100
    b_min = 0
    for k, v in kwargs.items():
        if k.lower() == 'width': b_width = v
        elif k.lower() == 'max': b_max = v
        elif k.lower() == 'min': b_min = v
        elif k.lower() == 'fg':
            if 0 <= v <= 255:
                color_fg = '\33[38;5;{}m'.format(v)
        elif k.lower() == 'bg':
            if 0 <= v <= 255:
                color_bg = '\33[48;5;{}m'.format(v)
        elif k.lower() == 'reverse':
            if 0 <= v <= 255:
                color_inverted_fg = '\33[38;5;{}m'.format(v)
        elif k.lower() == 'border':
            if 0 <= v <= 255:
                color_border = '\33[38;5;{}m'.format(v)

    if b_min >= b_max:
        print color('Minimum value cannot be greater than or equal to maximum value.', 'red')
        return
    if b_val < b_min: b_val = b_min
    if b_val > b_max: b_val = b_max
    if b_width < 10: b_width = 10

    # top border
    print color_border + top_left_border + horizontal_border * (b_width - 2) + top_right_border + color_end

    # progress bar fill count, percentage string and starting position of string
    fill_cnt = int(round(float(b_val - b_min) / (b_max - b_min) * (b_width - 2)))     # filled spaces
    fill_pct = str(int(round((float(b_val - b_min) / (b_max - b_min)) * 100))) + '%'  # % string
    pct_pos = int(round((b_width - 2) / 2) - round((len(fill_pct) / 2) - 1))          # start position of %

    # build the percentage bar string & percentage text
    b_bar = color_border + vertical_border + color_end

    if fill_cnt >= pct_pos:
        # if filled bar position ends after start of text
        num_dig = pct_pos - 1  # number of spaces before text
        b_bar += color_bg + ' ' * num_dig + color_end
        if fill_cnt < pct_pos + len(fill_pct):
            # if filled bar ends within text block
            num_dig = fill_cnt - pct_pos + 1  # how many digits of text are filled
            b_bar += color_bg + color_inverted_fg + fill_pct[:num_dig] + color_end
            b_bar += color_fg + fill_pct[num_dig:] + color_end  # unfilled text digits after
            num_dig = (b_width - 2) - (pct_pos + len(fill_pct) - 1)  # blank spaces after text
            b_bar += color_fg + ' ' * num_dig + color_border + vertical_border + color_end
        else:
            # if the filled bar position ends after the end of text
            b_bar += color_bg + color_inverted_fg + fill_pct + color_end  # percentage text
            num_dig = fill_cnt - (pct_pos + len(fill_pct) - 1)  # filled bar positions after end of text
            b_bar += color_bg + ' ' * num_dig + color_end
            num_dig = (b_width - 2) - fill_cnt  # number of blanks after filled bar
            b_bar += color_fg + ' ' * num_dig + color_border + vertical_border + color_end
    else:
        # if the filled bar position end before start of text
        b_bar += color_bg + ' ' * fill_cnt + color_end  # filled bar spaces
        num_dig = pct_pos - fill_cnt - 1  # blanks after fill & before start of text
        b_bar += color_fg + ' ' * num_dig + fill_pct + color_end
        num_dig = (b_width - 2) - (pct_pos + len(fill_pct) - 1)  # blanks after end of text
        b_bar += color_fg + ' ' * num_dig + color_border + vertical_border + color_end
    print b_bar

    # bottom border
    print color_border + bottom_left_border + horizontal_border * (b_width - 2) + bottom_right_border + color_end
</code>```

Usage: progress_bar(value, **kwargs)
kwargs: width=50, max=100, min=0, fg=foreground color index, bg=background color index, reverse=foreground color index of inverted text, border=color index of border

kwargs are optional.

I was unable to streamline the code and had to make 3 separate cases to handle different lengths of the filled progress bar.

Side note: this is on a work computer so I only have access to the standard library and cannot use some modules such as tkinter. I am also limited to Python 2.7.15

Title: Dynamic Progress Bar

Body:
I have a dynamic progress bar function I made to use in a debugging application. Everything works as intended but I need help condensing the code to be more efficient.

def progress_bar(current_value, **kwargs):
    top_left_border = u'\u2554'.encode('utf-8')
    top_right_border = u'\u2557'.encode('utf-8')
    bottom_left_border = u'\u255A'.encode('utf-8')
    bottom_right_border = u'\u255D'.encode('utf-8')
    horizontal_border = u'\u2550'.encode('utf-8')
    vertical_border = u'\u2551'.encode('utf-8')
    color_border = '\33[38;5;3m'
    color_fg = '\33[38;5;4m'
    color_bg = '\33[48;5;4m'
    color_inverted_fg = '\33[38;5;0m'
    color_end = '\33[0m'

    b_val = int(current_value)
    b_width = 50
    b_max = 100
    b_min = 0
    for k, v in kwargs.items():
        if k.lower() == 'width': b_width = v
        elif k.lower() == 'max': b_max = v
        elif k.lower() == 'min': b_min = v
        elif k.lower() == 'fg':
            if 0 <= v <= 255:
                color_fg = '\33[38;5;{}m'.format(v)
        elif k.lower() == 'bg':
            if 0 <= v <= 255:
                color_bg = '\33[48;5;{}m'.format(v)
        elif k.lower() == 'reverse':
            if 0 <= v <= 255:
                color_inverted_fg = '\33[38;5;{}m'.format(v)
        elif k.lower() == 'border':
            if 0 <= v <= 255:
                color_border = '\33[38;5;{}m'.format(v)

    if b_min >= b_max:
        print color('Minimum value cannot be greater than or equal to maximum value.', 'red')
        return
    if b_val < b_min: b_val = b_min
    if b_val > b_max: b_val = b_max
    if b_width < 10: b_width = 10

    # top border
    print color_border + top_left_border + horizontal_border * (b_width - 2) + top_right_border + color_end

    # progress bar fill count, percentage string and starting position of string
    fill_cnt = int(round(float(b_val - b_min) / (b_max - b_min) * (b_width - 2)))     # filled spaces
    fill_pct = str(int(round((float(b_val - b_min) / (b_max - b_min)) * 100))) + '%'  # % string
    pct_pos = int(round((b_width - 2) / 2) - round((len(fill_pct) / 2) - 1))          # start position of %

    # build the percentage bar string & percentage text
    b_bar = color_border + vertical_border + color_end

    if fill_cnt >= pct_pos:
        # if filled bar position ends after start of text
        num_dig = pct_pos - 1  # number of spaces before text
        b_bar += color_bg + ' ' * num_dig + color_end
        if fill_cnt < pct_pos + len(fill_pct):
            # if filled bar ends within text block
            num_dig = fill_cnt - pct_pos + 1  # how many digits of text are filled
            b_bar += color_bg + color_inverted_fg + fill_pct[:num_dig] + color_end
            b_bar += color_fg + fill_pct[num_dig:] + color_end  # unfilled text digits after
            num_dig = (b_width - 2) - (pct_pos + len(fill_pct) - 1)  # blank spaces after text
            b_bar += color_fg + ' ' * num_dig + color_border + vertical_border + color_end
        else:
            # if the filled bar position ends after the end of text
            b_bar += color_bg + color_inverted_fg + fill_pct + color_end  # percentage text
            num_dig = fill_cnt - (pct_pos + len(fill_pct) - 1)  # filled bar positions after end of text
            b_bar += color_bg + ' ' * num_dig + color_end
            num_dig = (b_width - 2) - fill_cnt  # number of blanks after filled bar
            b_bar += color_fg + ' ' * num_dig + color_border + vertical_border + color_end
    else:
        # if the filled bar position end before start of text
        b_bar += color_bg + ' ' * fill_cnt + color_end  # filled bar spaces
        num_dig = pct_pos - fill_cnt - 1  # blanks after fill & before start of text
        b_bar += color_fg + ' ' * num_dig + fill_pct + color_end
        num_dig = (b_width - 2) - (pct_pos + len(fill_pct) - 1)  # blanks after end of text
        b_bar += color_fg + ' ' * num_dig + color_border + vertical_border + color_end
    print b_bar

    # bottom border
    print color_border + bottom_left_border + horizontal_border * (b_width - 2) + bottom_right_border + color_end

Usage: progress_bar(value, **kwargs)
kwargs: width=50, max=100, min=0, fg=foreground color index, bg=background color index, reverse=foreground color index of inverted text, border=color index of border

kwargs are optional.

I was unable to streamline the code and had to make 3 separate cases to handle different lengths of the filled progress bar.

Side note: this is on a work computer so I only have access to the standard library and cannot use some modules such as tkinter. I am also limited to Python 2.7.15


问:
in svelte , how to access a env variable in dev environment?
I have a project created by   npx degit sveltejs/template myapp

And I added a .env.local  at the top level that contains
VITE_ARWEAVE_PROTOCOL=http

(I also tried .env file)

in  app.svelte  script section,   why does this fail :

```<code>    protocol=import.meta.env.VITE_ARWEAVE_PROTOCOL;
</code>```

This is the error === App.svelte:3 Uncaught TypeError: Cannot read properties of undefined (reading 'VITE_ARWEAVE_PROTOCOL')

Is this the right wiki: env variable   ?

What in the world am I missing?

Body:
I have a project created by   npx degit sveltejs/template myapp

And I added a .env.local  at the top level that contains
VITE_ARWEAVE_PROTOCOL=http

(I also tried .env file)

in  app.svelte  script section,   why does this fail :

    protocol=import.meta.env.VITE_ARWEAVE_PROTOCOL;

This is the error === App.svelte:3 Uncaught TypeError: Cannot read properties of undefined (reading 'VITE_ARWEAVE_PROTOCOL')

Is this the right wiki: env variable   ?

What in the world am I missing?


问:
How to implement dash graph inorder to prevent resizing when using a smaller screen
I've been stuck with this problem for a while now. Basically I'm trying to create a dashboard using dash and plotly to display stock histories together with useful indicators and a Backtesting function. The data itself is not the problem but because I'm new to dash and css/html I still have trouble to wrap my head around the concept of the app layout.

My final goal would be to have a simple dashboard with the sidebar feature on the left and three graphs on the right. The stock graph and the indicator graph are next to each other on the first row and the graph with the backtest should then below those two graphs and span over the whole surface of the content space.

Useful Screenshots to further understand my problem

Display on my laptop monitor

Display on my monitor

In summary I've two major flaws that I'm stuck with

What do I have to change in order to display the graphs and the sidebar without the overlap. I know that the problem lays in the style attributes of the individual components but no matter how I change them they never fit into the forseen space

I'm working on a 34 inch curved monitor, but when I open the same app on my laptop the problem which I just described gets even worse. Is there a way to implement the style attribute of the dcc and dbc elements so that it doesn't resize but simply scales down to avoid the overlap of the graphs and dash components on the side

I'll post my code so that you guys might get a better understanding on what I'm trying to achieve

```<code>app = Dash(external_stylesheets=[dbc.themes.FLATLY])

sidebar = html.Div(
    [dbc.Row(
        [
            html.Div([
                html.P('Select a time range for the Analysis',
                       style={'margin-top': '14px', 'margin-left': '0px'}),

                dcc.DatePickerRange(id="date-Picker",
                                    min_date_allowed=dt(2017, 1, 1),
                                    max_date_allowed=dt(2022, 12, 31),
                                    calendar_orientation="vertical",
                                    initial_visible_month=dt(2022, 12, 1),
                                    start_date=dt(2021, 12, 31),
                                    end_date=dt(2022, 12, 30))

            ]

            )
        ], style={"height": "10vh"},
        className='bg-primary text-white font-italic'
    ),
        dbc.Row(
            [
                html.Div([
                    html.P('Select a Ticker from the List',
                                    style={'margin-top': '15px', 'margin-left': '24px'}),

                             dcc.Dropdown(
                                 id="dropdown-Ticker",
                                 options=["META", "MSFT", "SHEL", "TTE", "XOM", "TSLA"],
                                 value="MSFT",
                                 placeholder="Select a ticker from the list",
                                 multi=False,
                                 style={'color': 'black'}
                             ),

                    html.P('Select an Indicator from the List',
                                    style={'margin-top': '8px', 'margin-left': '24px'}),
                             dcc.Dropdown(

                                 id="dropdown-Indicator",
                                 options=["RSI", "Stochastic Oscilator", "EMA", "Sentiment Analysis", "WILLR", "MACD"],
                                 placeholder="Select a Indicator from the list",
                                 multi=False,
                                 value="Stochastic Oscilator",
                                 style={'color': 'black'}
                             ),
                    html.P('Indicator Input',
                                    style={'margin-top': '8px', 'margin-left': '24px'}),
                             html.Div([dcc.Input(id="Long Window",
                                                 type="number",
                                                 placeholder="Input the Long Window",
                                                 value=15,
                                                 required=True,
                                                 min=0,
                                                 style={"display": "block"}),

                                       dcc.Input(id="Short Window",
                                                 type="number",
                                                 placeholder="Input the Short Window",
                                                 required=True,
                                                 value=3,
                                                 min=0,
                                                 style={"margin-left": "15px", "display": "block"}),
                                       dcc.Input(id="MACD Sig",
                                                 type="number",
                                                 placeholder="Input the MACD Signal length",
                                                 required=True,
                                                 value=3,
                                                 min=0,
                                                 style={"margin-left": "15px", "display": "None"})
                                       ])

                ])],
            style={"height": "70vh"},
            className='bg-primary text-white font-italic'
        ),
        dbc.Row(
            [

            ]
        )

    ]
)

content = html.Div(
    [
        dbc.Row(
            [
                dbc.Col(
                    [
                        html.Div([
                            html.P('Graph with Ticker', id="Ticker-Chart"),
                            dcc.Graph(id="line-graph")
                        ])],
                    className='bg-white'
                ),
                dbc.Col(
                    [
                        html.P('Indicator'),
                        dcc.Graph(id="Indicator-Graph")
                    ],
                    className='bg-dark text-white'
                )
            ],
            style={"height": "60vh",
                   'margin-top': '0px', 'margin-left': '8px',
                   'margin-bottom': '8px', 'margin-right': '8px'}),
        dbc.Row(
            [
                dbc.Col(
                    [
                        html.P('Backtesting Ratios'),
                        dcc.Graph(id= "Backtesting-Graph")
                    ],
                    className='bg-light'
                )
            ],
            style={"height": "40vh", 'margin-left': '8px'}
        )
    ]
)
app.layout = dbc.Container(
    [
        html.H1('Analysis of Stock Market', id="header", style={'color': 'black'}),
        dbc.Row(
            [
                dbc.Col(sidebar, width=2, className='bg-primary'),
                dbc.Col(content, width=10)
            ],

        ),
    ],
    fluid=True
)
</code>```

Let me know if you also need the callback functions to get a better understanding of the code

Body:
I've been stuck with this problem for a while now. Basically I'm trying to create a dashboard using dash and plotly to display stock histories together with useful indicators and a Backtesting function. The data itself is not the problem but because I'm new to dash and css/html I still have trouble to wrap my head around the concept of the app layout.

My final goal would be to have a simple dashboard with the sidebar feature on the left and three graphs on the right. The stock graph and the indicator graph are next to each other on the first row and the graph with the backtest should then below those two graphs and span over the whole surface of the content space.

Useful Screenshots to further understand my problem

Display on my laptop monitor

Display on my monitor

In summary I've two major flaws that I'm stuck with

What do I have to change in order to display the graphs and the sidebar without the overlap. I know that the problem lays in the style attributes of the individual components but no matter how I change them they never fit into the forseen space

I'm working on a 34 inch curved monitor, but when I open the same app on my laptop the problem which I just described gets even worse. Is there a way to implement the style attribute of the dcc and dbc elements so that it doesn't resize but simply scales down to avoid the overlap of the graphs and dash components on the side

I'll post my code so that you guys might get a better understanding on what I'm trying to achieve

app = Dash(external_stylesheets=[dbc.themes.FLATLY])

sidebar = html.Div(
    [dbc.Row(
        [
            html.Div([
                html.P('Select a time range for the Analysis',
                       style={'margin-top': '14px', 'margin-left': '0px'}),

                dcc.DatePickerRange(id="date-Picker",
                                    min_date_allowed=dt(2017, 1, 1),
                                    max_date_allowed=dt(2022, 12, 31),
                                    calendar_orientation="vertical",
                                    initial_visible_month=dt(2022, 12, 1),
                                    start_date=dt(2021, 12, 31),
                                    end_date=dt(2022, 12, 30))

            ]

            )
        ], style={"height": "10vh"},
        className='bg-primary text-white font-italic'
    ),
        dbc.Row(
            [
                html.Div([
                    html.P('Select a Ticker from the List',
                                    style={'margin-top': '15px', 'margin-left': '24px'}),

                             dcc.Dropdown(
                                 id="dropdown-Ticker",
                                 options=["META", "MSFT", "SHEL", "TTE", "XOM", "TSLA"],
                                 value="MSFT",
                                 placeholder="Select a ticker from the list",
                                 multi=False,
                                 style={'color': 'black'}
                             ),

                    html.P('Select an Indicator from the List',
                                    style={'margin-top': '8px', 'margin-left': '24px'}),
                             dcc.Dropdown(

                                 id="dropdown-Indicator",
                                 options=["RSI", "Stochastic Oscilator", "EMA", "Sentiment Analysis", "WILLR", "MACD"],
                                 placeholder="Select a Indicator from the list",
                                 multi=False,
                                 value="Stochastic Oscilator",
                                 style={'color': 'black'}
                             ),
                    html.P('Indicator Input',
                                    style={'margin-top': '8px', 'margin-left': '24px'}),
                             html.Div([dcc.Input(id="Long Window",
                                                 type="number",
                                                 placeholder="Input the Long Window",
                                                 value=15,
                                                 required=True,
                                                 min=0,
                                                 style={"display": "block"}),

                                       dcc.Input(id="Short Window",
                                                 type="number",
                                                 placeholder="Input the Short Window",
                                                 required=True,
                                                 value=3,
                                                 min=0,
                                                 style={"margin-left": "15px", "display": "block"}),
                                       dcc.Input(id="MACD Sig",
                                                 type="number",
                                                 placeholder="Input the MACD Signal length",
                                                 required=True,
                                                 value=3,
                                                 min=0,
                                                 style={"margin-left": "15px", "display": "None"})
                                       ])

                ])],
            style={"height": "70vh"},
            className='bg-primary text-white font-italic'
        ),
        dbc.Row(
            [

            ]
        )

    ]
)

content = html.Div(
    [
        dbc.Row(
            [
                dbc.Col(
                    [
                        html.Div([
                            html.P('Graph with Ticker', id="Ticker-Chart"),
                            dcc.Graph(id="line-graph")
                        ])],
                    className='bg-white'
                ),
                dbc.Col(
                    [
                        html.P('Indicator'),
                        dcc.Graph(id="Indicator-Graph")
                    ],
                    className='bg-dark text-white'
                )
            ],
            style={"height": "60vh",
                   'margin-top': '0px', 'margin-left': '8px',
                   'margin-bottom': '8px', 'margin-right': '8px'}),
        dbc.Row(
            [
                dbc.Col(
                    [
                        html.P('Backtesting Ratios'),
                        dcc.Graph(id= "Backtesting-Graph")
                    ],
                    className='bg-light'
                )
            ],
            style={"height": "40vh", 'margin-left': '8px'}
        )
    ]
)
app.layout = dbc.Container(
    [
        html.H1('Analysis of Stock Market', id="header", style={'color': 'black'}),
        dbc.Row(
            [
                dbc.Col(sidebar, width=2, className='bg-primary'),
                dbc.Col(content, width=10)
            ],

        ),
    ],
    fluid=True
)

Let me know if you also need the callback functions to get a better understanding of the code


问:
shutil.copy() throwing up invalid argument error when repeating
I'm seeing some very odd behavior with shutil's copy method.

Here is my basic code:

def time_and_log(func):
    def inner_function(*args,**kwargs):
        times = np.array([])
        repititions = kwargs.pop("repititions",1)
        for i in range(repititions):
            print(f"i: {i}")
            start_time = time.perf_counter()
            logfile = func(*args,**kwargs)
            end_time = time.perf_counter()
            elapsed_time = end_time - start_time
            times = np.append(times,elapsed_time)
            #Other stuff ommitted here, but basically just logging to a file
    return inner_function

@time_and_log
def copy(src,dst,logfile,repititions=1):
    if Path(src).is_dir():
        shutil.copytree(src,dst)
    else:
        #I originally didn't have this but I thought the existence of the file was blocking it somehow?
        if os.path.isfile(dst):
            os.remove(dst)
        shutil.copy(src,dst)
    return logfile
```
<p>the time_and_log decorator just takes the number of repetitions and loops it that many times and then does some custom formatting and logging.</p>
<p>I'm writing to a mounted file system via WSL2, the first iteration of the loop it runs, fine, then the second iteration of the loop returns an error:</p>
```OSError: [Errno 22] Invalid argument: '\\\\wsl.localhost\\\\Ubuntu\\\\home\\\\me\\\\mountpoint\\\\myfile.bin'
```
<p>But then I can take that exact argument and do this:</p>
<pre class="lang-py prettyprint-override"><code>shutil.copy(src,'\\\\wsl.localhost\\\\Ubuntu\\\\home\\\\me\\\\mountpoint\\\\myfile.bin')
</code>```

and that works.

I'm kind of baffled. Anyone know why this is happening?

Here's the code to recreate it

```<code>LOG_FILE = "log.txt"
REPS = 5
dst = r"\\wsl.localhost\\Ubuntu\\home\\me\\mountpoint\\"
src_path = ".\\anypath\\"
test_file = "myfile.bin"

copy(src=src_path+test_file,dst=dst+test_file,logfile=LOG_FILE,repititions=REPS)

</code>```

For clarity, the reason I'm doing this is I'm testing performance for different methods to mount to azure storage, blobfuse vs smb file share vs NFSv3 vs RClone

Body:
I'm seeing some very odd behavior with shutil's copy method.

Here is my basic code:

def time_and_log(func):
    def inner_function(*args,**kwargs):
        times = np.array([])
        repititions = kwargs.pop("repititions",1)
        for i in range(repititions):
            print(f"i: {i}")
            start_time = time.perf_counter()
            logfile = func(*args,**kwargs)
            end_time = time.perf_counter()
            elapsed_time = end_time - start_time
            times = np.append(times,elapsed_time)
            #Other stuff ommitted here, but basically just logging to a file
    return inner_function

@time_and_log
def copy(src,dst,logfile,repititions=1):
    if Path(src).is_dir():
        shutil.copytree(src,dst)
    else:
        #I originally didn't have this but I thought the existence of the file was blocking it somehow?
        if os.path.isfile(dst):
            os.remove(dst)
        shutil.copy(src,dst)
    return logfile

the time_and_log decorator just takes the number of repetitions and loops it that many times and then does some custom formatting and logging.

I'm writing to a mounted file system via WSL2, the first iteration of the loop it runs, fine, then the second iteration of the loop returns an error:

OSError: [Errno 22] Invalid argument: '\\\\wsl.localhost\\\\Ubuntu\\\\home\\\\me\\\\mountpoint\\\\myfile.bin'

But then I can take that exact argument and do this:

shutil.copy(src,'\\\\wsl.localhost\\\\Ubuntu\\\\home\\\\me\\\\mountpoint\\\\myfile.bin')

and that works.

I'm kind of baffled. Anyone know why this is happening?

Here's the code to recreate it

LOG_FILE = "log.txt"
REPS = 5
dst = r"\\wsl.localhost\\Ubuntu\\home\\me\\mountpoint\\"
src_path = ".\\anypath\\"
test_file = "myfile.bin"

copy(src=src_path+test_file,dst=dst+test_file,logfile=LOG_FILE,repititions=REPS)

For clarity, the reason I'm doing this is I'm testing performance for different methods to mount to azure storage, blobfuse vs smb file share vs NFSv3 vs RClone


问:
Internal error not handled System.InvalidOperationException at System.Data.OracleClient.OracleConnection.CheckError
I have a web application and I am getting an error related to oracle.

System.InvalidOperationException Internal error not handled (-2)
at System.Data.OracleClient.OracleConnection.CheckError()

This is the scenario.

sql1

```<code>select * from table1@otheroracledb
</code>```

sql2

```<code>select * from table2
</code>```

I am getting this error when I run the sql1 and then sql2.

What could be the problem?

Body:
I have a web application and I am getting an error related to oracle.

System.InvalidOperationException Internal error not handled (-2)
at System.Data.OracleClient.OracleConnection.CheckError()

This is the scenario.

sql1

select * from table1@otheroracledb

sql2

select * from table2

I am getting this error when I run the sql1 and then sql2.

What could be the problem?


问:
Remove TinyMCE toolbar buttons
Link Options GearI am a novice and not a programmer. I'm building a website in WordPress and Elementor. I intend to have many users who will be adding and editing their posts. I have created the necessary forms using the Frontend Admin plugin. The problem that I'm having is using the TinyMCE WYSIWYG editor for the comments field; it shows a link button which, when clicked, has an options gear that brings up a popup that gives my users way too much access to areas that I don't want them to have.Link Options Popup How can I disable the options gear or simply remove the link button? I have searched the internet and found many plugins that don't work. There is lots of help, but not being a programmer, I can't figure out how to use the help or where to paste the code samples. I know this might seem rather lame to you, but I can't go live with my site until I find a solution that I can use as a novice. Please help me.

I have searched the internet and found many plugins that don't work. There is lots of help, but not being a programmer, I can't figure out how to use. There are lots of code customizations that don't explain how to use or where to paste. The Frontend Admin plugin can't help because it is part of the TinyMCE editor.

Title: Remove TinyMCE toolbar buttons


问:
PRESTO cannot unnest type: varchar
I have data in a string field without any delimiters and I need to split it out so I can discover the data more clearly. The data in the string looks like this:
{7 items
actionType:"Create"
propertyStatus:"active"
feature:"EID"
hotelID:"23131303"
userCode:"Alexandre Giard"
providerStatus:"active"
statusCode:"Created"
}
and I need to be able to get individual columns for actionType, propertyStatus, feature, hotelID, userCode, providerStatus, statusCode
if have tried cross join unnest and cross join unnest with cast(json()) and several other things and nothing works.

I tried split, but because the only delimiter is the colon, it just splits the single field into a single fields with the colon removed and the data all run together.
I will continue to search the web for information, but if anyone else has run into this situation and has a solution, I would really appreciate some assistance.
I also tried this:

select  expe_property_id
    , eventdate
     , eventname
       , split_part(t.value, ':', 1)
       , split_part(t.value, ':', 2)
from bexg_prod_project_arm_report.apm_bulk
    CROSS JOIN UNNEST(eventdata) AS t(value)
```

and got the error message "CANNOT UNNEST TYPE: VARCHAR"

Title: PRESTO cannot unnest type: varchar

Body:
I have data in a string field without any delimiters and I need to split it out so I can discover the data more clearly. The data in the string looks like this:
{7 items
actionType:"Create"
propertyStatus:"active"
feature:"EID"
hotelID:"23131303"
userCode:"Alexandre Giard"
providerStatus:"active"
statusCode:"Created"
}
and I need to be able to get individual columns for actionType, propertyStatus, feature, hotelID, userCode, providerStatus, statusCode
if have tried cross join unnest and cross join unnest with cast(json()) and several other things and nothing works.

I tried split, but because the only delimiter is the colon, it just splits the single field into a single fields with the colon removed and the data all run together.
I will continue to search the web for information, but if anyone else has run into this situation and has a solution, I would really appreciate some assistance.
I also tried this:

select  expe_property_id
    , eventdate
     , eventname
       , split_part(t.value, ':', 1)
       , split_part(t.value, ':', 2)
from bexg_prod_project_arm_report.apm_bulk
    CROSS JOIN UNNEST(eventdata) AS t(value)

and got the error message "CANNOT UNNEST TYPE: VARCHAR"


问:
Can CheckboxTreeView create horizontal CheckButtons?
I am trying to use CheckboxTreeView from ttkWidgets and so far I am able to create Checkbuttons using the insert command. However, the number of check buttons are pretty lengthy (got about 30 of them ). I would like to have them horizontally stacked ( 5 per row ) so that the number of lines of checkbuttons are reduced to 6.

Is there anyway of doing this? I don't see the option of stacking buttons horizontally in CheckboxTreeView.

Thanks

I have tried grid as well as inserting Checkbutton inside "CheckboxTreeView". I have no success.

Here is my code :

```<code>from ttkwidgets import CheckboxTreeview, Table
import tkinter as tk
from tkinter import IntVar

root = tk.Tk()

tree = CheckboxTreeview(root)
tree.pack()
t = Table(root, drag_cols=True, drag_rows=True)

tree.insert("", "end", "1", text="1", values = ('1','2'))
tree.insert("1", "end", "11", text="11")
tree.insert("1", "end", "12",  text="12")
tree.insert("1", "end", "13",  text="13")
tree.insert("1", "end", "14",  text="14")
tree.insert("1", "end", "15",  text="15")
tree.insert("1", "end", "16",  text="16")
tree.insert("1", "end", "17",  text="17")
tree.insert("1", "end", "18",  text="18")
tree.insert("1", "end", "19",  text="19")
tree.insert("1", "end", "20",  text="20")
tree.insert("1", "end", "21",  text="21")

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

Is there a way to make these Checkbuttons horizontally aligned?

Body:
I am trying to use CheckboxTreeView from ttkWidgets and so far I am able to create Checkbuttons using the insert command. However, the number of check buttons are pretty lengthy (got about 30 of them ). I would like to have them horizontally stacked ( 5 per row ) so that the number of lines of checkbuttons are reduced to 6.

Is there anyway of doing this? I don't see the option of stacking buttons horizontally in CheckboxTreeView.

Thanks

I have tried grid as well as inserting Checkbutton inside "CheckboxTreeView". I have no success.

Here is my code :

from ttkwidgets import CheckboxTreeview, Table
import tkinter as tk
from tkinter import IntVar

root = tk.Tk()

tree = CheckboxTreeview(root)
tree.pack()
t = Table(root, drag_cols=True, drag_rows=True)

tree.insert("", "end", "1", text="1", values = ('1','2'))
tree.insert("1", "end", "11", text="11")
tree.insert("1", "end", "12",  text="12")
tree.insert("1", "end", "13",  text="13")
tree.insert("1", "end", "14",  text="14")
tree.insert("1", "end", "15",  text="15")
tree.insert("1", "end", "16",  text="16")
tree.insert("1", "end", "17",  text="17")
tree.insert("1", "end", "18",  text="18")
tree.insert("1", "end", "19",  text="19")
tree.insert("1", "end", "20",  text="20")
tree.insert("1", "end", "21",  text="21")

root.mainloop()

Is there a way to make these Checkbuttons horizontally aligned?


问:
set a schema in SQLAlchemy without hardcoding it on an entity
I am using SQLAlchemy to interact with a PostgreSQL db.

My database has a schema called my_schema

I am aware that I can hardcode the schema name on the entity using __table_args__ like so:

```<code>Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    __table_args__ = {'schema': 'my_schema'}
    id = Column(Integer, primary_key=True)
    name = Column(String)
</code>```

However, I would like to be able to pass the schema name as a command line argument instead of hardcoding it on the class of the entity.
How can I do that?

Body:
I am using SQLAlchemy to interact with a PostgreSQL db.

My database has a schema called my_schema

I am aware that I can hardcode the schema name on the entity using __table_args__ like so:

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    __table_args__ = {'schema': 'my_schema'}
    id = Column(Integer, primary_key=True)
    name = Column(String)

However, I would like to be able to pass the schema name as a command line argument instead of hardcoding it on the class of the entity.
How can I do that?


问:
VS Code create a costume parameters info popup
On VS Code, is it possible to create a xml/json to show information about functions/commands? Something like the following image. How can I do it?

I tried to find the correct name for this, I believe its called "Quick info and parameter info" or Suggestions Popup.

All I can find is about how to create snippets. But what I need is a way to show information about commands, for example when the user write read_data and press TAB it will show a popup info:

```<code>read_data --> -----------------------------------------------
              | Parameters: -from_sensor -from_file -random |
              |Description: Command used to read data from..|
              -----------------------------------------------
</code>```

Note: I don't have access to the commands code, so I can't write documentation (docstrings) directly on the command code.

Thanks in advance.

Body:
On VS Code, is it possible to create a xml/json to show information about functions/commands? Something like the following image. How can I do it?

I tried to find the correct name for this, I believe its called "Quick info and parameter info" or Suggestions Popup.

All I can find is about how to create snippets. But what I need is a way to show information about commands, for example when the user write read_data and press TAB it will show a popup info:

read_data --> -----------------------------------------------
              | Parameters: -from_sensor -from_file -random |
              |Description: Command used to read data from..|
              -----------------------------------------------

Note: I don't have access to the commands code, so I can't write documentation (docstrings) directly on the command code.

Thanks in advance.


问:
How to refactor components into a new component?
New to React and started doing Fullstack's web dev course, but currently stumped on exercise 1.8 in Part 1/the React section. It tells me to refactor the statistics (which are Display, DisplayTotal, DisplayTotalScore and DisplayPositive) into a single, new component called Statistics, but I've written these statistic displays as components. Since writing components inside another is discouraged, what approach should I take in refactoring?

Here is what my code looks like:

```<code>import { useState } from 'react'

const Button = (props) => (
  <button onClick={props.handleClick}>
    {props.text}
  </button>
)

  const Display = (props) => (
    <div>
      {props.text}: {props.value}
    </div>
  )

  const DisplayTotal = ({total}) => (
    <div>
      Total clicks: {total}
    </div>
  )

  const DisplayTotalScore = ({total, totalScore}) => {
    let average = totalScore/total
    if(total == 0) {
      average = 0
    }
    //console.log(`Total: ${total} Total Score: ${totalScore} Average Score: ${average}`)
    return(
      <div>
      Average Score: {average}
    </div>
    )
  }

  const DisplayPositive = ({total, posPercent}) => {
    let positiveAvg = (posPercent/total) * 100
    if(total == 0) {
      positiveAvg = 0
    }
    return(
      <div>
        Positive Score Average: {positiveAvg}
      </div>
    )
  }

const App = () => {
  // save clicks of each button to its own state
  const [good, setGood] = useState(0)
  const [neutral, setNeutral] = useState(0)
  const [bad, setBad] = useState(0)
  const [total, setTotal] = useState(0)
  const [totalScore, setTotalScore] = useState(0)
  const [posPercent, setPosPrecent] = useState(0)

  const Count = (setVal, value, total, totalScore, posPercent) => {
      setVal(value)
      setTotal(total+1)
      setTotalScore(totalScore)
      setPosPrecent(posPercent)
}

  const Reset = (setGood, setNeutral, setBad) => (
    setGood(0),
    setNeutral(0),
    setBad(0),
    setPosPrecent(0),
    setTotalScore(0)
  )

  return (
    <div>
      <Button handleClick={()=> Count(setGood, good+1, total, totalScore+1, posPercent+1)} text='Good'/>
      <Button handleClick={()=> Count(setNeutral, neutral+1, total, totalScore, posPercent)} text='Neutral'/>
      <Button handleClick={()=> Count(setBad, bad+1, total, totalScore-1, posPercent)} text='Bad'/>

      <Display value={good} text='Good'/>
      <Display value={neutral} text='Neutral'/>
      <Display value={bad} text='Bad'/>

      <Button handleClick={()=> Reset(setGood, setNeutral, setBad, setPosPrecent, setTotalScore)} text='Reset'/>
      <DisplayTotal total={total}/>
      <DisplayTotalScore totalScore={totalScore} total={total}/>
      <DisplayPositive total={total} posPercent={posPercent} />
    </div>
  )
}

export default App

</code>```

I tried putting these components inside a new one, but it didn't work out

Body:
New to React and started doing Fullstack's web dev course, but currently stumped on exercise 1.8 in Part 1/the React section. It tells me to refactor the statistics (which are Display, DisplayTotal, DisplayTotalScore and DisplayPositive) into a single, new component called Statistics, but I've written these statistic displays as components. Since writing components inside another is discouraged, what approach should I take in refactoring?

Here is what my code looks like:

import { useState } from 'react'

const Button = (props) => (
  <button onClick={props.handleClick}>
    {props.text}
  </button>
)

  const Display = (props) => (

      {props.text}: {props.value}

  )

  const DisplayTotal = ({total}) => (

      Total clicks: {total}

  )

  const DisplayTotalScore = ({total, totalScore}) => {
    let average = totalScore/total
    if(total == 0) {
      average = 0
    }
    //console.log(`Total: ${total} Total Score: ${totalScore} Average Score: ${average}`)
    return(

      Average Score: {average}

    )
  }

  const DisplayPositive = ({total, posPercent}) => {
    let positiveAvg = (posPercent/total) * 100
    if(total == 0) {
      positiveAvg = 0
    }
    return(

        Positive Score Average: {positiveAvg}

    )
  }

const App = () => {
  // save clicks of each button to its own state
  const [good, setGood] = useState(0)
  const [neutral, setNeutral] = useState(0)
  const [bad, setBad] = useState(0)
  const [total, setTotal] = useState(0)
  const [totalScore, setTotalScore] = useState(0)
  const [posPercent, setPosPrecent] = useState(0)

  const Count = (setVal, value, total, totalScore, posPercent) => {
      setVal(value)
      setTotal(total+1)
      setTotalScore(totalScore)
      setPosPrecent(posPercent)
}

  const Reset = (setGood, setNeutral, setBad) => (
    setGood(0),
    setNeutral(0),
    setBad(0),
    setPosPrecent(0),
    setTotalScore(0)
  )

  return (

      <Button handleClick={()=> Count(setGood, good+1, total, totalScore+1, posPercent+1)} text='Good'/>
      <Button handleClick={()=> Count(setNeutral, neutral+1, total, totalScore, posPercent)} text='Neutral'/>
      <Button handleClick={()=> Count(setBad, bad+1, total, totalScore-1, posPercent)} text='Bad'/>

      <Display value={good} text='Good'/>
      <Display value={neutral} text='Neutral'/>
      <Display value={bad} text='Bad'/>

      <Button handleClick={()=> Reset(setGood, setNeutral, setBad, setPosPrecent, setTotalScore)} text='Reset'/>
      <DisplayTotal total={total}/>
      <DisplayTotalScore totalScore={totalScore} total={total}/>
      <DisplayPositive total={total} posPercent={posPercent} />

  )
}

export default App

I tried putting these components inside a new one, but it didn't work out


问:
Create n-dimensional array with singletons on all but one dimension
I want to create a vector that runs along the N'th dimension of an M-dimensional array.

Example:
Given a vector

```<code>x = np.random.rand(10)
array([0.095, 0.079, 0.202, 0.905, 0.644,
   0.786 , 0.359, 0.830, 0.874, 0.053 ])
</code>```

Now, if M==4 and N==0, then we want simply

```<code>y = x[:,np.newaxis,np.newaxis,np.newaxis]
</code>```

For N==1, we want

```<code>y = x[ np.newaxis, : , np.newaxis,np.newaxis]
</code>```

For N==2, we want

```<code>y = x[ np.newaxis, np.newaxis, : , np.newaxis]
</code>```

and so on. I tried the following:

```<code>dims = [ np.newaxis ] * M
dims[N] = ':'                # ??
y = x[ *dims ]
</code>```

But you can't unpack an array into square brackets -- and the string ':' seems quite wrong.  Note that I can do this in Matlab something like this:

```<code>dims = repmat( { 1 }, N, 1 )
dims{end} = ':'
y( dims{:} ) = x
</code>```

because the cell dims unpacks to integers and a string ':', which is somehow understood.

Another way to do it in Matlab is

```<code>dims = ones(M)
dims(N) = 10
y = zeros( dims )
y(:) = x          # preserves shape of y
</code>```

but the numpy analogue fails

```<code>ValueError: could not broadcast input array from shape (10,) into shape (1,1,10,1)
</code>```

Body:
I want to create a vector that runs along the N'th dimension of an M-dimensional array.

Example:
Given a vector

x = np.random.rand(10)
array([0.095, 0.079, 0.202, 0.905, 0.644,
   0.786 , 0.359, 0.830, 0.874, 0.053 ])

Now, if M==4 and N==0, then we want simply

y = x[:,np.newaxis,np.newaxis,np.newaxis]

For N==1, we want

y = x[ np.newaxis, : , np.newaxis,np.newaxis]

For N==2, we want

y = x[ np.newaxis, np.newaxis, : , np.newaxis]

and so on. I tried the following:

dims = [ np.newaxis ] * M
dims[N] = ':'                # ??
y = x[ *dims ]

But you can't unpack an array into square brackets -- and the string ':' seems quite wrong.  Note that I can do this in Matlab something like this:

dims = repmat( { 1 }, N, 1 )
dims{end} = ':'
y( dims{:} ) = x

because the cell dims unpacks to integers and a string ':', which is somehow understood.

Another way to do it in Matlab is

dims = ones(M)
dims(N) = 10
y = zeros( dims )
y(:) = x          # preserves shape of y

but the numpy analogue fails

ValueError: could not broadcast input array from shape (10,) into shape (1,1,10,1)


问:
why user in AuthContext store previes user not te one from argumentd?
loginUser is corret while user contains data from previouse call, May it be connected with returning useContext(AuthContext)

```<code>import React, { useReducer,useState,useContext,useEffect, createContext} from "react";
import jwtDecode from "jwt-decode";
export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState();

const login = async(loginUser)=>{

    localStorage.setItem("token", loginUser.token);

    console.log(loginUser.name);

   await setUser(loginUser);

    console.log(user.name);
};

return(
<AuthContext.Provider value={{ user, login, logout}}>
{children}
</AuthContext.Provider>);
};
export  const useAuthValue = () => {
    return  useContext(AuthContext);
   };
</code>```

is there a better way to stor user

Body:
loginUser is corret while user contains data from previouse call, May it be connected with returning useContext(AuthContext)

import React, { useReducer,useState,useContext,useEffect, createContext} from "react";
import jwtDecode from "jwt-decode";
export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState();

const login = async(loginUser)=>{

    localStorage.setItem("token", loginUser.token);

    console.log(loginUser.name);

   await setUser(loginUser);

    console.log(user.name);
};

return(
<AuthContext.Provider value={{ user, login, logout}}>
{children}
</AuthContext.Provider>);
};
export  const useAuthValue = () => {
    return  useContext(AuthContext);
   };

is there a better way to stor user


问:
Converting rows into the columns in Pandas, Python
I have a data set that includes patients and medical analysis data about them. One of my features is showing that what kind of analysis has been done on patient and there is 129 unique values. Also, there is a date column and result of the analysis column at the same time. You can see my data set below.

```<code>
    DATE      ANALYSIS     RESULT

04/06/2020     D-Dímero     863
04/06/2020     RDW              13.0
04/06/2020         Sódio        134
04/06/2020       Eosinófilos        1.3
04/06/2020   Uréia              24
</code>```

In that point, all the data I show you above is belong to a patient. What I want to do is, taking all the "ANALYSIS" row  values and convert them into a column value. At the same time, creating an another column that shows the result of the spesific analysis(for example, "sodio_result" column for the sodio analysis). But as you see, dates are the same. What I exactly want to do is taking one patient's data and show them in only one row.

Also, there is my expected output for the first row of my example data:

```<code>DATE        D-DİMERO_RESULT  Sodio_ANALYSIS   RDW_ANALYSIS
04/06/2020      863                134            13.0
</code>```

Body:
I have a data set that includes patients and medical analysis data about them. One of my features is showing that what kind of analysis has been done on patient and there is 129 unique values. Also, there is a date column and result of the analysis column at the same time. You can see my data set below.

    DATE      ANALYSIS     RESULT

04/06/2020     D-Dímero     863
04/06/2020     RDW              13.0
04/06/2020         Sódio        134
04/06/2020       Eosinófilos        1.3
04/06/2020   Uréia              24

In that point, all the data I show you above is belong to a patient. What I want to do is, taking all the "ANALYSIS" row  values and convert them into a column value. At the same time, creating an another column that shows the result of the spesific analysis(for example, "sodio_result" column for the sodio analysis). But as you see, dates are the same. What I exactly want to do is taking one patient's data and show them in only one row.

Also, there is my expected output for the first row of my example data:

DATE        D-DİMERO_RESULT  Sodio_ANALYSIS   RDW_ANALYSIS
04/06/2020      863                134            13.0


问:
Using fread and rbind.fill to read and combine unique values only in R
I would like to read a number of large csv files and bind them but only combine the unique values as there are duplicates that appear across different files.

Previously I used read.csv following by rbind but this was very slow.

I am now using:

```<code>files <- list.files('C:/Users/Michael/documents')
df <- rbind.fill(lapply(files, fread, header=TRUE))
</code>```

Each file contains about 300,000 records and there are approx. 15 files bringing the total to about 4m records.

Once complete, I use:

```<code>df <- df[!duplicated(df$UniqueID), ]
</code>```

which reduces the number of records to approx. 3m.

My questions:

How can I rbind only the unique values and thus eliminate the last step in the process?

Is this the most efficient and fastest way to complete this task?

It seems that I have to set the workig directory just prior to running the above otherwise I get this error:

File "file name" does not exist or is non-readable.

Body:
I would like to read a number of large csv files and bind them but only combine the unique values as there are duplicates that appear across different files.

Previously I used read.csv following by rbind but this was very slow.

I am now using:

files <- list.files('C:/Users/Michael/documents')
df <- rbind.fill(lapply(files, fread, header=TRUE))

Each file contains about 300,000 records and there are approx. 15 files bringing the total to about 4m records.

Once complete, I use:

df <- df[!duplicated(df$UniqueID), ]

which reduces the number of records to approx. 3m.

My questions:

How can I rbind only the unique values and thus eliminate the last step in the process?

Is this the most efficient and fastest way to complete this task?

It seems that I have to set the workig directory just prior to running the above otherwise I get this error:

File "file name" does not exist or is non-readable.


问:
How do you perform "entity splitting" to fluently map multiple tables to a single entity based on a single key?
I am upgrading a legacy ASP.NET 4.7.2 tenant-aware application from the ASP.NET Membership framework to the ASP.NET Identity framework. I have two tables, Users and UserProfile. Users contains the bulk of the data for authentication via Identity and whatever is being carried over from the Membership data. UserProfile contains my custom user data, including to which tenant they belong. Both tables contain a GUID/UniqueIdentifier UserId field ("UserId" in the Users table, and "UserID" in the UserProfile table) and there is a one to one relationship between these two tables. For every UserId that exists in Users, there is an equal UserID that exists in UserProfile linking the custom profile data.

For my application-specific derivative of IdentityUser model, I want it to pull all of the fields from the Users table and the TenantId field from the UserProfile table. But I get the following exception:

System.InvalidOperationException : Properties for type 'ApplicationUser' can only be mapped once. The non-key property 'UserName' is mapped more than once. Ensure the Properties method specifies each non-key property only once.

Please see below for the OnModelCreating method of my ApplicationIdentityDbContext:

```<code>        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var userEntity = modelBuilder.Entity<ApplicationUser>();

            userEntity.Map(m =>
            {
                m.Properties(e => new
                {
                    e.UserName,
                    e.PasswordHash,
                    e.SecurityStamp,
                    e.EmailConfirmed,
                    e.PhoneNumber,
                    e.PhoneNumberConfirmed,
                    e.TwoFactorEnabled,
                    e.LockoutEndDateUtc,
                    e.LockoutEnabled,
                    e.AccessFailedCount,
                    e.Email,
                    e.ApplicationId,
                    e.IsAnonymous,
                    e.LastActivityDate,
                    e.LastLockoutDate,
                    e.LastPasswordChangedDate,
                    e.CreateDate
                });

                m.ToTable("Users");
            });

            userEntity.Map(m =>
            {
                m.Properties(e => new
                {
                    e.TenantId
                });
                m.ToTable("UserProfile");
            });

            userEntity.HasKey(u => u.Id)
                .Property(u => u.Id)
                .HasColumnName("UserId")
                .IsRequired();
            userEntity.Property(u => u.UserName)
                .HasColumnName("UserName")
                .IsRequired()
                .HasMaxLength(64)
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 1 }));
            userEntity.Property(u => u.PasswordHash)
                .HasColumnName("PasswordHash")
                .IsOptional();
            userEntity.Property(u => u.SecurityStamp)
                .HasColumnName("SecurityStamp")
                .IsOptional();
            userEntity.Property(u => u.EmailConfirmed)
                .HasColumnName("EmailConfirmed")
                .IsRequired();
            userEntity.Property(u => u.PhoneNumber)
                .HasColumnName("PhoneNumber")
                .IsOptional()
                .HasMaxLength(128);
            userEntity.Property(u => u.PhoneNumberConfirmed)
                .HasColumnName("PhoneNumberConfirmed")
                .IsRequired();
            userEntity.Property(u => u.TwoFactorEnabled)
                .HasColumnName("TwoFactorEnabled")
                .IsRequired();
            userEntity.Property(u => u.LockoutEndDateUtc)
                .HasColumnName("LockoutEndDateUtc")
                .IsOptional();
            userEntity.Property(u => u.LockoutEnabled)
                .HasColumnName("LockoutEnabled")
                .IsRequired();
            userEntity.Property(u => u.AccessFailedCount)
                .HasColumnName("AccessFailedCount")
                .IsRequired();
            userEntity.Property(u => u.Email)
                .HasColumnName("Email")
                .IsOptional()
                .HasMaxLength(256);
            userEntity.Property(u => u.ApplicationId)
                .HasColumnName("ApplicationId")
                .IsRequired();
            userEntity.Property(u => u.IsAnonymous)
                .HasColumnName("IsAnonymous")
                .IsRequired();
            userEntity.Property(u => u.LastActivityDate)
                .HasColumnName("LastActivityDate")
                .IsRequired();
            userEntity.Property(u => u.LastLockoutDate)
                .HasColumnName("LastLockoutDate")
                .IsOptional();
            userEntity.Property(u => u.LastPasswordChangedDate)
                .HasColumnName("LastPasswordChangedDate")
                .IsRequired();
            userEntity.Property(u => u.CreateDate)
                .HasColumnName("CreateDate")
                .IsRequired();
            userEntity.Property(u => u.TenantId)
                .HasColumnName("TenantId")
                .IsRequired()
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 2 }));

            userEntity.HasMany(u => u.Claims)
                .WithRequired()
                .HasForeignKey(uc => uc.UserId);
            userEntity.HasMany(u => u.Logins)
                .WithRequired()
                .HasForeignKey(ul => ul.UserId);
            userEntity.HasMany(u => u.Roles)
                .WithRequired()
                .HasForeignKey(ur => ur.UserId);
        }
</code>```

How can I fix my model creation code to avoid this exception and properly perform entity splitting?

Body:
I am upgrading a legacy ASP.NET 4.7.2 tenant-aware application from the ASP.NET Membership framework to the ASP.NET Identity framework. I have two tables, Users and UserProfile. Users contains the bulk of the data for authentication via Identity and whatever is being carried over from the Membership data. UserProfile contains my custom user data, including to which tenant they belong. Both tables contain a GUID/UniqueIdentifier UserId field ("UserId" in the Users table, and "UserID" in the UserProfile table) and there is a one to one relationship between these two tables. For every UserId that exists in Users, there is an equal UserID that exists in UserProfile linking the custom profile data.

For my application-specific derivative of IdentityUser model, I want it to pull all of the fields from the Users table and the TenantId field from the UserProfile table. But I get the following exception:

System.InvalidOperationException : Properties for type 'ApplicationUser' can only be mapped once. The non-key property 'UserName' is mapped more than once. Ensure the Properties method specifies each non-key property only once.

Please see below for the OnModelCreating method of my ApplicationIdentityDbContext:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var userEntity = modelBuilder.Entity<ApplicationUser>();

            userEntity.Map(m =>
            {
                m.Properties(e => new
                {
                    e.UserName,
                    e.PasswordHash,
                    e.SecurityStamp,
                    e.EmailConfirmed,
                    e.PhoneNumber,
                    e.PhoneNumberConfirmed,
                    e.TwoFactorEnabled,
                    e.LockoutEndDateUtc,
                    e.LockoutEnabled,
                    e.AccessFailedCount,
                    e.Email,
                    e.ApplicationId,
                    e.IsAnonymous,
                    e.LastActivityDate,
                    e.LastLockoutDate,
                    e.LastPasswordChangedDate,
                    e.CreateDate
                });

                m.ToTable("Users");
            });

            userEntity.Map(m =>
            {
                m.Properties(e => new
                {
                    e.TenantId
                });
                m.ToTable("UserProfile");
            });

            userEntity.HasKey(u => u.Id)
                .Property(u => u.Id)
                .HasColumnName("UserId")
                .IsRequired();
            userEntity.Property(u => u.UserName)
                .HasColumnName("UserName")
                .IsRequired()
                .HasMaxLength(64)
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 1 }));
            userEntity.Property(u => u.PasswordHash)
                .HasColumnName("PasswordHash")
                .IsOptional();
            userEntity.Property(u => u.SecurityStamp)
                .HasColumnName("SecurityStamp")
                .IsOptional();
            userEntity.Property(u => u.EmailConfirmed)
                .HasColumnName("EmailConfirmed")
                .IsRequired();
            userEntity.Property(u => u.PhoneNumber)
                .HasColumnName("PhoneNumber")
                .IsOptional()
                .HasMaxLength(128);
            userEntity.Property(u => u.PhoneNumberConfirmed)
                .HasColumnName("PhoneNumberConfirmed")
                .IsRequired();
            userEntity.Property(u => u.TwoFactorEnabled)
                .HasColumnName("TwoFactorEnabled")
                .IsRequired();
            userEntity.Property(u => u.LockoutEndDateUtc)
                .HasColumnName("LockoutEndDateUtc")
                .IsOptional();
            userEntity.Property(u => u.LockoutEnabled)
                .HasColumnName("LockoutEnabled")
                .IsRequired();
            userEntity.Property(u => u.AccessFailedCount)
                .HasColumnName("AccessFailedCount")
                .IsRequired();
            userEntity.Property(u => u.Email)
                .HasColumnName("Email")
                .IsOptional()
                .HasMaxLength(256);
            userEntity.Property(u => u.ApplicationId)
                .HasColumnName("ApplicationId")
                .IsRequired();
            userEntity.Property(u => u.IsAnonymous)
                .HasColumnName("IsAnonymous")
                .IsRequired();
            userEntity.Property(u => u.LastActivityDate)
                .HasColumnName("LastActivityDate")
                .IsRequired();
            userEntity.Property(u => u.LastLockoutDate)
                .HasColumnName("LastLockoutDate")
                .IsOptional();
            userEntity.Property(u => u.LastPasswordChangedDate)
                .HasColumnName("LastPasswordChangedDate")
                .IsRequired();
            userEntity.Property(u => u.CreateDate)
                .HasColumnName("CreateDate")
                .IsRequired();
            userEntity.Property(u => u.TenantId)
                .HasColumnName("TenantId")
                .IsRequired()
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 2 }));

            userEntity.HasMany(u => u.Claims)
                .WithRequired()
                .HasForeignKey(uc => uc.UserId);
            userEntity.HasMany(u => u.Logins)
                .WithRequired()
                .HasForeignKey(ul => ul.UserId);
            userEntity.HasMany(u => u.Roles)
                .WithRequired()
                .HasForeignKey(ur => ur.UserId);
        }

How can I fix my model creation code to avoid this exception and properly perform entity splitting?


问:
Keep getting "TypeError: Cannot perform 'getPrototypeOf' when i console.log the state on redux-toolkit
I am new to using redux-tool kit. I am trying to map through the orders and set the order as confirmed when the button is clicked on. So far i am just trying to view the state before looping through it. But every time i click the confirm order button  i keep getting this error message
TypeError: Cannot perform 'getPrototypeOf'

I am really not sure what I am doing wrong. I have added the link to my sandbox

https://codesandbox.io/s/vibrant-hugle-ioo2nb?file=/redux/store.js

```<code>Below is the code i am having issues with. Any help would be really appreciated
import { createSlice } from "@reduxjs/toolkit";

const orders = createSlice({
  name: "orders",
  initialState: [
    { id: 1, name: "Pizza", is_confirmed: "0" },
    { id: 2, name: "Hamburher", is_confirmed: "0" }
  ],
  reducers: {
    addToOrders: (state, action) => {
      console.log(action.payload);
      state.concat(action.payload);
    },

    confirmOrder: (state, action) => {
      const { id } = action.payload;
      console.log(id);

       console.log(state,"state"); // Error happens here

      return state;

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

Body:
I am new to using redux-tool kit. I am trying to map through the orders and set the order as confirmed when the button is clicked on. So far i am just trying to view the state before looping through it. But every time i click the confirm order button  i keep getting this error message
TypeError: Cannot perform 'getPrototypeOf'

I am really not sure what I am doing wrong. I have added the link to my sandbox

https://codesandbox.io/s/vibrant-hugle-ioo2nb?file=/redux/store.js

Below is the code i am having issues with. Any help would be really appreciated
import { createSlice } from "@reduxjs/toolkit";

const orders = createSlice({
  name: "orders",
  initialState: [
    { id: 1, name: "Pizza", is_confirmed: "0" },
    { id: 2, name: "Hamburher", is_confirmed: "0" }
  ],
  reducers: {
    addToOrders: (state, action) => {
      console.log(action.payload);
      state.concat(action.payload);
    },

    confirmOrder: (state, action) => {
      const { id } = action.payload;
      console.log(id);

       console.log(state,"state"); // Error happens here

      return state;

    }
  }
});


问:
WordPress. how to use wp_enqueue_script to dynamic code script or style
Create a block of code dynamically, where the content uses a variable.

The hpcs reports that I need to use wp_enqueue_script, it was understood that it is used to import a file, but since the content of the block is not dynamic, what is the best way to implement it?

code example:

```<code>$html .= '<script type="text/javascript">
            (function() { $MTS.openChk({ url: "' . esc_url( $url ) . '", mode: "automatic" }); })();
          </script>';
</code>```

Error-

```<code>Scripts must be registered/enqueued via wp_enqueue_script
</code>```

Body:
Create a block of code dynamically, where the content uses a variable.

The hpcs reports that I need to use wp_enqueue_script, it was understood that it is used to import a file, but since the content of the block is not dynamic, what is the best way to implement it?

code example:

$html .= '';

Error-

Scripts must be registered/enqueued via wp_enqueue_script


问:
How should I stop and analyze requests before blocking them in webRequest.OnBeforeRequest?
I'm trying to build a dyi adblock, that instead of just blocking ads, it first analyzes them based on their URL structure and their provided response from a fetch request
I'm using this as my starting point: https://github.com/AdrS/dyi-adblocker
I have a huge list of URLs and using webRequest.OnBeforeRequest to stop each request from that ad URL list and block them.
In the middle, I would like to first do a GET request to the stopped URL, get it's response, analyze everything and determine if it should be blocked or not.

I tried doing everything on a Google Chrome extension, based on thst github. But it seems to not be possible due to the listener not waiting for the fetch request (too async) + I'm getting "max stack size reached" errors. I searched for info on the internet and found out that it is somehow possible with a Mozilla Firefox extension, but couldn't find a solution.
Basically the steps should be:

Have a listener webRequest.OnBeforeRequest to stop requests from the urls in the list given.

fetch the URL's response

Analyze the URL's structure

Analyze the response

Calculate results
6.1. If results are positive, allow the request to go through
6.2. If results are negative, block the request

Speed is not an issue, it can even load for websites for minutes if needed, as this would be a small simple prototype.

Does anyone know a solution? Both Chrome and Firefox extension solutions work, as long as I can stall the webRequest.OnBeforeRequest (or anything else) for as long as I want until I do the needed analysis.

Any code examples and links to documentations are appreciated!