问:
device frame is not visible even when I enable it in chrome developer tools
I can't see any frames! I tried to disable and re-enable it but the result was the same btw I'm new and maybe it's a silly question to ask! sorry.

I have toggled between all the options but nothing happened.


来源: stackexchange

问:
How to make express-session work on a cross-site setup (Cannot set a cookie from the backend to the frontend)?
How to make express-session work on a cross-site setup (Cannot set a cookie from the backend to the frontend)?

I created a test app as I am having a hard time finding ways to set cookies to the front end. When I try to set sameSite: 'none' and cookie: true, I cannot find the cookie in the header. But when I set the cookie to false and remove the sameSite, The cookie was in the header but it was blocked and i am getting an error such as I should set the sameSite=none and secure to true. The website is deployed at render.com.

The link of the react looks like this
https://react-websiteName-2d0w.onrender.com

The link of the server looks like this
https://api-websiteName-hj7g.onrender.com

```<code>//server
const express = require("express");
const cors = require("cors");
const sessions = require('express-session');
const app = express();

const PORT = 3001;

app.use(express.json());
app.use(cors({
    origin: 'https://react-websiteName-2d0w.onrender.com',
    methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
    credentials: true
}));

const oneDay = 1000 * 60 * 60 * 24;
app.use(sessions({
    secret: "secret",
    saveUninitialized: true,
    cookie: {
        httpOnly: true,
        secure: true,
        maxAge: oneDay,
        sameSite:'none'
    },
    resave: false
}));

app.post('/createSession', (req, res) => {
    req.session.user = req.body.user;
    res.send('new session is created');
});

app.listen(PORT, () => {
    console.log(`The server is running on port ${PORT}`);
});

//react app
import { useEffect } from 'react';
import Axios from 'axios';
import './App.css';
import axios from 'axios';

const App = () => {
  axios.defaults.withCredentials = true;
  useEffect(() => {
    Axios.post('https://api-websiteName-hj7g.onrender.com/createSession',
      { user: "user" }
    );
  }, []);

  return (
    <div>
      <h1>Check if there is a cookie</h1>
    </div>
  );
}

export default App;
</code>```

I am trying to make express-session work on my project when deployed with different domian.
Are there better alternatives or methods that could work in render.com instead of express-session?

ContentLicense: CC BY-SA 4.0

Body:
How to make express-session work on a cross-site setup (Cannot set a cookie from the backend to the frontend)?

I created a test app as I am having a hard time finding ways to set cookies to the front end. When I try to set sameSite: 'none' and cookie: true, I cannot find the cookie in the header. But when I set the cookie to false and remove the sameSite, The cookie was in the header but it was blocked and i am getting an error such as I should set the sameSite=none and secure to true. The website is deployed at render.com.

The link of the react looks like this
https://react-websiteName-2d0w.onrender.com

The link of the server looks like this
https://api-websiteName-hj7g.onrender.com

//server
const express = require("express");
const cors = require("cors");
const sessions = require('express-session');
const app = express();

const PORT = 3001;

app.use(express.json());
app.use(cors({
    origin: 'https://react-websiteName-2d0w.onrender.com',
    methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
    credentials: true
}));

const oneDay = 1000 * 60 * 60 * 24;
app.use(sessions({
    secret: "secret",
    saveUninitialized: true,
    cookie: {
        httpOnly: true,
        secure: true,
        maxAge: oneDay,
        sameSite:'none'
    },
    resave: false
}));

app.post('/createSession', (req, res) => {
    req.session.user = req.body.user;
    res.send('new session is created');
});

app.listen(PORT, () => {
    console.log(`The server is running on port ${PORT}`);
});

//react app
import { useEffect } from 'react';
import Axios from 'axios';
import './App.css';
import axios from 'axios';

const App = () => {
  axios.defaults.withCredentials = true;
  useEffect(() => {
    Axios.post('https://api-websiteName-hj7g.onrender.com/createSession',
      { user: "user" }
    );
  }, []);

  return (

Check if there is a cookie

  );
}

export default App;

I am trying to make express-session work on my project when deployed with different domian.
Are there better alternatives or methods that could work in render.com instead of express-session?


问:
Signature comes out in table format
When using the code below with the getboiler function i retireve the signature in table format. I have in the .htmlbody included a table earlier in the code. Have you experienced this problem before or know how to solve it?:

```<code>Dim SigString As String
Dim Signature As String

SigString = Environ("appdata") & _
            "\Microsoft\Signatures\1.Lundbeck all details.htm"

If Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString)
Else
    Signature = ""
End If
On Error Resume Next
</code>```

EDIT: I have added the code behind stableheads and stabledata below if this helps. I can not seem to find the direct issue.

```<code>Dim NameList As Range
Set NameList = Range("A2", Range("a2").End(xlDown))

'Table header.
Dim iColumnsCount, iColCnt As Integer
Dim sTableHeads As String
iColumnsCount = Worksheets("").UsedRange.Columns.Count

For iColCnt = 1 To iColumnsCount
'Table header concatenated with HTML <th> tags.
    If (sTableHeads) = "" Then
        sTableHeads = "<th>" & Worksheets("").Cells(1, iColCnt) & "
   </th>"
       Else
        sTableHeads = sTableHeads & "<th>" & Worksheets("").Cells(1,
    iColCnt) & "</th>"
    End If
  Next iColCnt

'The list of names in excel sheet

'For Name = 1 To NameList.Count
 For Name = 2 To 4

' Table data.

 Dim iRowsCount, iRows As Integer
 Dim sTableData As String
 iRowsCount = Worksheets("").Rows.Count

 sTableData = "<tr>"
 For iColCnt = 1 To iColumnsCount
    If (sTableData) = "" Then
        sTableData = Worksheets("").Cells(Name, iColCnt) & "</td>"
     Else
        sTableData = sTableData & "<td>" & Worksheets("").Cells(Name,
  iColCnt) & "</td>"
    End If
Next iColCnt

sTableData = sTableData & "</tr>"
    Dim sTableStyle As String
sTableStyle = "<style> table.edTable { width: 75%; font: 18px calibri; } table, table.edTable th, table.edTable td { border: solid 1px #000000; border-collapse: collapse; padding: 3px; text-align: center; } table.edTable td { background-color: #ffffff; color: #000000; font-size: 14px; } table.edTable th { background-color : #ffffff; color: #000000; } tr:hover td { background-color: #000000; color: #ffffff; } </style>"

Set EItem = EApp.CreateItem(0)

With EItem

    .To = Worksheets("").Cells(Name, 8)

    .CC = ""
    .Subject = " " & Worksheets("").Cells(Name, 2)
    .HTMLbody = "Dear " & Worksheets("").Cells(Name, 9) & "," & "
     <br>" & "<br>" _
                & "" & "<br>" & "<br>" _
                & "T" & "(" & Date & ")" & "" & "<br>" & "<br>" _
                & "<b></b>" & "<br>" _
                & "" & "<br>" & "<br>" _
                & "<b></b>" & "<br>" _
                & ""
 & "<br>" & "<br>" _
                & "" & "<br>" _
                & "<b></b>" & "<br>" _
                & ":"
 & "<br>" & "<br>" _
                & sTableStyle & "<table class='edTable'><tr>" &
  sTableHeads & "</tr>" & _
                       "<tr>" & sTableData & "</tr></table>" & "<br>" &
  "<br>" _
                & "" & "<br>" & "<br>" _
                & Signature
        .Display
</code>```

Title: Signature comes out in table format

Body:
When using the code below with the getboiler function i retireve the signature in table format. I have in the .htmlbody included a table earlier in the code. Have you experienced this problem before or know how to solve it?:

Dim SigString As String
Dim Signature As String

SigString = Environ("appdata") & _
            "\Microsoft\Signatures\1.Lundbeck all details.htm"

If Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString)
Else
    Signature = ""
End If
On Error Resume Next

EDIT: I have added the code behind stableheads and stabledata below if this helps. I can not seem to find the direct issue.

Dim NameList As Range
Set NameList = Range("A2", Range("a2").End(xlDown))

'Table header.
Dim iColumnsCount, iColCnt As Integer
Dim sTableHeads As String
iColumnsCount = Worksheets("").UsedRange.Columns.Count

For iColCnt = 1 To iColumnsCount
'Table header concatenated with HTML  tags.
    If (sTableHeads) = "" Then
        sTableHeads = "" & Worksheets("").Cells(1, iColCnt) & "
   	"
       Else
        sTableHeads = sTableHeads & "" & Worksheets("").Cells(1,
    iColCnt) & "	"
    End If
  Next iColCnt

'The list of names in excel sheet

'For Name = 1 To NameList.Count
 For Name = 2 To 4

' Table data.

 Dim iRowsCount, iRows As Integer
 Dim sTableData As String
 iRowsCount = Worksheets("").Rows.Count

 sTableData = "
"
 For iColCnt = 1 To iColumnsCount
    If (sTableData) = "" Then
        sTableData = Worksheets("").Cells(Name, iColCnt) & "	"
     Else
        sTableData = sTableData & "" & Worksheets("").Cells(Name,
  iColCnt) & "	"
    End If
Next iColCnt

sTableData = sTableData & "
"
    Dim sTableStyle As String
sTableStyle = ""

Set EItem = EApp.CreateItem(0)

With EItem

    .To = Worksheets("").Cells(Name, 8)

    .CC = ""
    .Subject = " " & Worksheets("").Cells(Name, 2)
    .HTMLbody = "Dear " & Worksheets("").Cells(Name, 9) & "," & "

" & "
" _
                & "" & "
" & "
" _
                & "T" & "(" & Date & ")" & "" & "
" & "
" _
                & "" & "
" _
                & "" & "
" & "
" _
                & "" & "
" _
                & ""
 & "
" & "
" _
                & "" & "
" _
                & "" & "
" _
                & ":"
 & "
" & "
" _
                & sTableStyle & "

" &
  sTableHeads & "
" & _
                       "
" & sTableData & "

" & "
" &
  "
" _
                & "" & "
" & "
" _
                & Signature
        .Display


问:
Tomcat blocks all requests until initial startup is finished
During the upgrade to Tomcat 10.1 I noticed a behavior causing the initial startup phase to take several minutes. If a web application tries to contact the Tomcat connector during its deployment, the request gets blocked. When no timeout is specified, this will pause the startup process indefinitely.

In order to test this, I created a small WAR using Spring Initializr with a small component:

@Component
public class Initializer {

    @Autowired
    public Initializer() {
        System.out.println("Init!");
        new RestTemplate().getForObject("http://localhost:8080/", String.class);
    }

}
```

If the resulting WAR file is deployed to a running Tomcat instance, the deployment is done in no time. However, if Tomcat is stopped and started again, it will halt after printing "Init!" on the console.

How can I make certain that my web-app behaves identical regardless if it is deployed on startup or redeployed later?

Body:
During the upgrade to Tomcat 10.1 I noticed a behavior causing the initial startup phase to take several minutes. If a web application tries to contact the Tomcat connector during its deployment, the request gets blocked. When no timeout is specified, this will pause the startup process indefinitely.

In order to test this, I created a small WAR using Spring Initializr with a small component:

@Component
public class Initializer {

    @Autowired
    public Initializer() {
        System.out.println("Init!");
        new RestTemplate().getForObject("http://localhost:8080/", String.class);
    }

}

If the resulting WAR file is deployed to a running Tomcat instance, the deployment is done in no time. However, if Tomcat is stopped and started again, it will halt after printing "Init!" on the console.

How can I make certain that my web-app behaves identical regardless if it is deployed on startup or redeployed later?


问:
for loop with if statement inside to create multiple graphs using ggstatsplot package
I am struggling with my code and I can't figure out which is the actual problem.

Just to give you a bit of context: I am trying to write some code which will help me in performing automatic EDA using the ggstatsplot. I would like to select a target variable in my dataset and on the basis of this, the program has to loop over the remaining columns perfoming different bivariate analysis, depending on the type of variable (it has to use the ggscatterstats if both are numerical, ggbetweenstats if one is a factor and the other is numerical and ggbarstats if both are factors). I am attaching a short db I am using for the experimentations.

how the dataset looks like

The code I am using is the following (let's suppose our target is Upselling hence the code should only procude ggbetweenstats and ggbarstats plots):

```<code>library(ggstatsplot)
</code>```
```<code>df <- dataset
target_var <- dataset$Upselling
</code>```
```<code>for (var in 1:ncol(df)) {
if (is.numeric(df[[var]]) && is.numeric(target_var)) {
plots <- ggscatterstats(data = df, x = var, y = target_var)}
else if (is.numeric(df[[var]]) && is.factor(target_var) || is.factor(df[[var]]) && is.numeric(target_var)) {
plots <- ggbetweenstats(data = df, x = var, y = target_var)}
else {plots <- ggbarstats(data = df, x = var, y = target_var)}
print(plots)
}
</code>```

The error I am getting is the following:

Error in select():
! Can't subset columns that don't exist.
✖ Column var doesn't exist.

Could you please help? Thank you so much

Body:
I am struggling with my code and I can't figure out which is the actual problem.

Just to give you a bit of context: I am trying to write some code which will help me in performing automatic EDA using the ggstatsplot. I would like to select a target variable in my dataset and on the basis of this, the program has to loop over the remaining columns perfoming different bivariate analysis, depending on the type of variable (it has to use the ggscatterstats if both are numerical, ggbetweenstats if one is a factor and the other is numerical and ggbarstats if both are factors). I am attaching a short db I am using for the experimentations.

how the dataset looks like

The code I am using is the following (let's suppose our target is Upselling hence the code should only procude ggbetweenstats and ggbarstats plots):

library(ggstatsplot)

df <- dataset
target_var <- dataset$Upselling

for (var in 1:ncol(df)) {
if (is.numeric(df[[var]]) && is.numeric(target_var)) {
plots <- ggscatterstats(data = df, x = var, y = target_var)}
else if (is.numeric(df[[var]]) && is.factor(target_var) || is.factor(df[[var]]) && is.numeric(target_var)) {
plots <- ggbetweenstats(data = df, x = var, y = target_var)}
else {plots <- ggbarstats(data = df, x = var, y = target_var)}
print(plots)
}

The error I am getting is the following:

Error in select():
! Can't subset columns that don't exist.
✖ Column var doesn't exist.

Could you please help? Thank you so much


问:
How to pass operator's output in .expand() in airflow 2.5
I am currently working with an operator that returns a continuation token. Considering that the operator is called FrOperator and I have a sensor that will take this operator's continuation token FrSensor.

Airflow doesn't seem to be passing the output when providing the `

```<code>expanded_froperator = FrOperator.partial(<FIXED_VALUES>).expand(<SOMETHING>)
expanded_frsensor = FrSensor.partial(<FIXED_VALUES>).expand(expanded_froperator.output)
</code>```

Any idea what am I doing wrong?

expanded_froperator.output seems to be returning a None value in Xcoms causing the dag to be skipped.

Body:
I am currently working with an operator that returns a continuation token. Considering that the operator is called FrOperator and I have a sensor that will take this operator's continuation token FrSensor.

Airflow doesn't seem to be passing the output when providing the `

expanded_froperator = FrOperator.partial(<FIXED_VALUES>).expand(<SOMETHING>)
expanded_frsensor = FrSensor.partial(<FIXED_VALUES>).expand(expanded_froperator.output)

Any idea what am I doing wrong?

expanded_froperator.output seems to be returning a None value in Xcoms causing the dag to be skipped.


问:
Can not resolve the error in vercel regarding grapesjs Error occurred prerendering page "/plugins/testimonials/testimonialblock2"?
I have build the website builder using grapesjs in Next js. The app runs fine at the dev but when i deploy the application on vercel. it gives error.

I have use grapesjs in this application and when i render my grapes js template in my module it gives error on all block.

vercel error:

here is my app structure:

In this i use the plugins i have created and render inside [id].js


问:
Why would using a port number in the Dynamic Ports range be unsuitable for an application?
As stated by IANA when one wants to register a port number and a service name in the User Ports range, one of the requirements from RFC 6335 section 8.1.2 is to have a reason:

"...why using a port number in the Dynamic Ports range is unsuitable for the given application."

as I did not find any given examples for valid reasons I tried to come up with one.

The only reason I can think of is the convenience of expecting your port to be free but since no one is really prevented from using your registered port you can't be sure about that. Therefore one needs to have some mechanic in place to resort to a free port from the Dynamic Ports range anyway. Besides that I don't think convenience is a reason they would accept but since there does not seem to be a list of invalid/inadequate reasons I can't be sure about that either.

Does someone know of a list of example reasons or a single example that was accepted in the past or examples that are inadequate?

What are generally adequate reasons why using a port number in the Dynamic Ports range is unsuitable?


问:
How to override parent in QSortFilterProxyModel?
I have an ObjectTreeModel class that inherits from QAbstractItemModel. The model stores ObjectTreeItem elements that have the _placement property, which is the uuid of another ObjectTreeItem element. I want that if an element has this property, then the ObjectTreeModel::parent() function returns the placement element, not the actual parent of the element and the tree structure changes accordingly. To do this, I redefined parent() in the SortFilterProxyTreeModel proxy model (inherited from QSortFilterProxyModel) of ObjectTreeModel, but as a result, the tree structure does not change. How can I redefine parent()correctly to get the desired result?

Source ObjectTreeModel::parent() function:

QModelIndex ObjectTreeModel::parent(const QModelIndex &index) const
{
    if (!index.isValid())
        return QModelIndex();

    ObjectTreeItem *childItem = getItem(index);
    ObjectTreeItem *parentItem = childItem ? childItem->parent() : nullptr;

    if (parentItem == rootItem || !parentItem)
        return QModelIndex();

    return createIndex(parentItem->childNumber(), 0, parentItem);
}
```
<p>Overridden parent in <code>SortFilterProxyTreeModel</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>QModelIndex SortFilterProxyTreeModel::parent(const QModelIndex &index) const
{
    if (!index.isValid())
        return QModelIndex();

    // get original model
    ObjectTreeModel* treeModel = static_cast< ObjectTreeModel* >( sourceModel() );

    // convert the index from SortFilterProxyTreeModel to ObjectTreeModel
    QModelIndex sourceIndex = mapToSource( index );
    ObjectTreeItem *item = treeModel->getItem(sourceIndex);
    QModelIndex parentIndex;
    // if the uuid placement property exists, then we get its index, otherwise — the real parent.
    // the isPlacementParent variable is needed for optional behavior, by default it is true.
    const QUuid placementUuid = item->payload->_placement.value();
    if( isPlacementParent && !placementUuid.isNull() ) {
        ObjectTreeItem* placementItem = treeModel->items().value( placementUuid );
        parentIndex = treeModel->createThisIndex(placementItem->childNumber(), 0, placementItem);

    } else {
        ObjectTreeItem *parentItem = item ? item->parent() : nullptr;

        if (parentItem == treeModel->rootItem || !parentItem)
            return QModelIndex();

        parentIndex = treeModel->createThisIndex(parentItem->childNumber(), 0, parentItem);
    }
    // convert parentIndex from ObjectTreeModel to SortFilterProxyTreeModel
    return mapFromSource( parentIndex );
}
</code>```

Body:
I have an ObjectTreeModel class that inherits from QAbstractItemModel. The model stores ObjectTreeItem elements that have the _placement property, which is the uuid of another ObjectTreeItem element. I want that if an element has this property, then the ObjectTreeModel::parent() function returns the placement element, not the actual parent of the element and the tree structure changes accordingly. To do this, I redefined parent() in the SortFilterProxyTreeModel proxy model (inherited from QSortFilterProxyModel) of ObjectTreeModel, but as a result, the tree structure does not change. How can I redefine parent()correctly to get the desired result?

Source ObjectTreeModel::parent() function:

QModelIndex ObjectTreeModel::parent(const QModelIndex &index) const
{
    if (!index.isValid())
        return QModelIndex();

    ObjectTreeItem *childItem = getItem(index);
    ObjectTreeItem *parentItem = childItem ? childItem->parent() : nullptr;

    if (parentItem == rootItem || !parentItem)
        return QModelIndex();

    return createIndex(parentItem->childNumber(), 0, parentItem);
}

Overridden parent in SortFilterProxyTreeModel:

QModelIndex SortFilterProxyTreeModel::parent(const QModelIndex &index) const
{
    if (!index.isValid())
        return QModelIndex();

    // get original model
    ObjectTreeModel* treeModel = static_cast< ObjectTreeModel* >( sourceModel() );

    // convert the index from SortFilterProxyTreeModel to ObjectTreeModel
    QModelIndex sourceIndex = mapToSource( index );
    ObjectTreeItem *item = treeModel->getItem(sourceIndex);
    QModelIndex parentIndex;
    // if the uuid placement property exists, then we get its index, otherwise — the real parent.
    // the isPlacementParent variable is needed for optional behavior, by default it is true.
    const QUuid placementUuid = item->payload->_placement.value();
    if( isPlacementParent && !placementUuid.isNull() ) {
        ObjectTreeItem* placementItem = treeModel->items().value( placementUuid );
        parentIndex = treeModel->createThisIndex(placementItem->childNumber(), 0, placementItem);

    } else {
        ObjectTreeItem *parentItem = item ? item->parent() : nullptr;

        if (parentItem == treeModel->rootItem || !parentItem)
            return QModelIndex();

        parentIndex = treeModel->createThisIndex(parentItem->childNumber(), 0, parentItem);
    }
    // convert parentIndex from ObjectTreeModel to SortFilterProxyTreeModel
    return mapFromSource( parentIndex );
}


问:
Angular Lazy Loading throws TypeError: Cannot read properties of undefined (reading 'ɵmod')
I'm trying to route to another module from app-routing module in lazy loading mode but it throws this exception that i cannot debug...

My app-routing.module:

```<code>`{
    path: 'dashboard',
    loadChildren: (): any => {
        import('./dashboard/dashboard-routing.module').then(m => { return m.DashboardRoutingModule })
    },
  },
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
 })
 export class AppRoutingModule {}`
</code>```

My dashboard-routing.module:

```<code>`const routes: Routes = [
  {
    path: '',
    component: DashboardComponent
  },
   {
  path: 'today',
    component: TodayComponent,
  }
];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DashboardRoutingModule {}`
</code>```

I'm expecting to get the dashboard component, I tried to load dashboard.module insted of dashboard-routing.module but nothing.

dashboard.module:

```<code>`@NgModule({
  declarations: [DashboardComponent],
  imports: [DashboardRoutingModule],
  exports: [DashboardComponent]
})
export class DashboardModule{}`
</code>```

Body:
I'm trying to route to another module from app-routing module in lazy loading mode but it throws this exception that i cannot debug...

My app-routing.module:

`{
    path: 'dashboard',
    loadChildren: (): any => {
        import('./dashboard/dashboard-routing.module').then(m => { return m.DashboardRoutingModule })
    },
  },
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
 })
 export class AppRoutingModule {}`

My dashboard-routing.module:

`const routes: Routes = [
  {
    path: '',
    component: DashboardComponent
  },
   {
  path: 'today',
    component: TodayComponent,
  }
];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DashboardRoutingModule {}`

I'm expecting to get the dashboard component, I tried to load dashboard.module insted of dashboard-routing.module but nothing.

dashboard.module:

`@NgModule({
  declarations: [DashboardComponent],
  imports: [DashboardRoutingModule],
  exports: [DashboardComponent]
})
export class DashboardModule{}`


问:
4D data to 2D contour
I have 4D data, each coordinate is independent:
2.76600e+00, -7.85800e+00,  1.40220e+01,  5.56817e+01
I have a long data, 2 millions points

When I plot it I get something like:

But then I can't see anything. so I would like to convert my data to 2D somehow so I can visualize it properly.
Does anyone have any idea what I should do?

Title: 4D data to 2D contour


问:
React Native TabView not working after generating an apk
I am using a TabView from react-native-tab-view, it works fine when when I am running my application with expo and scan the QR Code with my android device, but when I generate an apk and open the application, it does not work.</p>
```<code> return isLoading ? (
    <LoadingComponent />
  ) : person? (
    <TabView
      navigationState={{ index, routes }}
      renderTabBar={renderTabBar}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={{ width: layout.width }}
      style={{ marginBottom: 20 }}
    />
  ) : (
    <View></View>
  )
}
</code>```

Body:
I am using a TabView from react-native-tab-view, it works fine when when I am running my application with expo and scan the QR Code with my android device, but when I generate an apk and open the application, it does not work.

 return isLoading ? (
    <LoadingComponent />
  ) : person? (
    <TabView
      navigationState={{ index, routes }}
      renderTabBar={renderTabBar}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={{ width: layout.width }}
      style={{ marginBottom: 20 }}
    />
  ) : (
    <View></View>
  )
}


问:
use shopify to write a picture similar
I want to use shopify to write a picture similar to apple's official website and turn it into a video-like page after detection by mouse scrolling, but it is not as complex as apple's page. How to do this? Do I need to calculate the height, position elements by calculating the distance, and then calculate the size of the picture? Too many of these pictures, put in the background one by one upload, and then do the mouse interaction effect is not advisable, will certainly occupy the background memory.

I hope to have the guidance of a teacher who has developed shopify template for a second time. Thank you!

Title: use shopify to write a picture similar


问:
I want to know why my gradcam implementation always show me all 0 values
I am using GradCAM with my custom dataset. I am following the codes of https://github.com/jacobgil/pytorch-grad-cam  <-this work
But I always get 0 values when the target layer is layer.4.
My network is pretrained resnet18. I checked there is a signal when it is layer1,2,3. but there was all 0 signal when the target layer was layer4. Below is my gradcam code.

def run_grad_cam_on_image():

```<code>net.eval()
for n_iter,(image,label) in enumerate(cifar100_test_loader):
    image=image.cuda()
    target_layers=[net.layer4]
    cam=GradCAM(net,target_layers=target_layers,use_cuda=True)

    targets=None

    grayscale_cam=cam(input_tensor=image,targets=targets)

    grayscale_cam=grayscale_cam[0,:]
    image=np.array(image.cpu())
    plt.figure(figsize=(5,5))

    for index in range(16):
        plt.subplot(4,4,index+1)
        cam_image=show_cam_on_image(np.transpose(image[index],(1,2,0)),grayscale_cam,use_rgb=True)
        plt.imshow(cam_image)
    plt.show()
</code>```

I didn't normalize values because grayscale_cam gets np.floats value between 0 and 1. so image data has value between 0 and 1 for each pixel. Is there anyone who knows the answer?

Body:
I am using GradCAM with my custom dataset. I am following the codes of https://github.com/jacobgil/pytorch-grad-cam  <-this work
But I always get 0 values when the target layer is layer.4.
My network is pretrained resnet18. I checked there is a signal when it is layer1,2,3. but there was all 0 signal when the target layer was layer4. Below is my gradcam code.

def run_grad_cam_on_image():

net.eval()
for n_iter,(image,label) in enumerate(cifar100_test_loader):
    image=image.cuda()
    target_layers=[net.layer4]
    cam=GradCAM(net,target_layers=target_layers,use_cuda=True)

    targets=None

    grayscale_cam=cam(input_tensor=image,targets=targets)

    grayscale_cam=grayscale_cam[0,:]
    image=np.array(image.cpu())
    plt.figure(figsize=(5,5))

    for index in range(16):
        plt.subplot(4,4,index+1)
        cam_image=show_cam_on_image(np.transpose(image[index],(1,2,0)),grayscale_cam,use_rgb=True)
        plt.imshow(cam_image)
    plt.show()

I didn't normalize values because grayscale_cam gets np.floats value between 0 and 1. so image data has value between 0 and 1 for each pixel. Is there anyone who knows the answer?


问:
How to exclude action activities from ShareSheet?
I am using a ShareLink to share a file, in this case, a pdf. I want to exclude Activities like Messages in the same way I can do it with the ActivityController. How can I do it with ShareLink?

```<code>  ...
  let fileURL =  URL.documentsDirectory.appending(path: path)
  ShareLink(item: fileURL){
     Label("Share", systemImage: "square.and.arrow.up")
  }
</code>```

Body:
I am using a ShareLink to share a file, in this case, a pdf. I want to exclude Activities like Messages in the same way I can do it with the ActivityController. How can I do it with ShareLink?

  ...
  let fileURL =  URL.documentsDirectory.appending(path: path)
  ShareLink(item: fileURL){
     Label("Share", systemImage: "square.and.arrow.up")
  }


问:
Failed to process import candidates for configuration class [com.cloud.hystrix.HystrixDashboardApplication]
Failed to process import candidates for configuration class [com.cloud.hystrix.HystrixDashboardApplication]: Failed to introspect Class [org.springframework.cloud.netflix.hystrix.dashboard.HystrixDashboardConfiguration] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2f333739]</p>


问:
Does PHP SAML provide any API for IdP as it does for SP?
I am very confused, I am getting every information for SP in this Api of PHP SAML . But I don't know how to handel IDP side e.g how to authenticate request coming from SP on IDP, and then how to send response back to SP from IDP.

API, I have been used https://github.com/SAML-Toolkits/php-saml.

Please help me out on this .

And I also explored Simple SAML api, Whats that api used for ? this is similar to above or some other purpose ?

Help me out for finding how to authenticate request on IDP and create response on IDP and send back to SP.


问:
Fix java.lang.IllegalStateException: 'You need to use a Theme.AppCompat theme (or descendant) with this activity' for specific devices
I get this in crashlytics.
I understand we could use AppCompat versions for theme. But why I'm getting this crash only for a certain device?
As of now, only one user, Having Android 9 Vivo phones.</p>
```<code>Caused by java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
</code>```

Body:
I get this in crashlytics.
I understand we could use AppCompat versions for theme. But why I'm getting this crash only for a certain device?
As of now, only one user, Having Android 9 Vivo phones.

Caused by java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.


问:
IntelliSense suggestions for C++ Concepts in Visual Studio?
I'm very new to templates and concepts and started using them in Visual Studio 2022 (17.4.2).

Here is a program that compiles, but I find that the IntelliSense it not working as I had hoped:

struct Entity {
  int i;

  Entity(const int i_) : i(i_) {}
  virtual ~Entity() {}
};

struct A : public Entity {
  bool a;
  A(const int i_, const bool a_) : Entity(i_), a(a_) {}
};

template <class T>
concept hasI = requires(T a) { a.i; };
template <class T>
concept ofEntity = std::derived_from<T, Entity>;

// template <ofEntity T>  // doesn't make IntelliSense work either
template <hasI T>
void tfunc(const std::map<int, std::shared_ptr<T>>& m) {
  for (auto& it : m) {
// ------------------------ V -------------- No IntelliSense?
    std::cout << it.second->i << std::endl;
  }
}

static void run() {
  std::map<int, std::shared_ptr<Entity>> aMap;
  std::shared_ptr myA = std::make_shared(1, true);
  aMap.insert({myA->i, myA});

  tfunc(aMap);
}
```

As you can see in the marked line, I access the member, but while typing it, I do not get any suggestions. I understand that this is not working for general templates, but I was hoping that this would work in conjunction with concepts.

Having no IntelliSense in all functions with templates sounds very cumbersome, as errors will only show up when you compile and missing suggestions means slower coding.

From the replies here I expected this to be implemented by now. Is there anything I'm missing or not doing incorrectly?

Thank you in advance!

Body:
I'm very new to templates and concepts and started using them in Visual Studio 2022 (17.4.2).

Here is a program that compiles, but I find that the IntelliSense it not working as I had hoped:

struct Entity {
  int i;

  Entity(const int i_) : i(i_) {}
  virtual ~Entity() {}
};

struct A : public Entity {
  bool a;
  A(const int i_, const bool a_) : Entity(i_), a(a_) {}
};

template <class T>
concept hasI = requires(T a) { a.i; };
template <class T>
concept ofEntity = std::derived_from<T, Entity>;

// template <ofEntity T>  // doesn't make IntelliSense work either
template <hasI T>
void tfunc(const std::map<int, std::shared_ptr<T>>& m) {
  for (auto& it : m) {
// ------------------------ V -------------- No IntelliSense?
    std::cout << it.second->i << std::endl;
  }
}

static void run() {
  std::map<int, std::shared_ptr<Entity>> aMap;
  std::shared_ptr myA = std::make_shared(1, true);
  aMap.insert({myA->i, myA});

  tfunc(aMap);
}

As you can see in the marked line, I access the member, but while typing it, I do not get any suggestions. I understand that this is not working for general templates, but I was hoping that this would work in conjunction with concepts.

Having no IntelliSense in all functions with templates sounds very cumbersome, as errors will only show up when you compile and missing suggestions means slower coding.

From the replies here I expected this to be implemented by now. Is there anything I'm missing or not doing incorrectly?

Thank you in advance!


问:
Permanent redirect for www to non-www site using NextJs
I've built a website with Nextjs (using version 12.1.4). For SEO purposes I would like to make a permanent redirect for my www version of the site to my non-www. Normally this could easily be done with nginx or an .htaccess file with apache. However, static websites hosted on Digitalocean are not running apache or nginx so an .htaccess file won’t do. I've read that this should be possible using Nextjs redirects.

I've tried the following 3 redirects:

```<code>  redirects: async () => [
    {
      source: '/:path*',
      has: [
        {
          type: 'host',
          value: 'www',
        },
      ],
      destination: '/:path*',
      permanent: true,
    },
  ],

---------------------------------------------------

  redirects: async () => [
    {
      source: '/:path*/',
      has: [
        {
          type: 'host',
          value: 'www',
        },
      ],
      destination: '/:path*/',
      permanent: true,
    },
  ],

------------------------------------------------------

  redirects: async () => [
    {
      source: '/:path*',
      has: [{ type: 'host', value: 'https://www.cvtips.nl/' }],
      destination: 'https://cvtips.nl/:path*',
      permanent: true,
    },
  ],
</code>```

All of them don't seem to redirect to the non-www version. I don't know if it is relevant, but I do use trailingSlash: true in the config.

Next thing I tried is adding a middleware file. I both tried adding it at the root and calling it middleware.js and inside the pages folder calling it _middleware.js.

This is the code I use for the redirect:

```<code>--> https://github.com/vercel/next.js/discussions/33554
import { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest) {
  const host = req.headers.get('host');
  const wwwRegex = /^www\./;
  // This redirect will only take effect on a production website (on a non-localhost domain)
  if (wwwRegex.test(host) && !req.headers.get('host').includes('localhost')) {
    const newHost = host.replace(wwwRegex, '');
    return NextResponse.redirect(`https://${newHost}${req.nextUrl.pathname}`, 301);
  }
  return NextResponse.next();
}
</code>```

Also does not work at all... Doesn't do anything I believe.

How can I redirect a Nextjs website from www to non-www?

Body:
I've built a website with Nextjs (using version 12.1.4). For SEO purposes I would like to make a permanent redirect for my www version of the site to my non-www. Normally this could easily be done with nginx or an .htaccess file with apache. However, static websites hosted on Digitalocean are not running apache or nginx so an .htaccess file won’t do. I've read that this should be possible using Nextjs redirects.

I've tried the following 3 redirects:

  redirects: async () => [
    {
      source: '/:path*',
      has: [
        {
          type: 'host',
          value: 'www',
        },
      ],
      destination: '/:path*',
      permanent: true,
    },
  ],

---------------------------------------------------

  redirects: async () => [
    {
      source: '/:path*/',
      has: [
        {
          type: 'host',
          value: 'www',
        },
      ],
      destination: '/:path*/',
      permanent: true,
    },
  ],

------------------------------------------------------

  redirects: async () => [
    {
      source: '/:path*',
      has: [{ type: 'host', value: 'https://www.cvtips.nl/' }],
      destination: 'https://cvtips.nl/:path*',
      permanent: true,
    },
  ],

All of them don't seem to redirect to the non-www version. I don't know if it is relevant, but I do use trailingSlash: true in the config.

Next thing I tried is adding a middleware file. I both tried adding it at the root and calling it middleware.js and inside the pages folder calling it _middleware.js.

This is the code I use for the redirect:

--> https://github.com/vercel/next.js/discussions/33554
import { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest) {
  const host = req.headers.get('host');
  const wwwRegex = /^www\./;
  // This redirect will only take effect on a production website (on a non-localhost domain)
  if (wwwRegex.test(host) && !req.headers.get('host').includes('localhost')) {
    const newHost = host.replace(wwwRegex, '');
    return NextResponse.redirect(`https://${newHost}${req.nextUrl.pathname}`, 301);
  }
  return NextResponse.next();
}

Also does not work at all... Doesn't do anything I believe.

How can I redirect a Nextjs website from www to non-www?


问:
AWS lambda throw an error occasionally when I invoke the lambda
Lately I have been getting  an error that happens about once a week . maybe it is  related to timeout of lambda or connection to monogoDB but I'm not sure. i using  aws lambda and nodejs14 .

That is the Error:

2022-12-19T14:30:40.715Z 2a5e8a43-a315-40e2-a151-97b6630d9d95 ERROR Unhandled Promise Rejection {
    "errorType": "Runtime.UnhandledPromiseRejection",
    "errorMessage": "Error: write EPROTO",
    "reason": {
        "errorType": "Error",
        "errorMessage": "write EPROTO",
        "code": "EPROTO",
        "errno": -71,
        "syscall": "write",
        "$metadata": {
            "attempts": 1,
            "totalRetryDelay": 0
        },
        "stack": [
            "Error: write EPROTO",
            "    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16)"
        ]
    },
    "promise": {},
    "stack": [
        "Runtime.UnhandledPromiseRejection: Error: write EPROTO",
        "    at process.<anonymous> (/var/runtime/index.js:35:15)",
        "    at process.emit (events.js:400:28)",
        "    at process.emit (domain.js:475:12)",
        "    at processPromiseRejections (internal/process/promises.js:245:33)",
        "    at processTicksAndRejections (internal/process/task_queues.js:96:32)"
    ]
}
```
<p>The most of time there is no problem when i invoke the lambda .</p>
<p>my function:</p>
```const repository = new CustomerRepository();
export const getCustomers: any = middlewareBuilder(async (event, _context) => {
    try {
        logger.info('getCustomer start');
        const customers = await repository.findAllCustomers(); // get data from db
        logger.info({ message: ' fetch all customers ', additionalInfo: customers });
        logger.info('getCustomer end  ');
        return httpResult(200, customers);
    } catch (error) {
        logger.error('error ' + error);
        throw error;
    }
});
```

I tried to upgrade  nodejs14 to nodejs16.

Body:
Lately I have been getting  an error that happens about once a week . maybe it is  related to timeout of lambda or connection to monogoDB but I'm not sure. i using  aws lambda and nodejs14 .

That is the Error:

2022-12-19T14:30:40.715Z 2a5e8a43-a315-40e2-a151-97b6630d9d95 ERROR Unhandled Promise Rejection {
    "errorType": "Runtime.UnhandledPromiseRejection",
    "errorMessage": "Error: write EPROTO",
    "reason": {
        "errorType": "Error",
        "errorMessage": "write EPROTO",
        "code": "EPROTO",
        "errno": -71,
        "syscall": "write",
        "$metadata": {
            "attempts": 1,
            "totalRetryDelay": 0
        },
        "stack": [
            "Error: write EPROTO",
            "    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16)"
        ]
    },
    "promise": {},
    "stack": [
        "Runtime.UnhandledPromiseRejection: Error: write EPROTO",
        "    at process.<anonymous> (/var/runtime/index.js:35:15)",
        "    at process.emit (events.js:400:28)",
        "    at process.emit (domain.js:475:12)",
        "    at processPromiseRejections (internal/process/promises.js:245:33)",
        "    at processTicksAndRejections (internal/process/task_queues.js:96:32)"
    ]
}

The most of time there is no problem when i invoke the lambda .

my function:

const repository = new CustomerRepository();
export const getCustomers: any = middlewareBuilder(async (event, _context) => {
    try {
        logger.info('getCustomer start');
        const customers = await repository.findAllCustomers(); // get data from db
        logger.info({ message: ' fetch all customers ', additionalInfo: customers });
        logger.info('getCustomer end  ');
        return httpResult(200, customers);
    } catch (error) {
        logger.error('error ' + error);
        throw error;
    }
});

I tried to upgrade  nodejs14 to nodejs16.


问:
Fail to merge/extract OpenSSL certificates
I have 4 certificates with the following extensions

_com-bundle.pem

_com.der

_com.p7b

_com.pem

In my internal tool i need to add the SSL Cert and SSL key.

How can i merge/extract the correct cert and key from the above extensions?

i've tried the bellow command

openssl x509 -inform DER -in *_com.pem  -outform PEM -out cert.pem

but i've received and error that the key file is incorrect


问:
Looking for Image Search Server Software
I'm looking for a (possibly up-to-date) software to create an image search on Linux.
I looked at the OpenSearchServer, which should do pretty much what I need, but it hasn't had an update for a long time.

Please post solutions with name and/or link.

Thanks


问:
Flutter advanced datatable how to make diferent last row
I am currently making a custom data table using advanced datatable package. Now managed to make it looked good, following the design I was given except one, how to make the last row different than the rest, fixed one where even if the user navigate to next page of table, the last row will still be there. Pretty much like this.

(sorry for the squared censors...)

I am trying to make the last row look like the "Total" row, so to make something like this in advanced data table? Or any other suggestion for a better paginated data table package?


Title: Convert MongoDB BSON to valid JSON (Python 3)

Body:
Good afternoon everyone!

I ask for your help with advice on how to convert a MongoDB document like this:

[{
    "_id": 1,
    "TypeId": UUID("00000000-0000-0000-0000-000000000001"),
    "DateTime": ISODate("2022-03-05T00:39:15.670+02:00"),
    "Ticks": NumberLong("637820303556707897"),
    "CreatedDate": {
        "DateTime": ISODate("2022-03-05T00:39:15.670+02:00"),
        "Ticks": NumberLong("637820303556707897")
    },
    "AdditionalInformation": [
        {
            "TypeId": UUID("00000000-0000-0000-0000-000000000002"),
            "Informations": [
                {
                    "FileLength": NumberLong("12365478")
                }
            ]
        }
    ],
    "AccessGroups": [
        [
            UUID("00000000-0000-0000-0000-000000000006"),
            UUID("00000000-0000-0000-0000-000000000007")
        ]
    ]
},
...]

Into a valid JSON like this:

[{
    "_id": 1,
    "TypeId": "00000000-0000-0000-0000-000000000001",
    "DateTime": "2022-03-05T00:39:15.670+02:00",
    "Ticks": "637820303556707897",
    "CreatedDate": {
        "DateTime": "2022-03-05T00:39:15.670+02:00",
        "Ticks": "637820303556707897"
    },
    "AdditionalInformation": [
        {
            "TypeId": "00000000-0000-0000-0000-000000000002",
            "Informations": [
                {
                    "FileLength": "12365478"
                }
            ]
        }
    ],
    "AccessGroups": [
        [
            "00000000-0000-0000-0000-000000000006",
            "00000000-0000-0000-0000-000000000007"
        ]
    ]
},
...]

I'm trying to do this with pymongo and json libraries, but nothing is working out.
Thank you in advance!


问:
Python Trouble using a button
When I press escape it show the button but I can't click on it and it doesn't change his color.
I try to quit the game with the button but it seems that I couldn't.
This is the code:</p>
```<code>import pygame
import pygame.locals

pygame.init()

screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

white = (255,255,255)

light_button = (170,170,170)

dark_button = (100,100,100)

width = screen.get_width()

height = screen.get_height()

smallfont = pygame.font.SysFont('Corbel',35)

text = smallfont.render('QUIT' , True , white)

while True:

    for ev in pygame.event.get():
        pygame.display.update()

        if ev.type == pygame.QUIT:
            pygame.quit()

        #regarde si echap est cliqué
        if ev.type == pygame.locals.KEYDOWN and ev.key == pygame.K_ESCAPE:
            screen.fill((60,25,60))

           # stoque la position de la souris dans un tuple
            mouse = pygame.mouse.get_pos()
            pygame.display.update()

           #si la souris passe sur le bouton il change de couleur
            if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
                pygame.draw.rect(screen,light_button,[width/2,height/2,140,40])
                pygame.display.update()

            else:
                pygame.draw.rect(screen,dark_button,[width/2,height/2,140,40])
                pygame.display.update()

            #superpose le texte sur le bouton
            screen.blit(text , (width/2+50,height/2))
            pygame.display.update()

            #regarde si la souris est cliquée
            if ev.type == pygame.MOUSEBUTTONDOWN:
                pygame.display.update()

                if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
                    pygame.quit()
                    pygame.display.update()

#actualise les frames
pygame.display.update()
</code>```

Title: Python Trouble using a button

Body:
When I press escape it show the button but I can't click on it and it doesn't change his color.
I try to quit the game with the button but it seems that I couldn't.
This is the code:

import pygame
import pygame.locals

pygame.init()

screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

white = (255,255,255)

light_button = (170,170,170)

dark_button = (100,100,100)

width = screen.get_width()

height = screen.get_height()

smallfont = pygame.font.SysFont('Corbel',35)

text = smallfont.render('QUIT' , True , white)

while True:

    for ev in pygame.event.get():
        pygame.display.update()

        if ev.type == pygame.QUIT:
            pygame.quit()

        #regarde si echap est cliqué
        if ev.type == pygame.locals.KEYDOWN and ev.key == pygame.K_ESCAPE:
            screen.fill((60,25,60))

           # stoque la position de la souris dans un tuple
            mouse = pygame.mouse.get_pos()
            pygame.display.update()

           #si la souris passe sur le bouton il change de couleur
            if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
                pygame.draw.rect(screen,light_button,[width/2,height/2,140,40])
                pygame.display.update()

            else:
                pygame.draw.rect(screen,dark_button,[width/2,height/2,140,40])
                pygame.display.update()

            #superpose le texte sur le bouton
            screen.blit(text , (width/2+50,height/2))
            pygame.display.update()

            #regarde si la souris est cliquée
            if ev.type == pygame.MOUSEBUTTONDOWN:
                pygame.display.update()

                if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
                    pygame.quit()
                    pygame.display.update()

#actualise les frames
pygame.display.update()


问:
How to make custom QStandardItem for QTreeView?
In my project there is a window for editing files. Each file has some properties that the user can change with several checkboxes. Also each file has an icon.

Now it is implemented through QScrollArea in which widgets are added. It looks like this:

Now I want to add folder support for files. I would like to support drag n drop and so on.

I thought it would be a good idea in my case to use QTreeView.
The widget for the files has already been drawn and it suits me completely:

I haven't worked with QT's model/view framework before. after a couple of days of trying to draw something acceptable, I broke my brain. That's what I did:

```<code>import sys

from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *

from scanner.models import *
from gui.styles.settings import *
from gui.utils import setup_fonts

class BaseFileItem(QStandardItem):
    def __init__(self, parent=None):
        super(BaseFileItem, self).__init__(parent)
        self.setEditable(False)

class TitleItem(QStandardItem):
    file_type = 'title'

class FolderItem(QStandardItem):
    file_type = 'folder'

class PreviewItem(BaseFileItem):
    file_type = 'preview'

class FileItem(BaseFileItem):
    file_type = 'file'

class Model(QStandardItemModel):
    def supportedDropActions(self):
        return Qt.MoveAction

class Delegate(QStyledItemDelegate):
    checkbox_width = 50
    checkboxes = [
        'main',
        'preview',
        'use',
    ]

    def sizeHint(self, option, index):
        match index.data(1002):
            case 'title':
                height = 32
            case 'folder':
                height = 24
            case _:
                height = 48

        return QSize(height, height)

    def paint(self, painter, option, index):
        super(Delegate, self).paint(painter, option, index)
        match index.data(1002):
            case 'title':
                item_type = 'label'
            case 'folder':
                return
            case _:
                item_type = 'checkbox'

        for column, name in enumerate(self.checkboxes):
            self.add_checkbox_item(painter, option, column, name, item_type)

    def add_checkbox_item(self, painter, option, column, text, item_type):
        rect = option.rect

        if item_type == 'checkbox':
            item = QStyleOptionButton()
            ce = QStyle.CE_CheckBox
        else:
            item = QStyleOptionHeader()
            item.text = text
            ce = QStyle.CE_HeaderLabel
        item.item_type = item_type

        x, y = rect.left() + rect.width() - (column + 1) * self.checkbox_width, rect.top()
        item.rect = QRect(x, y, self.checkbox_width, rect.height())
        QApplication.style().drawControl(ce, item, painter)

class AssetEditFilesView(QWidget):
    rows = ['Asset files', 'Previews', 'Candidates']

    def __init__(self, files, parent=None):
        self.files = files
        super(AssetEditFilesView, self).__init__(parent)
        self.setContentsMargins(24, 24, 24, 24)
        self.model = Model()
        self.tree = QTreeView(self)
        self.tree.setContentsMargins(4, 4, 4, 4)
        self.tree.setItemDelegate(Delegate(self.tree))
        self.tree.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.tree.setSortingEnabled(True)
        self.tree.setDragEnabled(True)
        self.tree.setAcceptDrops(True)
        self.tree.setDropIndicatorShown(True)
        self.tree.header().hide()
        self.tree.setModel(self.model)
        self.import_data(files)
        self.tree.expandAll()
        layout = QVBoxLayout(self)
        layout.addWidget(self.tree)

    def import_data(self, data):
        self.model.setRowCount(0)
        for group, files in zip(self.rows, self.prepare_files(data)):
            if files:
                self.add_files_to_group(group, files)

    def add_files_to_group(self, group, files):
        files = sorted(files, key=lambda x: str(x.data().asset_path))
        data = [f.data().asset_path.parts for f in files]
        max_len = max([len(x) for x in data])
        prepared = [x for x in zip(*[[y[i] if i < len(y) else None for i in range(max_len)] for y in data])]
        structure = self.create_structure(prepared, files)

        root = self.add_file_row(self.model.invisibleRootItem(), group, TitleItem)
        for folder, items in structure.items():
            file_model = PreviewItem if group == 'Previews' else FileItem
            self.add_items(root, folder, items, file_model=file_model)

    def add_items(self, root, folder, items, file_model=FileItem):
        if folder == '.':
            for item in items:
                self.add_file_row(root, item, file_model)
        else:
            new_root = self.add_file_row(root, folder, FolderItem)
            for _folder, _items in items.items():
                self.add_items(new_root, _folder, _items, file_model=file_model)

    def add_file_row(self, root, item, file_model):
        item_name = str(item.filename.name) if hasattr(item, 'filename') else item
        item_model = file_model(item_name)
        item_model.setData(item, 1001)
        item_model.setData(file_model.file_type, 1002)
        print(root)
        root.appendRow(item_model)
        return item_model

    def create_structure(self, prepared, files):
        structure = {'.': []}
        for *parts, file in zip(*prepared, [f.data() for f in files]):
            parts = list(filter(lambda x: x is not None, parts))
            parent = structure
            for part in parts:
                if part not in parent:
                    parent[part] = {'.': []}
                parent = parent[part]
            parent['.'].append(file)
        return structure

    def prepare_files(self, data):
        groups = [[], [], []]
        for file in data:
            if type(file) in [PreviewImage, PreviewVideo]:
                group = 1
            elif isinstance(file, BaseFileModel):
                group = 0
            else:
                group = 2
            item = QStandardItem(str(file.filename.name))
            item.setData(file)
            groups[group].append(item)
        return groups

style = f'''
    AssetEditFilesView QTreeView {{
        {Fonts.normal}
        border: 2px;
        border-radius: 8px;
        background-color: {Colors.asset_edit_bg};
    }}
    AssetEditFilesView {{
        background-color: {Colors.popup_bg};
    }}
    AssetEditFilesView {{
        background-color: {Colors.popup_bg};
'''

if __name__ == '__main__':
    files = [
        BaseFileModel(filename=r'c:\temp0036.png'),
        BaseFileModel(filename=r'c:\temp0036.png'),
        BaseFileModel(filename=r'c:\temp0036.png', asset_path=Path('./huita/huyatina')),
        BaseFileModel(filename=r'c:\temp0048.png', asset_path=Path('./huita')),
        BaseFileModel(filename=r'c:\temp0127.png', asset_path=Path('./ne_huita')),
        BaseFileModel(filename=r'c:\temp0229.png', asset_path=Path('./ne_huita/huiyatina')),
        PreviewVideo(filename=r'c:\references.gif', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp321.png', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp0267.png', asset_path=Path('./previews/generated')),
        PreviewImage(filename=r'c:\temp3.png', asset_path=Path('./previews/generated/1/2')),
        PreviewImage(filename=r'c:\temp.bin', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp.bin.png', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp.png', asset_path=Path('./previews/generated/2/1')),
        PreviewImage(filename=r'c:\temp.png', asset_path=Path('./previews/generated/1/2')),
        PreviewImage(filename=r'c:\temp.png', asset_path=Path('./previews/generated/1')),
    ]
    app = QApplication(sys.argv)
    setup_fonts(app)
    app.setStyleSheet(style)
    view = AssetEditFilesView(files)
    view.setGeometry(800, 500, 800, 640)
    view.setWindowTitle('QTreeview Example')
    view.show()
    sys.exit(app.exec())

</code>```

I have 3 entities:

file (should look like on the 1st screenshot (3 checkboxes and an icon))

folder (must contain a name)

title (in fact the folder only the font should be larger)

how do i implement all entities using 1 QStyledItemDelegate?
Can I use a ready-made custom QWidget as a file entity?
the only thing I managed to do was to implement a more or less working sizeHint, but I have no idea how to add a file widget.

I will be grateful for any help, as now I am close to implementing all this through QScrollArea instead of QTreeView

i need some thing like this:

I also can't figure out how to apply styles to a QStandardItem, QStyledItemDelegate,

Body:
In my project there is a window for editing files. Each file has some properties that the user can change with several checkboxes. Also each file has an icon.

Now it is implemented through QScrollArea in which widgets are added. It looks like this:

Now I want to add folder support for files. I would like to support drag n drop and so on.

I thought it would be a good idea in my case to use QTreeView.
The widget for the files has already been drawn and it suits me completely:

I haven't worked with QT's model/view framework before. after a couple of days of trying to draw something acceptable, I broke my brain. That's what I did:

import sys

from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *

from scanner.models import *
from gui.styles.settings import *
from gui.utils import setup_fonts

class BaseFileItem(QStandardItem):
    def __init__(self, parent=None):
        super(BaseFileItem, self).__init__(parent)
        self.setEditable(False)

class TitleItem(QStandardItem):
    file_type = 'title'

class FolderItem(QStandardItem):
    file_type = 'folder'

class PreviewItem(BaseFileItem):
    file_type = 'preview'

class FileItem(BaseFileItem):
    file_type = 'file'

class Model(QStandardItemModel):
    def supportedDropActions(self):
        return Qt.MoveAction

class Delegate(QStyledItemDelegate):
    checkbox_width = 50
    checkboxes = [
        'main',
        'preview',
        'use',
    ]

    def sizeHint(self, option, index):
        match index.data(1002):
            case 'title':
                height = 32
            case 'folder':
                height = 24
            case _:
                height = 48

        return QSize(height, height)

    def paint(self, painter, option, index):
        super(Delegate, self).paint(painter, option, index)
        match index.data(1002):
            case 'title':
                item_type = 'label'
            case 'folder':
                return
            case _:
                item_type = 'checkbox'

        for column, name in enumerate(self.checkboxes):
            self.add_checkbox_item(painter, option, column, name, item_type)

    def add_checkbox_item(self, painter, option, column, text, item_type):
        rect = option.rect

        if item_type == 'checkbox':
            item = QStyleOptionButton()
            ce = QStyle.CE_CheckBox
        else:
            item = QStyleOptionHeader()
            item.text = text
            ce = QStyle.CE_HeaderLabel
        item.item_type = item_type

        x, y = rect.left() + rect.width() - (column + 1) * self.checkbox_width, rect.top()
        item.rect = QRect(x, y, self.checkbox_width, rect.height())
        QApplication.style().drawControl(ce, item, painter)

class AssetEditFilesView(QWidget):
    rows = ['Asset files', 'Previews', 'Candidates']

    def __init__(self, files, parent=None):
        self.files = files
        super(AssetEditFilesView, self).__init__(parent)
        self.setContentsMargins(24, 24, 24, 24)
        self.model = Model()
        self.tree = QTreeView(self)
        self.tree.setContentsMargins(4, 4, 4, 4)
        self.tree.setItemDelegate(Delegate(self.tree))
        self.tree.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.tree.setSortingEnabled(True)
        self.tree.setDragEnabled(True)
        self.tree.setAcceptDrops(True)
        self.tree.setDropIndicatorShown(True)
        self.tree.header().hide()
        self.tree.setModel(self.model)
        self.import_data(files)
        self.tree.expandAll()
        layout = QVBoxLayout(self)
        layout.addWidget(self.tree)

    def import_data(self, data):
        self.model.setRowCount(0)
        for group, files in zip(self.rows, self.prepare_files(data)):
            if files:
                self.add_files_to_group(group, files)

    def add_files_to_group(self, group, files):
        files = sorted(files, key=lambda x: str(x.data().asset_path))
        data = [f.data().asset_path.parts for f in files]
        max_len = max([len(x) for x in data])
        prepared = [x for x in zip(*[[y[i] if i < len(y) else None for i in range(max_len)] for y in data])]
        structure = self.create_structure(prepared, files)

        root = self.add_file_row(self.model.invisibleRootItem(), group, TitleItem)
        for folder, items in structure.items():
            file_model = PreviewItem if group == 'Previews' else FileItem
            self.add_items(root, folder, items, file_model=file_model)

    def add_items(self, root, folder, items, file_model=FileItem):
        if folder == '.':
            for item in items:
                self.add_file_row(root, item, file_model)
        else:
            new_root = self.add_file_row(root, folder, FolderItem)
            for _folder, _items in items.items():
                self.add_items(new_root, _folder, _items, file_model=file_model)

    def add_file_row(self, root, item, file_model):
        item_name = str(item.filename.name) if hasattr(item, 'filename') else item
        item_model = file_model(item_name)
        item_model.setData(item, 1001)
        item_model.setData(file_model.file_type, 1002)
        print(root)
        root.appendRow(item_model)
        return item_model

    def create_structure(self, prepared, files):
        structure = {'.': []}
        for *parts, file in zip(*prepared, [f.data() for f in files]):
            parts = list(filter(lambda x: x is not None, parts))
            parent = structure
            for part in parts:
                if part not in parent:
                    parent[part] = {'.': []}
                parent = parent[part]
            parent['.'].append(file)
        return structure

    def prepare_files(self, data):
        groups = [[], [], []]
        for file in data:
            if type(file) in [PreviewImage, PreviewVideo]:
                group = 1
            elif isinstance(file, BaseFileModel):
                group = 0
            else:
                group = 2
            item = QStandardItem(str(file.filename.name))
            item.setData(file)
            groups[group].append(item)
        return groups

style = f'''
    AssetEditFilesView QTreeView {{
        {Fonts.normal}
        border: 2px;
        border-radius: 8px;
        background-color: {Colors.asset_edit_bg};
    }}
    AssetEditFilesView {{
        background-color: {Colors.popup_bg};
    }}
    AssetEditFilesView {{
        background-color: {Colors.popup_bg};
'''

if __name__ == '__main__':
    files = [
        BaseFileModel(filename=r'c:\temp0036.png'),
        BaseFileModel(filename=r'c:\temp0036.png'),
        BaseFileModel(filename=r'c:\temp0036.png', asset_path=Path('./huita/huyatina')),
        BaseFileModel(filename=r'c:\temp0048.png', asset_path=Path('./huita')),
        BaseFileModel(filename=r'c:\temp0127.png', asset_path=Path('./ne_huita')),
        BaseFileModel(filename=r'c:\temp0229.png', asset_path=Path('./ne_huita/huiyatina')),
        PreviewVideo(filename=r'c:\references.gif', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp321.png', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp0267.png', asset_path=Path('./previews/generated')),
        PreviewImage(filename=r'c:\temp3.png', asset_path=Path('./previews/generated/1/2')),
        PreviewImage(filename=r'c:\temp.bin', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp.bin.png', asset_path=Path('./previews')),
        PreviewImage(filename=r'c:\temp.png', asset_path=Path('./previews/generated/2/1')),
        PreviewImage(filename=r'c:\temp.png', asset_path=Path('./previews/generated/1/2')),
        PreviewImage(filename=r'c:\temp.png', asset_path=Path('./previews/generated/1')),
    ]
    app = QApplication(sys.argv)
    setup_fonts(app)
    app.setStyleSheet(style)
    view = AssetEditFilesView(files)
    view.setGeometry(800, 500, 800, 640)
    view.setWindowTitle('QTreeview Example')
    view.show()
    sys.exit(app.exec())

I have 3 entities:

file (should look like on the 1st screenshot (3 checkboxes and an icon))

folder (must contain a name)

title (in fact the folder only the font should be larger)

how do i implement all entities using 1 QStyledItemDelegate?
Can I use a ready-made custom QWidget as a file entity?
the only thing I managed to do was to implement a more or less working sizeHint, but I have no idea how to add a file widget.

I will be grateful for any help, as now I am close to implementing all this through QScrollArea instead of QTreeView

i need some thing like this:

I also can't figure out how to apply styles to a QStandardItem, QStyledItemDelegate,


问:
How can I connect 2 react projects with one socket server? And let them communicate via socket?
I want two separate react projects to communicate with each other through below provided code-base.
So if I tap on counter1 on project-1, counter1 of project-2 gets updates automatically without refreshing the page.

```<code>parentDirectory:
    project-1:
        ReactProject1
    project-2:
        ReactProject2
    socketServer
        index.js (Socket.io)
</code>```

Index.js:

```<code>import { Server } from "socket.io";

const io = new Server(3001, {
    cors: {
        origin: '*',
    }
});

io.on('connection', (socket) => {
    socket.emit('welcome', 'connection established');
    socket.on('msg', (data) => {
        let dataArr = data.split("--")
        console.log(dataArr[0], dataArr[1])
        socket.emit('update1', data);
        socket.emit('update2', data);
    })
})
</code>```

App.js: (Project1)

```<code>import './App.css';

import React from 'react'
import CounterButton from './components/counter-button';
import { io } from 'socket.io-client';
const socket = io("http://localhost:3001")

function App() {
  let [counter1, setCounter1] = React.useState(0);
  let [counter2, setCounter2] = React.useState(0);
  let [counter3, setCounter3] = React.useState(0);
  // let [socketio, setSocket] = React.useState(null);

  React.useEffect(() => {
    socket.on('connect', () => {
      socket.on('update1', (data) => {
        let dataArr = data.split('--')
        console.log("Im here", data)
        let index = dataArr[0] - 0;
        let value = dataArr[1] - 0;
        if (index == 0) {
          setCounter1(value)
        }
        else if (index == 1) {
          setCounter2(value)
        }
        else if (index == 2) {
          setCounter3(value)
        }
      })
    })
  }, []);

  const messageServer = (index, newValue) => {
    socket.emit('msg', "" + index + "--" + newValue);
  }

  return (
    <div className="App">
      <div className='button-row' style={{ "display": "flex", "flexDirection": "row", "gap": "20px" }}>
        <CounterButton buttonName={1}
          value={counter1}
          onClick={() => { messageServer(0, counter1 + 1) }}
        />
        <CounterButton buttonName={2}
          value={counter2}
          onClick={() => { messageServer(1, counter2 + 1) }}
        />
        <CounterButton buttonName={3}
          value={counter3}
          onClick={() => { messageServer(2, counter3 + 1) }}
        />
      </div>
    </div>
  );
}

export default App;
</code>```

App.js (Project 2):

Same as App.js in project1, just React.useEffect has 'update2' in socket listener.

```<code>React.useEffect(() => {
    socket.on('connect', () => {
      socket.on('update2', (data) => {
        let dataArr = data.split('--')
        console.log("Im here", data)
        let index = dataArr[0] - 0;
        let value = dataArr[1] - 0;
        if (index == 0) {
          setCounter1(value)
        }
        else if (index == 1) {
          setCounter2(value)
        }
        else if (index == 2) {
          setCounter3(value)
        }
      })
    })
  }, []);
</code>```

Body:
I want two separate react projects to communicate with each other through below provided code-base.
So if I tap on counter1 on project-1, counter1 of project-2 gets updates automatically without refreshing the page.

parentDirectory:
    project-1:
        ReactProject1
    project-2:
        ReactProject2
    socketServer
        index.js (Socket.io)

Index.js:

import { Server } from "socket.io";

const io = new Server(3001, {
    cors: {
        origin: '*',
    }
});

io.on('connection', (socket) => {
    socket.emit('welcome', 'connection established');
    socket.on('msg', (data) => {
        let dataArr = data.split("--")
        console.log(dataArr[0], dataArr[1])
        socket.emit('update1', data);
        socket.emit('update2', data);
    })
})

App.js: (Project1)

import './App.css';

import React from 'react'
import CounterButton from './components/counter-button';
import { io } from 'socket.io-client';
const socket = io("http://localhost:3001")

function App() {
  let [counter1, setCounter1] = React.useState(0);
  let [counter2, setCounter2] = React.useState(0);
  let [counter3, setCounter3] = React.useState(0);
  // let [socketio, setSocket] = React.useState(null);

  React.useEffect(() => {
    socket.on('connect', () => {
      socket.on('update1', (data) => {
        let dataArr = data.split('--')
        console.log("Im here", data)
        let index = dataArr[0] - 0;
        let value = dataArr[1] - 0;
        if (index == 0) {
          setCounter1(value)
        }
        else if (index == 1) {
          setCounter2(value)
        }
        else if (index == 2) {
          setCounter3(value)
        }
      })
    })
  }, []);

  const messageServer = (index, newValue) => {
    socket.emit('msg', "" + index + "--" + newValue);
  }

  return (

        <CounterButton buttonName={1}
          value={counter1}
          onClick={() => { messageServer(0, counter1 + 1) }}
        />
        <CounterButton buttonName={2}
          value={counter2}
          onClick={() => { messageServer(1, counter2 + 1) }}
        />
        <CounterButton buttonName={3}
          value={counter3}
          onClick={() => { messageServer(2, counter3 + 1) }}
        />

  );
}

export default App;

App.js (Project 2):

Same as App.js in project1, just React.useEffect has 'update2' in socket listener.

React.useEffect(() => {
    socket.on('connect', () => {
      socket.on('update2', (data) => {
        let dataArr = data.split('--')
        console.log("Im here", data)
        let index = dataArr[0] - 0;
        let value = dataArr[1] - 0;
        if (index == 0) {
          setCounter1(value)
        }
        else if (index == 1) {
          setCounter2(value)
        }
        else if (index == 2) {
          setCounter3(value)
        }
      })
    })
  }, []);


问:
SignalR connection issue on 5G
I am having a connection issue with SignalR on only 5G mobile data. I am using ASP.NET Core Web API for the backend and Angular for the front end. I am using Azure SignalR, when I am using Wifi or 4G it works fine but when I switch to 5G data I get the following error in the console.

Error: Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.

Any helping regarding this will be very usefull.

I tried to increase the timeout but still no luck.

Title: SignalR connection issue on 5G


问:
CRY gate control when '0'
I want to make CRY gate which operates when control bit is '0'

which figure is like this circle with empty space.

I can make it on qiskit but not on pennylane.

How I make that in Pennylane circuit....

Here is my code.

import pennylane as qml
from pennylane import numpy as np
import matplotlib
dev = qml.device('qiskit.aer', wires=2)
@qml.qnode(dev)
def circuit():

 qml.CRY(np.pi/2, wires=[0,1],id='0')

 return qml.expval(qml.PauliZ(0))
 circuit()
 dev._circuit.draw(output="mpl")
```

I want to make this circuit.

And optimizing the gates by method introduced in pennylane

Title: CRY gate control when '0'

Body:
I want to make CRY gate which operates when control bit is '0'

which figure is like this circle with empty space.

I can make it on qiskit but not on pennylane.

How I make that in Pennylane circuit....

Here is my code.

import pennylane as qml
from pennylane import numpy as np
import matplotlib
dev = qml.device('qiskit.aer', wires=2)
@qml.qnode(dev)
def circuit():

 qml.CRY(np.pi/2, wires=[0,1],id='0')

 return qml.expval(qml.PauliZ(0))
 circuit()
 dev._circuit.draw(output="mpl")

I want to make this circuit.

And optimizing the gates by method introduced in pennylane


问:
TDengine all streams stopped working for no reason
all streams stop working at one time for no reason;

one of the stream create sql is:

```<code>CREATE STREAM IF NOT EXISTS cq_action_info_1m_s TRIGGER WINDOW_CLOSE into cq_action_info_1m SUBTABLE(CONCAT('cai1_', tbname)) AS  SELECT  _wstart as _ts, avg(ave_time_top) as ave_time_top, avg(average_time) as average_time, max(handle_now_count) as handle_now_count, max(last_time) as last_time, max(max_time_top) as max_time_top, max(p_error_rate) as p_error_rate, max(profession_error) as profession_error, max(req_count) as req_count, max(req_second_count) as req_second_count, max(total_time) as total_time, max(unusual_count) as unusual_count, action, action_name, host, port, shelltype FROM zzdb.action_info PARTITION BY action, action_name, host, port, shelltype INTERVAL(1m);
</code>```

some system information is as follows:
TDengine version: 3.0.2.2

But I'm not sure if the result of the last write is complete;

This is my latest query result, it still stops at 30th, I don't know if there is a local log file for query reason:

Body:
all streams stop working at one time for no reason;

one of the stream create sql is:

CREATE STREAM IF NOT EXISTS cq_action_info_1m_s TRIGGER WINDOW_CLOSE into cq_action_info_1m SUBTABLE(CONCAT('cai1_', tbname)) AS  SELECT  _wstart as _ts, avg(ave_time_top) as ave_time_top, avg(average_time) as average_time, max(handle_now_count) as handle_now_count, max(last_time) as last_time, max(max_time_top) as max_time_top, max(p_error_rate) as p_error_rate, max(profession_error) as profession_error, max(req_count) as req_count, max(req_second_count) as req_second_count, max(total_time) as total_time, max(unusual_count) as unusual_count, action, action_name, host, port, shelltype FROM zzdb.action_info PARTITION BY action, action_name, host, port, shelltype INTERVAL(1m);

some system information is as follows:
TDengine version: 3.0.2.2

But I'm not sure if the result of the last write is complete;

This is my latest query result, it still stops at 30th, I don't know if there is a local log file for query reason:


问:
Linux i2c touch device driver probe not be called
I try to add focaltech touch driver to my board, the fts_ts_init() is worked, but the ->probe() not be called, I do not why. CONFIG_OF is opened.

Driver code：

static const struct i2c_device_id fts_ts_id[] = {
    {FTS_DRIVER_NAME, 0},
    {}
};
static const struct of_device_id fts_dt_match[] = {
    {.compatible = "focaltech,fts", },
    {}
};
MODULE_DEVICE_TABLE(of, fts_dt_match);

static struct i2c_driver fts_ts_driver = {
    .probe = fts_ts_probe,
    .remove = fts_ts_remove,
    .driver = {
        .name = FTS_DRIVER_NAME,
        .owner = THIS_MODULE,
#if defined(CONFIG_PM) && FTS_PATCH_COMERR_PM
        .pm = &fts_dev_pm_ops,
#endif
        .of_match_table = of_match_ptr(fts_dt_match),
    },
    .id_table = fts_ts_id,
};

static int __init fts_ts_init(void)
{
    int ret = 0;

    FTS_FUNC_ENTER();
    ret = i2c_add_driver(&fts_ts_driver);
    printk("[FTS_TS] ret=%d\n", ret);
    if (ret)
        FTS_ERROR("Focaltech touch screen driver init failed!");
    FTS_FUNC_EXIT();
    return ret;
}
module_init(fts_ts_init);
```
<h1>Device Tree Source:</h1>
<pre class="lang-dts prettyprint-override"><code>i2c4: i2c@0x10054000 {
    compatible = "ingenic,x2000-i2c";
    reg = <0x10054000 0x1000>;
    interrupt-parent = <&core_intc>;
    interrupts = <IRQ_I2C4>;
    #address-cells = <1>;
    #size-cells = <0>;
    status = "okay";

    focaltech@38{
        compatible = "focaltech,fts";
        reg = <0x38>;
        interrupt-parent = <&gpa>;
        interrupts = <3 0x2>;

        focaltech,reset-gpio = <&gpa 0 GPIO_ACTIVE_LOW >;
        focaltech,irq-gpio = <&gpa 3 0x2 >;
        focaltech,max-touch-number = <2>;
        focaltech,display-coords =  <0 0 800 480>;

        status = "okay";
    };
};
</code>```

I try to write the node in /, and use a simple paltform drvier, of_match_table is the same, ->probe() is called.

Body:
I try to add focaltech touch driver to my board, the fts_ts_init() is worked, but the ->probe() not be called, I do not why. CONFIG_OF is opened.

Driver code：

static const struct i2c_device_id fts_ts_id[] = {
    {FTS_DRIVER_NAME, 0},
    {}
};
static const struct of_device_id fts_dt_match[] = {
    {.compatible = "focaltech,fts", },
    {}
};
MODULE_DEVICE_TABLE(of, fts_dt_match);

static struct i2c_driver fts_ts_driver = {
    .probe = fts_ts_probe,
    .remove = fts_ts_remove,
    .driver = {
        .name = FTS_DRIVER_NAME,
        .owner = THIS_MODULE,
#if defined(CONFIG_PM) && FTS_PATCH_COMERR_PM
        .pm = &fts_dev_pm_ops,
#endif
        .of_match_table = of_match_ptr(fts_dt_match),
    },
    .id_table = fts_ts_id,
};

static int __init fts_ts_init(void)
{
    int ret = 0;

    FTS_FUNC_ENTER();
    ret = i2c_add_driver(&fts_ts_driver);
    printk("[FTS_TS] ret=%d\n", ret);
    if (ret)
        FTS_ERROR("Focaltech touch screen driver init failed!");
    FTS_FUNC_EXIT();
    return ret;
}
module_init(fts_ts_init);

Device Tree Source:

i2c4: i2c@0x10054000 {
    compatible = "ingenic,x2000-i2c";
    reg = <0x10054000 0x1000>;
    interrupt-parent = <&core_intc>;
    interrupts = <IRQ_I2C4>;
    #address-cells = <1>;
    #size-cells = <0>;
    status = "okay";

    focaltech@38{
        compatible = "focaltech,fts";
        reg = <0x38>;
        interrupt-parent = <&gpa>;
        interrupts = <3 0x2>;

        focaltech,reset-gpio = <&gpa 0 GPIO_ACTIVE_LOW >;
        focaltech,irq-gpio = <&gpa 3 0x2 >;
        focaltech,max-touch-number = <2>;
        focaltech,display-coords =  <0 0 800 480>;

        status = "okay";
    };
};

I try to write the node in /, and use a simple paltform drvier, of_match_table is the same, ->probe() is called.


问:
Error: exceptionjavax.servlet.ServletException: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0)
```<code><%

            String ID,name,username = (String)session.getAttribute("username");

            String leaveType, StartDate, EndDate, reason;

            leaveType = request.getParameter("leaveType");

            StartDate = request.getParameter("StartDate");

            EndDate = request.getParameter("EndDate");

            reason = request.getParameter("reason");

            Class.forName("com.mysql.jdbc.Driver");

            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","12345");

            ID="select EID from empinfo where EUsername="+username+"'";

            name="select EName from empinfo where EUsername="+username+"'";

            PreparedStatement pst = con.prepareStatement("INSERT INTO 'leave (EID,EName,leaveType,StartDate,EndDate,Reason) VALUES (?,?,?,?,?,?)");

            pst.setString(1, ID);

            pst.setString(2, name);

            pst.setString(3, leaveType);

            pst.setString(4, StartDate);

            pst.setString(5, EndDate);

            pst.setString(6, reason);

           int row = pst.executeUpdate();

            if(row==1)

            {

               %>

           <script>

            alert("Leave Applied");

        </script>

        <jsp:include page="profile.jsp"></jsp:include>

        <%

            }

            else

            {

                out.println("Leave Application Failed");

            }

%>

javax.servlet.ServletException: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
</code>```

root cause

```<code>java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
</code>```

How can solve this error?

I am new to this.
Working on my first project.

Body:
<%

            String ID,name,username = (String)session.getAttribute("username");

            String leaveType, StartDate, EndDate, reason;

            leaveType = request.getParameter("leaveType");

            StartDate = request.getParameter("StartDate");

            EndDate = request.getParameter("EndDate");

            reason = request.getParameter("reason");

            Class.forName("com.mysql.jdbc.Driver");

            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","12345");

            ID="select EID from empinfo where EUsername="+username+"'";

            name="select EName from empinfo where EUsername="+username+"'";

            PreparedStatement pst = con.prepareStatement("INSERT INTO 'leave (EID,EName,leaveType,StartDate,EndDate,Reason) VALUES (?,?,?,?,?,?)");

            pst.setString(1, ID);

            pst.setString(2, name);

            pst.setString(3, leaveType);

            pst.setString(4, StartDate);

            pst.setString(5, EndDate);

            pst.setString(6, reason);

           int row = pst.executeUpdate();

            if(row==1)

            {

               %>

        <jsp:include page="profile.jsp"></jsp:include>

        <%

            }

            else

            {

                out.println("Leave Application Failed");

            }

%>

javax.servlet.ServletException: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

root cause

java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

How can solve this error?

I am new to this.
Working on my first project.


问:
Rstudio save Rmd file failed
While I editing Rmd file using RStudio, "Ctrl+S" not work anymore for the current edited file. The unsaved file status is illustrated as fig 1. But both the "Ctrl+S" and "Clicking the save icon" not work. This occurred several hours after the RStudio started. I can't catch exactly when this is happened. To solve this problem, using "Ctrl +A" and copy all the content to another file. And then close the problem Rmd file without saving.

It is ok to open another new Rmd file and both "Ctrl+S" and "Clicking the save icon" worked normally for the new Rmd file.

fig.1 there is a "*" after the file name, indicating the file has been changed and not saved.

My OS is: Windows 10 home version

Title: Rstudio save Rmd file failed


问:
how to specifies the path that is used by AdaptiveIconDrawable class to crop launcher icons
Does anybody know svg path viewport size use in design the svg path?

config_icon_mask in framework/base/../config.xml

 <string name="config_icon_mask" translatable="false">"M50,0L100,0 100,100 0,100 0,0z"</string>


问:
Find all the rights set for a specific SPN within Azure
I'm looking for a way to find all the rights that have set within Azure for a specific SPN.
I'd like to have either through the GUI/AZ CLI/Powershell/Graph explorer a single result with all the rights set for this SPN.
Is it possible ?
Thanks in advance.

I have tried many things but couldn't find anything so far.


问:
DB2 read bulk data
I am reading bulk data from database with a size of 100mb.
What I am doing is reading it in a procedure and building a xml which is amazingly very fast.
So I am calling the stored procedure via Hibernate through JDBC in which the transmission takes too long, because of the large xml.
I am thinking of to zip the file in the procedure.
Does DB2 LUW supporting zipping from a stored procedure?</p>

Title: DB2 read bulk data


问:
Indicator for tradingview
I would like to create an indicator on tradingview that returns the gap of an instrument that I am going to select, then I would like to compare it with the performance of the chart.
Within the indicator I would like to have the ability to select a different instrument from the chart

I'm a complete newbie and wish someone could code me. I don't think it's difficult and I tried to write something but unfortunately after several attempts I can't get it to work

Title: Indicator for tradingview


问:
os.kill not working as expected with Spyder on Windows
My Python (3.6) script starts a subprocess that handles SIGINT (CTRL_C_EVENT) and SIGTERM.
Everything works fine with Terminal or Powershell.
However, when run in Spyder (3.2.4)/Ipython, I get an error for os.kill(..):

SystemError: <built-in function kill> returned a result with an error set

with traceback:

OSError: [WinError 6] The Handle is invalid.

When starting another scirpt with Popen that sends the CTRL_C_EVENT with os.kill, the first subprocess gets stoped but not as I want it to. Both, CTRL_C_EVENT and SIGTERM seem to become a SIGKILL instead and the process ends unclean.

I can start it with
Configuration Per File > Execute In An External System Terminal
but that is not really a good solution in this case (would confuse other users etc etc).

Updating IPython didn´t help.

Using creationflags for Popen doens´t seem to help.
Starting other suprocesses and trying to stop them cleanly brings the same result.

Does somebody know why this happens and why Ipython handles it differently?
Any way to get it run in the IPython console?

Thanks in advance!

Edit:
I thought I would keep it short and leave code away as it doesn´t seem that important for this problem, but here some more info.
I have tried it with different solutions and subprocesses with the same result. One for example I start with:

```<code>proc = subprocess.Popen(command, shell=False, start_new_session=True)
</code>```

Which simply starts an .exe that handles the Signals mentioned above.

When calling

```<code>os.kill(proc.pid, signal.CTRL_C_EVENT)
</code>```

everything works fine when run in Terminal or Powershell. I does not however in Spyders IPython console.

May it be a problem/bug in IPython, is it intended, or am I just not seeing something I did wrong? I have updated IPython but it changed nothing.

Any help is much appreciated.

Body:
My Python (3.6) script starts a subprocess that handles SIGINT (CTRL_C_EVENT) and SIGTERM.
Everything works fine with Terminal or Powershell.
However, when run in Spyder (3.2.4)/Ipython, I get an error for os.kill(..):

SystemError: <built-in function kill> returned a result with an error set

with traceback:

OSError: [WinError 6] The Handle is invalid.

When starting another scirpt with Popen that sends the CTRL_C_EVENT with os.kill, the first subprocess gets stoped but not as I want it to. Both, CTRL_C_EVENT and SIGTERM seem to become a SIGKILL instead and the process ends unclean.

I can start it with
Configuration Per File > Execute In An External System Terminal
but that is not really a good solution in this case (would confuse other users etc etc).

Updating IPython didn´t help.

Using creationflags for Popen doens´t seem to help.
Starting other suprocesses and trying to stop them cleanly brings the same result.

Does somebody know why this happens and why Ipython handles it differently?
Any way to get it run in the IPython console?

Thanks in advance!

Edit:
I thought I would keep it short and leave code away as it doesn´t seem that important for this problem, but here some more info.
I have tried it with different solutions and subprocesses with the same result. One for example I start with:

proc = subprocess.Popen(command, shell=False, start_new_session=True)

Which simply starts an .exe that handles the Signals mentioned above.

When calling

os.kill(proc.pid, signal.CTRL_C_EVENT)

everything works fine when run in Terminal or Powershell. I does not however in Spyders IPython console.

May it be a problem/bug in IPython, is it intended, or am I just not seeing something I did wrong? I have updated IPython but it changed nothing.

Any help is much appreciated.


问:
Get background-color of element in DOM when clicked
I have a mapping, with different colorful nodes linked together (or not) in d3.js.
When a user clicks somewhere, it's either on nodes, on the links between the nodes or on the black background.
What I would like is a way to get the color of the element I'm clicking, especially to know if it's outside the mapping, so a way to get "black" as a result (since the background is black).

```<code>const elems = document.body.getElementsByTagName("*");
const cssObj = window.getComputedStyle(elems, null);
let bgColor = cssObj.getPropertyValue("background-color");
console.log("The color clicked is : "+bgColor);
</code>```

So far, this is the only code I've tested and I'm getting this error.

I don't understand how this can come out. Help on this would really be appreciated I can't find anything. Also, here's what my mapping looks like.

Body:
I have a mapping, with different colorful nodes linked together (or not) in d3.js.
When a user clicks somewhere, it's either on nodes, on the links between the nodes or on the black background.
What I would like is a way to get the color of the element I'm clicking, especially to know if it's outside the mapping, so a way to get "black" as a result (since the background is black).

const elems = document.body.getElementsByTagName("*");
const cssObj = window.getComputedStyle(elems, null);
let bgColor = cssObj.getPropertyValue("background-color");
console.log("The color clicked is : "+bgColor);

So far, this is the only code I've tested and I'm getting this error.

I don't understand how this can come out. Help on this would really be appreciated I can't find anything. Also, here's what my mapping looks like.


问:
Is there any method to extract "score" produced when querying dataset in MongoDB compass
I am new in learning about MongoDB compass.

How do I extract the highlighted "score" produced when we query the data as shown below?

I tried using “Export Collection”, but it doesn’t work. Even if I add a new field ("score") in 'Export Collection", a score column will be created but it will be empty.

I want to create "score" column containing all the score for each of the result

Any suggestions will be appreciated.


问:
Update InputDataSet table in SQL Server while executing R-Services
In a SQL Server database I have an InputTable whose data is given to a stored procedure which runs an R-script on the rows whose Flag=0 after running the script I want to set Flag=1 on the specific rows of InputTable on which the script was executed.

Below is my code for the stored procedure, in this way when I update after the script using the line UPDATE InputTable SET Flag=1 - while the procedure is running and if there is new data inserted in the table, this sets the Flag=1 on the newly inserted data on which the R-script/stored procedure was not executed.

```<code>BEGIN
    INSERT INTO OutputTable
    EXECUTE sp_execute_external_script @language = N'R'
        , @script = N'

         <running some R code in here>

        '
        , @input_data_1 = N'SELECT * FROM InputTable WHERE Flag=''0'';'
UPDATE InputTable SET Flag=1
END;

</code>```

How can I track the Id's of the rows on which the R-script was executed? Currently, I can only return an OutputDataSet which I am Inserting into another table. Can I use another variable to return Id's of OutputDataSet and update Flag=1 on the specific Ids.

The main idea is to somehow mark the rows that have already been computed using the R-script in the stored procedure.

Body:
In a SQL Server database I have an InputTable whose data is given to a stored procedure which runs an R-script on the rows whose Flag=0 after running the script I want to set Flag=1 on the specific rows of InputTable on which the script was executed.

Below is my code for the stored procedure, in this way when I update after the script using the line UPDATE InputTable SET Flag=1 - while the procedure is running and if there is new data inserted in the table, this sets the Flag=1 on the newly inserted data on which the R-script/stored procedure was not executed.

BEGIN
    INSERT INTO OutputTable
    EXECUTE sp_execute_external_script @language = N'R'
        , @script = N'

         <running some R code in here>

        '
        , @input_data_1 = N'SELECT * FROM InputTable WHERE Flag=''0'';'
UPDATE InputTable SET Flag=1
END;

How can I track the Id's of the rows on which the R-script was executed? Currently, I can only return an OutputDataSet which I am Inserting into another table. Can I use another variable to return Id's of OutputDataSet and update Flag=1 on the specific Ids.

The main idea is to somehow mark the rows that have already been computed using the R-script in the stored procedure.