问:
req.isAuthenticated() always returns false
I am new to the Passport.js. Whenever I login or register through the routes, req.isAuthenticated() always returns false and the secrets view is never rendered. Here is my app.js:

`

```<code>require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
const passport = require("passport");
const LocalStrategy = require("passport-local")
const passportLocalMongoose = require("passport-local-mongoose");

const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
uri = "mongodb://localhost:27017/usersDB";

const userSchema = new mongoose.Schema({
    username: String,
    password: String
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.set("view engine", "ejs");

app.use(session({
    secret: "MyLittleSecret",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

app.get("/", function(req, res) {
    res.render("home");
});

app.get("/secrets", function(req, res) {
    if(req.isAuthenticated) {
        res.render("secrets");
    } else {
        res.redirect("/login");
    }
});

app.route("/register")
    .get(function(req, res) {
        res.render("register");
    })

    .post(async function(req, res) {
        await User.register({username: req.body.username}, req.body.password, function(err, user) {
            console.log("In the User.register callback function");
            if(err) {
                console.log(err);
                res.redirect("/register");
            } else {
                passport.authenticate("local")(req, res, function() {
                    res.redirect("/secrets");
                });
            }
        });
    });

app.route("/login")
    .get(function(req, res) {
        res.render("login",{
            errorMessage: ""
        });
    })

    .post(async function(req, res) {
        const userInstance = new User({
            username: req.body.username,
            password: req.body.password
        });

        req.login(userInstance, function(err) {
            if(err) {
                console.log(err);
            } else {
                passport.authenticate("local")(req,res,function() {
                    res.redirect("/secrets");
                });
            }
        });
    });

app.listen(3000, function() {
    console.log("Server started listening to port 3000");
});
</code>```

I searched on the web and tried the various orders of middleware. I could not solve the problem.

Body:
I am new to the Passport.js. Whenever I login or register through the routes, req.isAuthenticated() always returns false and the secrets view is never rendered. Here is my app.js:

`

require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
const passport = require("passport");
const LocalStrategy = require("passport-local")
const passportLocalMongoose = require("passport-local-mongoose");

const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
uri = "mongodb://localhost:27017/usersDB";

const userSchema = new mongoose.Schema({
    username: String,
    password: String
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.set("view engine", "ejs");

app.use(session({
    secret: "MyLittleSecret",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

app.get("/", function(req, res) {
    res.render("home");
});

app.get("/secrets", function(req, res) {
    if(req.isAuthenticated) {
        res.render("secrets");
    } else {
        res.redirect("/login");
    }
});

app.route("/register")
    .get(function(req, res) {
        res.render("register");
    })

    .post(async function(req, res) {
        await User.register({username: req.body.username}, req.body.password, function(err, user) {
            console.log("In the User.register callback function");
            if(err) {
                console.log(err);
                res.redirect("/register");
            } else {
                passport.authenticate("local")(req, res, function() {
                    res.redirect("/secrets");
                });
            }
        });
    });

app.route("/login")
    .get(function(req, res) {
        res.render("login",{
            errorMessage: ""
        });
    })

    .post(async function(req, res) {
        const userInstance = new User({
            username: req.body.username,
            password: req.body.password
        });

        req.login(userInstance, function(err) {
            if(err) {
                console.log(err);
            } else {
                passport.authenticate("local")(req,res,function() {
                    res.redirect("/secrets");
                });
            }
        });
    });

app.listen(3000, function() {
    console.log("Server started listening to port 3000");
});

I searched on the web and tried the various orders of middleware. I could not solve the problem.


来源: stackexchange

问:
GoogleCobal (Free Version) - Working with PySpark with Hive

AnalysisException                         Traceback (most recent call last)

 in
----> 1 spark.sql('''CREATE TABLE employees (
2     employee_id INT,
3     employee_first_name STRING,
4     employee_last_name STRING,
5     employee_salary FLOAT,

2 frames

/usr/local/lib/python3.8/dist-packages/pyspark/sql/utils.py in deco(*a, **kw)
194                 # Hide where the exception came from that shows a non-Pythonic
195                 # JVM exception message.
--> 196                 raise converted from None
197             else:
198                 raise

AnalysisException: Hive support is required to CREATE Hive TABLE (AS SELECT);
'CreateTable pyspark_semistructureddata.employees, org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, ErrorIfExists

`

ContentLicense: CC BY-SA 4.0


问:
web3j-maven-plugin fail to deserialize @openzeppelin dependencies
Trying to generate the java objects for the HelloWorld solidity contract below, it was not able to generate all of it:

```<code>// SPDX-License-Identifier: MIT

pragma solidity >= 0.8.17;

import "../@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../@openzeppelin/contracts/utils/Counters.sol";
import "../@openzeppelin/contracts/access/Ownable.sol";
import "../@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract HelloWorld is ERC721URIStorage, Ownable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIdCounter;
...
}
</code>```

And the returned error:

```<code>[ERROR]
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `[Lorg.web3j.protocol.core.methods.response.AbiDefinition;` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (String)"{
  "name": "@openzeppelin/contracts",
  "description": "Secure Smart Contract library for Solidity",
  "version": "4.8.0",
  ...
  "keywords": [
    "solidity",
    "ethereum"[truncated 304 chars]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from (MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch (DeserializationContext.java:1741)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken (DeserializationContext.java:1515)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken (DeserializationContext.java:1462)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.handleNonArray (ObjectArrayDeserializer.java:343)...
</code>```

Body:
Trying to generate the java objects for the HelloWorld solidity contract below, it was not able to generate all of it:

// SPDX-License-Identifier: MIT

pragma solidity >= 0.8.17;

import "../@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../@openzeppelin/contracts/utils/Counters.sol";
import "../@openzeppelin/contracts/access/Ownable.sol";
import "../@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract HelloWorld is ERC721URIStorage, Ownable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIdCounter;
...
}

And the returned error:

[ERROR]
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `[Lorg.web3j.protocol.core.methods.response.AbiDefinition;` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (String)"{
  "name": "@openzeppelin/contracts",
  "description": "Secure Smart Contract library for Solidity",
  "version": "4.8.0",
  ...
  "keywords": [
    "solidity",
    "ethereum"[truncated 304 chars]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from (MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch (DeserializationContext.java:1741)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken (DeserializationContext.java:1515)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken (DeserializationContext.java:1462)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.handleNonArray (ObjectArrayDeserializer.java:343)...


问:
Why does autocompletion for React work sporadically in Visual Studio Code?
Occasionally entering useState will not result in key suggestions. Even after reinstalling Visual Studio Code, the symptom is the same.

The keyword should appear as below, but as you work on it, you can't see the keyword as above.

You must manually create an import statement at this time.

I will upload the extensions list just in case.


问:
What does this stacktrace in google play console mean?
I can only see a really short stacktrace from google play console. But around 50% of Users are getting this crash.

```<code>pid: 0, tid: 12515 >>> com.example.app <<<

backtrace:
  #00  pc 0x0000000000339f90  /vendor/lib/egl/libGLES_mali.so
  #01  pc 0x000000000033ba07  /vendor/lib/egl/libGLES_mali.so
  #02  pc 0x0000000000348b3f  /vendor/lib/egl/libGLES_mali.so
  #03  pc 0x0000000000348291  /vendor/lib/egl/libGLES_mali.so
  #04  pc 0x000000000001643f  /system/lib/libEGL.so (android::eglSwapBuffersWithDamageKHRImpl(void*, void*, int*, int)+306)
  #05  pc 0x000000000001416f  /system/lib/libEGL.so (eglSwapBuffersWithDamageKHR+66)
  #06  pc 0x000000000016beb1  /data/app/com.example.app-MzvUY2g1duJayWef1JIgfg==/split_config.armeabi_v7a.apk!libflutter.so
</code>```

Can somebody please help me ? Im not really shure if its a flutter bug or my incomeptence :)

Flutter Doctor:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.3.10, on Microsoft Windows [Version 10.0.19045.2364], locale de-DE)
[√] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.1.2)
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.74.2)
[√] Connected device (5 available)
[√] HTTP Host Availability

</code>```

I tried googling the crash but with no success. I cant reproduce the crash locally because I dont know when the app is crashing.

Body:
I can only see a really short stacktrace from google play console. But around 50% of Users are getting this crash.

pid: 0, tid: 12515 >>> com.example.app <<<

backtrace:
  #00  pc 0x0000000000339f90  /vendor/lib/egl/libGLES_mali.so
  #01  pc 0x000000000033ba07  /vendor/lib/egl/libGLES_mali.so
  #02  pc 0x0000000000348b3f  /vendor/lib/egl/libGLES_mali.so
  #03  pc 0x0000000000348291  /vendor/lib/egl/libGLES_mali.so
  #04  pc 0x000000000001643f  /system/lib/libEGL.so (android::eglSwapBuffersWithDamageKHRImpl(void*, void*, int*, int)+306)
  #05  pc 0x000000000001416f  /system/lib/libEGL.so (eglSwapBuffersWithDamageKHR+66)
  #06  pc 0x000000000016beb1  /data/app/com.example.app-MzvUY2g1duJayWef1JIgfg==/split_config.armeabi_v7a.apk!libflutter.so

Can somebody please help me ? Im not really shure if its a flutter bug or my incomeptence :)

Flutter Doctor:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.3.10, on Microsoft Windows [Version 10.0.19045.2364], locale de-DE)
[√] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.1.2)
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.74.2)
[√] Connected device (5 available)
[√] HTTP Host Availability

I tried googling the crash but with no success. I cant reproduce the crash locally because I dont know when the app is crashing.


问:
pytorch_geometric 'GlobalStorage' object has no attribute 'edge_indexes'
I am working on Unsupervised Domain Adaptation and I'm working on a geometric learning approach to this problem. In this approach the a custom model uses the scores of a CNN model (in my case a pretrained ResNet50) and uses the class scores of the original ImageNet to build a graph and applies a GCN to the resulting graph. Here is the code of my forward pass

```<code>def forward(self, x):

    features = self.cnn.forward(x)
    scores = self.dsa.forward(x)
    transposed_scores = torch.transpose(scores, 0, 1)
    adjacency_matrix = torch.matmul(scores, transposed_scores)
    sparse_adj_matrix = dense_to_sparse(adjacency_matrix)

    edge_index, edge_attr = sparse_adj_matrix[0], sparse_adj_matrix[1]
    graph = geometric_data(scores, edge_index=edge_index)
    graph.to(self.device)

    gcn_features = self.gcn(graph.x, graph.edge_indexes)
    concat_features = torch.cat((features, gcn_features))
    domain_classification = self.domain_alignment(concat_features)
    pseudo_label = self.classifier(concat_features)

    return domain_classification, pseudo_label
</code>```

The problem is that when calling the forward method, I get a runtime error saying 'GlobalStorage' object has no attribute 'edge_indexes'. I'm working on Google Colab. What did I get wrong?

EDIT:
The full error traceback is:

```<code>---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/storage.py in __getattr__(self, key)
     61         try:
---> 62             return self[key]
     63         except KeyError:

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/storage.py in __getitem__(self, key)
     84     def __getitem__(self, key: str) -> Any:
---> 85         return self._mapping[key]
     86

KeyError: 'edge_indexes'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)

<ipython-input-32-7436986037c0> in <module>
      7 uda_model.to(device)
      8
----> 9 summary(uda_model, input_size=(3, 224, 224))

/usr/local/lib/python3.8/dist-packages/torchsummary/torchsummary.py in summary(model, input_size, batch_size, device)
     70     # make a forward pass
     71     # print(x.shape)
---> 72     model(*x)
     73
     74     # remove these hooks

/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

<ipython-input-31-1c0d271d6797> in forward(self, x)
     43         graph = geometric_data(scores, edge_index=edge_index)
     44
---> 45         gcn_features = self.gcn(graph.x, graph.edge_indexes)
     46         concat_features = torch.cat((features, gcn_features))
     47         domain_classification = self.domain_alignment(concat_features)

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/data.py in __getattr__(self, key)
    426                 "dataset, remove the 'processed/' directory in the dataset's "
    427                 "root folder and try again.")
--> 428         return getattr(self._store, key)
    429
    430     def __setattr__(self, key: str, value: Any):

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/storage.py in __getattr__(self, key)
     62             return self[key]
     63         except KeyError:
---> 64             raise AttributeError(
     65                 f"'{self.__class__.__name__}' object has no attribute '{key}'")
     66

AttributeError: 'GlobalStorage' object has no attribute 'edge_indexes'
</code>```

For a minimum reproducible example:

```<code>import os
import random

import numpy as np
from PIL import Image
from skimage.metrics import structural_similarity as ssim

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, random_split

from torchvision import transforms

from torch_geometric import nn as geometric_nn
from torch_geometric.data import Data as geometric_data
from torch_geometric.utils import dense_to_sparse

from torchsummary import summary
</code>```

The code here was divided into different cells in Google Colab, here reported in different code sections

```<code>def get_transform():

    transform = list()
    transform.append(transforms.Resize((256, 256)))
    transform.append(transforms.RandomCrop((224, 224)))
    transform.append(transforms.RandomHorizontalFlip(0.5))
    transform.append(transforms.RandomVerticalFlip(0.5))
    transform.append(transforms.GaussianBlur((3, 3)))
    transform.append(transforms.RandomGrayscale(0.5))
    transform.append(transforms.ToTensor())
    transform.append(transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                           std=[0.229, 0.224, 0.225]))

    return transforms.Compose(transform)
</code>```

```<code>class GCANDataset(Dataset):

    def __init__(self, source_path, target_path, transform=None):

        self.transform = transform
        self.source_path = source_path
        self.target_path = target_path

        self.file_counter = 0
        self.source_length = 0

        for folder in os.listdir(source_path):
            path = os.path.join(source_path, folder)
            self.file_counter += len(os.listdir(path))
            self.source_length += len(os.listdir(path))

        for folder in os.listdir(target_path):
            path = os.path.join(target_path, folder)
            self.file_counter += len(os.listdir(path))

    def __len__(self):

        return self.file_counter

    def __getitem__(self, index):

        path_to_use = self.source_path
        domain = 0
        if index > self.source_length:

            path_to_use = self.target_path
            index -= self.source_length
            domain = 1

        label = ''
        image = 0

        for folder in os.listdir(path_to_use):

            item_list = os.listdir(os.path.join(path_to_use, folder))
            if index - len(item_list) < 0:
                file_to_take = len(item_list) - index - 1
                file_path = os.path.join(os.path.join(path_to_use, folder), item_list[file_to_take])
                image = Image.open(file_path)
                label = folder

        if self.transform is not None:

            image = self.transform(image)

        return image, label, domain
</code>```

```<code>class GCANModel(nn.Module):

    def __init__(self, num_classes, gcn_in_channels=224, gcn_out_channels=150, device='cuda:0'):
        super(GCANModel, self).__init__()
        self.device = device
        self.cnn = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
        features = self.cnn.fc.in_features
        combined_features = features + gcn_out_channels
        self.cnn = nn.Sequential(*list(self.cnn.children())[:-1])
        self.dsa = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
        self.gcn = geometric_nn.GCNConv(in_channels=gcn_in_channels,
                                        out_channels=gcn_out_channels)

        self.domain_alignment = nn.Sequential(
            nn.Linear(in_features=combined_features, out_features=1024),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=1024),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=1),
            nn.Sigmoid()
        )

        self.classifier = nn.Sequential(
            nn.Linear(in_features=combined_features, out_features=1024),
            nn.Dropout(p=0.2),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=1024),
            nn.Dropout(p=0.2),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=num_classes),
            nn.Softmax()
        )

    def forward(self, x):

        features = self.cnn.forward(x)
        scores = self.dsa.forward(x)
        transposed_scores = torch.transpose(scores, 0, 1)
        adjacency_matrix = torch.matmul(scores, transposed_scores)
        sparse_adj_matrix = dense_to_sparse(adjacency_matrix)

        edge_index, edge_attr = sparse_adj_matrix[0], sparse_adj_matrix[1]
        graph = geometric_data(scores, edge_index=edge_index)

        gcn_features = self.gcn(graph.x, graph.edge_indexes)
        concat_features = torch.cat((features, gcn_features))
        domain_classification = self.domain_alignment(concat_features)
        pseudo_label = self.classifier(concat_features)

        return domain_classification, pseudo_label
</code>```

```<code>real_world_path = '/content/Adaptiope/product_images'
products_path = '/content/Adaptiope/real_life'
device='cuda:0'
transform = get_transform()
uda_dataset = GCANDataset(source_path=real_world_path,
                              target_path=products_path, transform=transform)

uda_model = GCANModel(20)
uda_model.to(device)

summary(uda_model, input_size=(3, 224, 224))
</code>```

The dataset is Adaptiope, which can be found here. The dataset is divided into 3 domains. The synthetic one is ignored, while on the others only 20 classes are considered. The classes mantained are:

backpack, bookcase, car jack, comb, crown, file cabinet, flat iron, game controller, glasses, helicopter, ice skates, letter tray, monitor, mug, network switch, over-ear headphones, pen, purse, stand mixer, stroller

Body:
I am working on Unsupervised Domain Adaptation and I'm working on a geometric learning approach to this problem. In this approach the a custom model uses the scores of a CNN model (in my case a pretrained ResNet50) and uses the class scores of the original ImageNet to build a graph and applies a GCN to the resulting graph. Here is the code of my forward pass

def forward(self, x):

    features = self.cnn.forward(x)
    scores = self.dsa.forward(x)
    transposed_scores = torch.transpose(scores, 0, 1)
    adjacency_matrix = torch.matmul(scores, transposed_scores)
    sparse_adj_matrix = dense_to_sparse(adjacency_matrix)

    edge_index, edge_attr = sparse_adj_matrix[0], sparse_adj_matrix[1]
    graph = geometric_data(scores, edge_index=edge_index)
    graph.to(self.device)

    gcn_features = self.gcn(graph.x, graph.edge_indexes)
    concat_features = torch.cat((features, gcn_features))
    domain_classification = self.domain_alignment(concat_features)
    pseudo_label = self.classifier(concat_features)

    return domain_classification, pseudo_label

The problem is that when calling the forward method, I get a runtime error saying 'GlobalStorage' object has no attribute 'edge_indexes'. I'm working on Google Colab. What did I get wrong?

EDIT:
The full error traceback is:

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

KeyError                                  Traceback (most recent call last)

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/storage.py in __getattr__(self, key)
     61         try:
---> 62             return self[key]
     63         except KeyError:

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/storage.py in __getitem__(self, key)
     84     def __getitem__(self, key: str) -> Any:
---> 85         return self._mapping[key]
     86

KeyError: 'edge_indexes'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)

<ipython-input-32-7436986037c0> in <module>
      7 uda_model.to(device)
      8
----> 9 summary(uda_model, input_size=(3, 224, 224))

/usr/local/lib/python3.8/dist-packages/torchsummary/torchsummary.py in summary(model, input_size, batch_size, device)
     70     # make a forward pass
     71     # print(x.shape)
---> 72     model(*x)
     73
     74     # remove these hooks

/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

<ipython-input-31-1c0d271d6797> in forward(self, x)
     43         graph = geometric_data(scores, edge_index=edge_index)
     44
---> 45         gcn_features = self.gcn(graph.x, graph.edge_indexes)
     46         concat_features = torch.cat((features, gcn_features))
     47         domain_classification = self.domain_alignment(concat_features)

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/data.py in __getattr__(self, key)
    426                 "dataset, remove the 'processed/' directory in the dataset's "
    427                 "root folder and try again.")
--> 428         return getattr(self._store, key)
    429
    430     def __setattr__(self, key: str, value: Any):

/usr/local/lib/python3.8/dist-packages/torch_geometric/data/storage.py in __getattr__(self, key)
     62             return self[key]
     63         except KeyError:
---> 64             raise AttributeError(
     65                 f"'{self.__class__.__name__}' object has no attribute '{key}'")
     66

AttributeError: 'GlobalStorage' object has no attribute 'edge_indexes'

For a minimum reproducible example:

import os
import random

import numpy as np
from PIL import Image
from skimage.metrics import structural_similarity as ssim

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, random_split

from torchvision import transforms

from torch_geometric import nn as geometric_nn
from torch_geometric.data import Data as geometric_data
from torch_geometric.utils import dense_to_sparse

from torchsummary import summary

The code here was divided into different cells in Google Colab, here reported in different code sections

def get_transform():

    transform = list()
    transform.append(transforms.Resize((256, 256)))
    transform.append(transforms.RandomCrop((224, 224)))
    transform.append(transforms.RandomHorizontalFlip(0.5))
    transform.append(transforms.RandomVerticalFlip(0.5))
    transform.append(transforms.GaussianBlur((3, 3)))
    transform.append(transforms.RandomGrayscale(0.5))
    transform.append(transforms.ToTensor())
    transform.append(transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                           std=[0.229, 0.224, 0.225]))

    return transforms.Compose(transform)

class GCANDataset(Dataset):

    def __init__(self, source_path, target_path, transform=None):

        self.transform = transform
        self.source_path = source_path
        self.target_path = target_path

        self.file_counter = 0
        self.source_length = 0

        for folder in os.listdir(source_path):
            path = os.path.join(source_path, folder)
            self.file_counter += len(os.listdir(path))
            self.source_length += len(os.listdir(path))

        for folder in os.listdir(target_path):
            path = os.path.join(target_path, folder)
            self.file_counter += len(os.listdir(path))

    def __len__(self):

        return self.file_counter

    def __getitem__(self, index):

        path_to_use = self.source_path
        domain = 0
        if index > self.source_length:

            path_to_use = self.target_path
            index -= self.source_length
            domain = 1

        label = ''
        image = 0

        for folder in os.listdir(path_to_use):

            item_list = os.listdir(os.path.join(path_to_use, folder))
            if index - len(item_list) < 0:
                file_to_take = len(item_list) - index - 1
                file_path = os.path.join(os.path.join(path_to_use, folder), item_list[file_to_take])
                image = Image.open(file_path)
                label = folder

        if self.transform is not None:

            image = self.transform(image)

        return image, label, domain

class GCANModel(nn.Module):

    def __init__(self, num_classes, gcn_in_channels=224, gcn_out_channels=150, device='cuda:0'):
        super(GCANModel, self).__init__()
        self.device = device
        self.cnn = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
        features = self.cnn.fc.in_features
        combined_features = features + gcn_out_channels
        self.cnn = nn.Sequential(*list(self.cnn.children())[:-1])
        self.dsa = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
        self.gcn = geometric_nn.GCNConv(in_channels=gcn_in_channels,
                                        out_channels=gcn_out_channels)

        self.domain_alignment = nn.Sequential(
            nn.Linear(in_features=combined_features, out_features=1024),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=1024),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=1),
            nn.Sigmoid()
        )

        self.classifier = nn.Sequential(
            nn.Linear(in_features=combined_features, out_features=1024),
            nn.Dropout(p=0.2),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=1024),
            nn.Dropout(p=0.2),
            nn.ReLU(),
            nn.Linear(in_features=1024, out_features=num_classes),
            nn.Softmax()
        )

    def forward(self, x):

        features = self.cnn.forward(x)
        scores = self.dsa.forward(x)
        transposed_scores = torch.transpose(scores, 0, 1)
        adjacency_matrix = torch.matmul(scores, transposed_scores)
        sparse_adj_matrix = dense_to_sparse(adjacency_matrix)

        edge_index, edge_attr = sparse_adj_matrix[0], sparse_adj_matrix[1]
        graph = geometric_data(scores, edge_index=edge_index)

        gcn_features = self.gcn(graph.x, graph.edge_indexes)
        concat_features = torch.cat((features, gcn_features))
        domain_classification = self.domain_alignment(concat_features)
        pseudo_label = self.classifier(concat_features)

        return domain_classification, pseudo_label

real_world_path = '/content/Adaptiope/product_images'
products_path = '/content/Adaptiope/real_life'
device='cuda:0'
transform = get_transform()
uda_dataset = GCANDataset(source_path=real_world_path,
                              target_path=products_path, transform=transform)

uda_model = GCANModel(20)
uda_model.to(device)

summary(uda_model, input_size=(3, 224, 224))

The dataset is Adaptiope, which can be found here. The dataset is divided into 3 domains. The synthetic one is ignored, while on the others only 20 classes are considered. The classes mantained are:

backpack, bookcase, car jack, comb, crown, file cabinet, flat iron, game controller, glasses, helicopter, ice skates, letter tray, monitor, mug, network switch, over-ear headphones, pen, purse, stand mixer, stroller


问:
Timber tries to log the image in the Request Body and results in an EOF error
I'm trying to use Timber and facing that problem. The task is uploading images via a Post function. While creating okhttp3.RequestBody of the argument of Post function, Timber is logging the elements of the Part's of the RequestBody. There is no problem with normal elements but, Timber is trying to log the whole image and getting EOF error.

The BaseApp:

```<code>class BaseApp : Application() {
    override fun onCreate() {
        super.onCreate()
        if (BuildConfig.DEBUG) {
            Timber.plant(DebugTree())
        }
    }
}
</code>```

The Request Body function:

```<code>    private fun createImageBody(filePath: String): RequestBody {
        val file = File(filePath)
        return file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
    }

    fun getRequestBody(albumImages: List<Album>): RequestBody{
        val bodyBuilder = MultipartBody.Builder().setType(FORM)
        bodyBuilder.addFormDataPart("name", "test")
        for (image in albumImages){
            bodyBuilder.addFormDataPart(
                "image", image.fileName + ".jpg",
                createImageBody(image.filePath)
            )
        }
        return bodyBuilder.build()
    }
</code>```

The Api:

```<code>interface MyApi {
    @POST("/api/upload")
    fun postLocalData(@Body postData: RequestBody): Call<ResponseClass>
}
</code>```

The Api Call:

```<code>val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(
                OkHttpClient.Builder()
                .addInterceptor(CurlInterceptor(Timber::d))
                .build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
myApi.postLocalData(getRequestBody(user, pickedData)).enqueue(object: Callback<ResponseClass> {
    override fun onResponse(call: Call<ResponseClass>, response: Response<ResponseClass>) {
    }
    override fun onFailure(call: Call<ResponseClass>, t: Throwable) {
    }
})
</code>```

The LogCat part:

```<code>1
--af6cf71c-c08e-4ec0-99c6-e69dc8b96364
Content-Disposition: form-data; name="image";
Content-Type: multipart/form-data
Content-Length: 20278632
������JFIF��������������(ICC_PROFILE�� ...
.
.
.
...�34x��l�0zb��~P�S�
read: unexpected EOF!
</code>```

Body:
I'm trying to use Timber and facing that problem. The task is uploading images via a Post function. While creating okhttp3.RequestBody of the argument of Post function, Timber is logging the elements of the Part's of the RequestBody. There is no problem with normal elements but, Timber is trying to log the whole image and getting EOF error.

The BaseApp:

class BaseApp : Application() {
    override fun onCreate() {
        super.onCreate()
        if (BuildConfig.DEBUG) {
            Timber.plant(DebugTree())
        }
    }
}

The Request Body function:

    private fun createImageBody(filePath: String): RequestBody {
        val file = File(filePath)
        return file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
    }

    fun getRequestBody(albumImages: List<Album>): RequestBody{
        val bodyBuilder = MultipartBody.Builder().setType(FORM)
        bodyBuilder.addFormDataPart("name", "test")
        for (image in albumImages){
            bodyBuilder.addFormDataPart(
                "image", image.fileName + ".jpg",
                createImageBody(image.filePath)
            )
        }
        return bodyBuilder.build()
    }

The Api:

interface MyApi {
    @POST("/api/upload")
    fun postLocalData(@Body postData: RequestBody): Call<ResponseClass>
}

The Api Call:

val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(
                OkHttpClient.Builder()
                .addInterceptor(CurlInterceptor(Timber::d))
                .build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
myApi.postLocalData(getRequestBody(user, pickedData)).enqueue(object: Callback<ResponseClass> {
    override fun onResponse(call: Call<ResponseClass>, response: Response<ResponseClass>) {
    }
    override fun onFailure(call: Call<ResponseClass>, t: Throwable) {
    }
})

The LogCat part:

1
--af6cf71c-c08e-4ec0-99c6-e69dc8b96364
Content-Disposition: form-data; name="image";
Content-Type: multipart/form-data
Content-Length: 20278632
������JFIF��������������(ICC_PROFILE�� ...
.
.
.
...�34x��l�0zb��~P�S�
read: unexpected EOF!


问:
Geotools. Gaps and Overlaps detection
I have a number of polygons distributed inside a delimited area.

I would like to know whether there are any gaps or overlaps among them. Is there any Geotools function for this?

Title: Geotools. Gaps and Overlaps detection


问:
Ability to load new samples on echart zoom actions (Zoom in & zoom out)
For the time series chart, on the initial load, we are displaying data aggregated for every 1 hour. when the user zoom in( for example for 4 hours) we see only 4 samples, instead, can we pull more data from the server which is aggregated for lower interval like 30 or 15 and display it in the chart when the user zoom in, display higher interval data on the zoom out.

On zoom in display lower intervals new data like more samples.

On zoom out restore the data which was already available.

Checking if this feature is available or not.


问:
openInputStream cause SecurityException : Permission Denial
I need help with this problem since I'm new to Android.

it crashes on the line where openInputStream() is called with error:

E/ex: java.lang.SecurityException: Permission Denial: reading com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/document/primary/MifareClassicTool/Dump-files/dump-file.dump from pid=19139, uid=10241 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()

code :

uri: content://com.android.externalstorage.documents/document/primary/MifareClassicTool/Dump-files/dump-file.dump

```<code>public static byte[] readUriRaw(Uri uri, Context context) {

    InputStream contentStream
    if (uri == null || context == null) {
        return null;
    }

    try {

           ContentResolver contentResolver = context.getContentResolver();
            int perms =   Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
       context.getContentResolver().takePersistableUriPermission(uri, perms);

        contentStream = context.getContentResolver().openInputStream(uri);

    } catch (SecurityException | IOException ex) {
        Log.e( "ex" , ex.toString());
        return null;
    }

    int len;
    byte[] data = new byte[16384];
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {
        while ((len = contentStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, len);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error while reading from file.", e);
        return null;
    }

    return buffer.toByteArray();
}
</code>```

Thank You in advance.

I need help with this problem.

Thank You in advance.

Body:
I need help with this problem since I'm new to Android.

it crashes on the line where openInputStream() is called with error:

E/ex: java.lang.SecurityException: Permission Denial: reading com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/document/primary/MifareClassicTool/Dump-files/dump-file.dump from pid=19139, uid=10241 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()

code :

uri: content://com.android.externalstorage.documents/document/primary/MifareClassicTool/Dump-files/dump-file.dump

public static byte[] readUriRaw(Uri uri, Context context) {

    InputStream contentStream
    if (uri == null || context == null) {
        return null;
    }

    try {

           ContentResolver contentResolver = context.getContentResolver();
            int perms =   Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
       context.getContentResolver().takePersistableUriPermission(uri, perms);

        contentStream = context.getContentResolver().openInputStream(uri);

    } catch (SecurityException | IOException ex) {
        Log.e( "ex" , ex.toString());
        return null;
    }

    int len;
    byte[] data = new byte[16384];
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {
        while ((len = contentStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, len);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error while reading from file.", e);
        return null;
    }

    return buffer.toByteArray();
}

Thank You in advance.

I need help with this problem.

Thank You in advance.


问:
inetmanet-4.x buiid error - undefined symbol of zlib.h
I got an error while building the project inetmanet-4.x in omnet++ 6.0.1. It says undefned symbol for gzclose_w, gzopen, gzwrite, gzeof, gzread, gzclose. The error is thrown from ICCLog.cc file. The imported header fiile"ICCLog.h" contains #include <zlib.h> header file, I assume this should have the definitions for the above symbol. I'm still getting errors.

The snippet of error:

```<code>Creating shared library: ../out/clang-debug/src/libINET_dbg.dll
ld.lld: error: undefined symbol: gzclose_w
>>> referenced by inet/icancloud/Base/Util/Log/ICCLog.cc:92
</code>```

I think these errors are generated at linking time rather than compile time. The final error looks like this:

```<code>clang++: error: linker command failed with exit code 1 (use -v to see invocation)
C:/omnet/omnetpp-6.0.1/tools/win32.x86_64/mingw64/bin/llvm-ar.exe: error: unable to load '../out/clang-debug/src/libINET_dbg.dll.a': No such file or directory
make[1]: *** [Makefile:2154: ../out/clang-debug/src/libINET_dbg.dll] Error 1
</code>```

Please help me with resolve this issue. Thanks in advance.

Body:
I got an error while building the project inetmanet-4.x in omnet++ 6.0.1. It says undefned symbol for gzclose_w, gzopen, gzwrite, gzeof, gzread, gzclose. The error is thrown from ICCLog.cc file. The imported header fiile"ICCLog.h" contains #include <zlib.h> header file, I assume this should have the definitions for the above symbol. I'm still getting errors.

The snippet of error:

Creating shared library: ../out/clang-debug/src/libINET_dbg.dll
ld.lld: error: undefined symbol: gzclose_w
>>> referenced by inet/icancloud/Base/Util/Log/ICCLog.cc:92

I think these errors are generated at linking time rather than compile time. The final error looks like this:

clang++: error: linker command failed with exit code 1 (use -v to see invocation)
C:/omnet/omnetpp-6.0.1/tools/win32.x86_64/mingw64/bin/llvm-ar.exe: error: unable to load '../out/clang-debug/src/libINET_dbg.dll.a': No such file or directory
make[1]: *** [Makefile:2154: ../out/clang-debug/src/libINET_dbg.dll] Error 1

Please help me with resolve this issue. Thanks in advance.


问:
Clip complex shape on canvas
I'm trying to clip an image with a shape that the user can draw.
Here is what I have so far:

This shape is then draggable and let the exact same shape under. But the draggable part should not be dark, it should be a clip of the image under except that I cannot create such a complicated clip, here is what I need to resolve:

```<code>  const [lines, setLines] = React.useState([]);
...

 lines.map((line, i) => (
              <Line
                key={i}
                points={line.points}      // Those are the points used to draw the shape
                stroke="#333"
                strokeWidth={1}
                tension={0.5}
                lineCap="round"
                lineJoin="round"
                closed
                fill="#333"
              />
            ))

...
            <Group clipFunc={ctx => {
              ctx.beginPath()
              lines.map((line, i) => (
                ctx.lineTo(line.points)     // Something here to map all the coordinate
              )).                           // of the shape is what I'm thinking about
              ctx.closePath()
            }}
              draggable
              stroke="#333"
            >
              <Image image={image} width={600} height={400} fill="black" />
            </Group>
</code>```

Im using React.js and Konva.js
Thank you.

Title: Clip complex shape on canvas

Body:
I'm trying to clip an image with a shape that the user can draw.
Here is what I have so far:

This shape is then draggable and let the exact same shape under. But the draggable part should not be dark, it should be a clip of the image under except that I cannot create such a complicated clip, here is what I need to resolve:

  const [lines, setLines] = React.useState([]);
...

 lines.map((line, i) => (
              <Line
                key={i}
                points={line.points}      // Those are the points used to draw the shape
                stroke="#333"
                strokeWidth={1}
                tension={0.5}
                lineCap="round"
                lineJoin="round"
                closed
                fill="#333"
              />
            ))

...
            <Group clipFunc={ctx => {
              ctx.beginPath()
              lines.map((line, i) => (
                ctx.lineTo(line.points)     // Something here to map all the coordinate
              )).                           // of the shape is what I'm thinking about
              ctx.closePath()
            }}
              draggable
              stroke="#333"
            >
              <Image image={image} width={600} height={400} fill="black" />
            </Group>

Im using React.js and Konva.js
Thank you.


问:
Adding regular expression find option to UITextView
I'm trying to implement a regular expression search in a UITextView with the UITextView.findInteraction introduced in iOS 16. The documentation shows a UIFindInteraction.optionsMenuProvider property and reads

You use this closure to modify, augement or omit options from the
default set available in UITextSearchOptions.

But it's not clear how to actually modify the UITextSearchOptions, and where these options are even stored. And how would I omit options? How can the UIActions passed as the only argument to UIFindInteraction.optionsMenuProvider be distinguished from one another?


问:
Parser issue through serialport package on Node.js
The code is almost identical from here.

Once I insert the parser (in order to separate lines), it cannot display anything on the side of server console. However, if I run port.on, there is no issue. Hence, I cannot execute properly none of parsers which are listed in here.

Testing scenario: Sending "test\r\n test\r\n test" from com port (connected to the COM2) terminal.

```<code>var express              = require('express');
app                      = express();
server                   = require('http').createServer(app);
io                       = require('socket.io')(server);
server.listen(8080);
app.use(express.static('public'));

const { SerialPort } = require('serialport')
const { ReadlineParser } = require('@serialport/parser-readline')
const port = new SerialPort({ path: 'COM2', baudRate: 9600 })

const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
parser.on('data', console.log)
//port.on('data', console.log)
</code>```

SerialPort Version
10.5.0

Node Version v18.12.1

It might be related with version upgrade ? How can I properly bind the parser side into serialport ?

Body:
The code is almost identical from here.

Once I insert the parser (in order to separate lines), it cannot display anything on the side of server console. However, if I run port.on, there is no issue. Hence, I cannot execute properly none of parsers which are listed in here.

Testing scenario: Sending "test\r\n test\r\n test" from com port (connected to the COM2) terminal.

var express              = require('express');
app                      = express();
server                   = require('http').createServer(app);
io                       = require('socket.io')(server);
server.listen(8080);
app.use(express.static('public'));

const { SerialPort } = require('serialport')
const { ReadlineParser } = require('@serialport/parser-readline')
const port = new SerialPort({ path: 'COM2', baudRate: 9600 })

const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
parser.on('data', console.log)
//port.on('data', console.log)

SerialPort Version
10.5.0

Node Version v18.12.1

It might be related with version upgrade ? How can I properly bind the parser side into serialport ?


问:
Monitoring AWS CodeBuild With CloudWatch Alarms in the CDK
Info: The AWS Console offers CloudWatch metrics for CodeBuild, such as FailedBuilds, Duration, InstallDuration, FinalizingDuration... There are roughly 40 metric options.

Problem: When creating with the pipelines in the CDK, I cannot find the equivalent monitoring solution for the CodeBuildStep (Link).

Typically, for example, the NodejsFunction has metric props which I can use to create AlarmProps and thus monitor.

CDK Pipeline Code:

    this.codePipeline = new CodePipeline(this, `${environment}-${appName}-`, {
      pipelineName: `${environment}-${appName}-`,
      selfMutation: true,
      crossAccountKeys: false,
      role: this.codePipelineRole,
      cliVersion: "21.0.0",
      synth: new CodeBuildStep("Deployment", {
        input: CodePipelineSource.codeCommit(this.codeRepository, environment),
        env: {environment},
        installCommands: ["npm uninstall -g aws-cdk", "npm i -g npm@latest", "npm install -g aws-cdk"],
        commands: [
          "cd backend",
          "npm ci",
          "npm run build",
          "npx cdk synth",
        ],
        primaryOutputDirectory: "backend/cdk.out",
        buildEnvironment: {
          computeType: ComputeType.SMALL,
        },
      })
    });
```
<p><strong>Desired Alarm Props:</strong></p>
<pre class="lang-js prettyprint-override"><code>    const codeBuildPostBuildDuration = (codeBuild: CodeBuildStep): AlarmProps => ({
        alarmName: "codeBuildPostBuildDuration",
        comparisonOperator: ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
        threshold: 1,
        evaluationPeriods: 1,
        metric: codeBuild.FailedBuilds()
    });
</code>```

What can I do to monitor and create alarms for my CDK CI/CD Pipeline?

Body:
Info: The AWS Console offers CloudWatch metrics for CodeBuild, such as FailedBuilds, Duration, InstallDuration, FinalizingDuration... There are roughly 40 metric options.

Problem: When creating with the pipelines in the CDK, I cannot find the equivalent monitoring solution for the CodeBuildStep (Link).

Typically, for example, the NodejsFunction has metric props which I can use to create AlarmProps and thus monitor.

CDK Pipeline Code:

    this.codePipeline = new CodePipeline(this, `${environment}-${appName}-`, {
      pipelineName: `${environment}-${appName}-`,
      selfMutation: true,
      crossAccountKeys: false,
      role: this.codePipelineRole,
      cliVersion: "21.0.0",
      synth: new CodeBuildStep("Deployment", {
        input: CodePipelineSource.codeCommit(this.codeRepository, environment),
        env: {environment},
        installCommands: ["npm uninstall -g aws-cdk", "npm i -g npm@latest", "npm install -g aws-cdk"],
        commands: [
          "cd backend",
          "npm ci",
          "npm run build",
          "npx cdk synth",
        ],
        primaryOutputDirectory: "backend/cdk.out",
        buildEnvironment: {
          computeType: ComputeType.SMALL,
        },
      })
    });

Desired Alarm Props:

    const codeBuildPostBuildDuration = (codeBuild: CodeBuildStep): AlarmProps => ({
        alarmName: "codeBuildPostBuildDuration",
        comparisonOperator: ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
        threshold: 1,
        evaluationPeriods: 1,
        metric: codeBuild.FailedBuilds()
    });

What can I do to monitor and create alarms for my CDK CI/CD Pipeline?


问:
My Decision Tree predict() method returns the same label for every test example
My Decision tree Classifier returns the same class label for every prediction "setosa" when minParentSize is set to 1 and in other cases returns a prediction accuracy of only 5%. I have spent days trying to fix this and assume it is something wrong with my buildTree method as my predict method is very simple and just loops through the nodes checking if the currentNode cutPoint is lower than the current feature value in test_examples.

Here is my buildTree() and findBestCutPoint()

```<code>function bestCut = findBestCutPoint(obj,node)%find the best cut point for the current node
            bestCut.CutPoint = 0;
            bestCut.CutPredictorIndex = 0;
            bestCut.CutIndex = 0;
            bestCut.ShouldCut = true;
            bestGDI = Inf;
            parentLabels = obj.Y(node.StartIndex:node.EndIndex, 1);
            parentProbability = node.Size/length(obj.X);
            parentGDI = weightedGDI(parentLabels, obj.Y);
            parentSplitVal = parentProbability * parentGDI;
            for i = 1:size(obj.X,2)% Loop through all the features
                values = unique(obj.X(node.StartIndex:node.EndIndex, i));% Loop through all the unique values of the feature
                values = sort(values);
                for j = 1:length(values) % Calculate the weighted impurity of the two cuts
                    leftLabels = obj.Y(node.StartIndex:node.EndIndex, 1);
                    rightLabels = obj.Y(node.StartIndex:node.EndIndex, 1);

                    leftProb = obj.X(node.StartIndex:node.EndIndex, i) < values(j);
                    rightProb = obj.X(node.StartIndex:node.EndIndex, i) >= values(j);
                    leftLabels = leftLabels(obj.X(node.StartIndex:node.EndIndex, i) < values(j));
                    rightLabels = rightLabels(obj.X(node.StartIndex:node.EndIndex, i) >= values(j));

                    leftProbability = length(leftProb)/length(obj.X);
                    rightProbability = length(rightProb)/length(obj.X);

                    leftGDI = weightedGDI(leftLabels, obj.Y);
                    rightGDI = weightedGDI(rightLabels, obj.Y);

                    cutGDI = ((leftProbability * leftGDI) + (rightProbability * rightGDI));% Calculate the weighted impurity of the split
                    if cutGDI < bestGDI  % Update the best split if the current split has a lower GDI
                        bestGDI = cutGDI;
                        value = (values(j) + values(j-1))/2;%added
                        bestCut.CutPoint = value; %swapped values(j)
                        bestCut.CutPredictorIndex = i;
                        bestCut.CutIndex = find(obj.X(:, i) == values(j), 1, 'first');
                    end
                end
            end
            if parentSplitVal <= bestGDI
                bestCut.ShouldCut = false;
                return
            end
        end

        % the fitting phase:
        function treenode = buildTree(obj,node)
            CutPoint = findBestCutPoint(obj,node);
            if node.Size <= obj.MinParentSize || obj.CurrentNumSplits >= obj.MaxNumSplits  || CutPoint.ShouldCut == false
                node.Leaf = true;% Mark the node as a leaf node
                labels = obj.Y(node.StartIndex:node.EndIndex); %gather all the labels for the data in the nodes range
                node.NodeClass = mode(labels);%find the most frequent label and classify the node as such
                obj.Nodes{end+1} = node;%add the node to the Nodes cell array
                obj.Leaves{end+1} = node;
                treenode = node;%return the node so it can be added as a child
                return;
            end
            leftChild = Node(node.StartIndex, CutPoint.CutIndex - 1);%create a node called left child with the same start index as the original node and end index as the last one before the cut index
            rightChild = Node(CutPoint.CutIndex, node.EndIndex);% create the right child node with the cut index as sindex and the same eindex as the original node
            obj.CurrentNumSplits = obj.CurrentNumSplits + 1;%update the number of splits
            node.CutPoint = CutPoint.CutPoint;%save the cutpoint
            node.CutPredictorIndex = CutPoint.CutPredictorIndex;%save the cutpredictor index
            %labels = obj.Y(node.StartIndex:node.EndIndex); %gather all the labels for the data in the nodes range
            %node.NodeClass = mode(labels); %find the most frequent label and classify the node as such
            node.Left = buildTree(obj,leftChild);%recusively build the tree from the left child and save it as the original nodes left child changed from CHILDREN{1}
            node.Right = buildTree(obj,rightChild);%recusively build the tree from the right child and save it as the original nodes right child
            treenode = node;%return the node
            obj.Nodes{end+1} = treenode;%add the node to the nodes cell array
        end

</code>```

And here is my predict()

```<code> function predictions = predict(obj, test_examples)
            % get ready to store our predicted class labels:
            predictions = categorical;
            for i = 1:length(test_examples)
                thisNode = obj.Root;
                while thisNode.Leaf == false
                    if test_examples(i,thisNode.CutPredictorIndex) < thisNode.CutPoint
                        k = findNodeIndex(obj,thisNode.Left);
                        thisNode = obj.Nodes{k};
                        disp('Left Child')
                        disp(thisNode)
                    else
                        k = findNodeIndex(obj,thisNode.Right);
                        thisNode = obj.Nodes{k};
                        disp('Right Child')
                        disp(thisNode)
                    end
                end
                predictions(i,1) = thisNode.NodeClass;
                disp('leaf')
                disp(thisNode)
            end
        end
</code>```

The data set I'm using is set out as a 90x2 array for training examples with 2 features and a 90x1 for the
training labels.
Testing data is 60x2 for the examples and 60x1 for the labels.

I am trying to train a decision tree based off the training data and labels to predict what labels the testing data has.
The testing data was predicted to be all the same label "setosa"

Body:
My Decision tree Classifier returns the same class label for every prediction "setosa" when minParentSize is set to 1 and in other cases returns a prediction accuracy of only 5%. I have spent days trying to fix this and assume it is something wrong with my buildTree method as my predict method is very simple and just loops through the nodes checking if the currentNode cutPoint is lower than the current feature value in test_examples.

Here is my buildTree() and findBestCutPoint()

function bestCut = findBestCutPoint(obj,node)%find the best cut point for the current node
            bestCut.CutPoint = 0;
            bestCut.CutPredictorIndex = 0;
            bestCut.CutIndex = 0;
            bestCut.ShouldCut = true;
            bestGDI = Inf;
            parentLabels = obj.Y(node.StartIndex:node.EndIndex, 1);
            parentProbability = node.Size/length(obj.X);
            parentGDI = weightedGDI(parentLabels, obj.Y);
            parentSplitVal = parentProbability * parentGDI;
            for i = 1:size(obj.X,2)% Loop through all the features
                values = unique(obj.X(node.StartIndex:node.EndIndex, i));% Loop through all the unique values of the feature
                values = sort(values);
                for j = 1:length(values) % Calculate the weighted impurity of the two cuts
                    leftLabels = obj.Y(node.StartIndex:node.EndIndex, 1);
                    rightLabels = obj.Y(node.StartIndex:node.EndIndex, 1);

                    leftProb = obj.X(node.StartIndex:node.EndIndex, i) < values(j);
                    rightProb = obj.X(node.StartIndex:node.EndIndex, i) >= values(j);
                    leftLabels = leftLabels(obj.X(node.StartIndex:node.EndIndex, i) < values(j));
                    rightLabels = rightLabels(obj.X(node.StartIndex:node.EndIndex, i) >= values(j));

                    leftProbability = length(leftProb)/length(obj.X);
                    rightProbability = length(rightProb)/length(obj.X);

                    leftGDI = weightedGDI(leftLabels, obj.Y);
                    rightGDI = weightedGDI(rightLabels, obj.Y);

                    cutGDI = ((leftProbability * leftGDI) + (rightProbability * rightGDI));% Calculate the weighted impurity of the split
                    if cutGDI < bestGDI  % Update the best split if the current split has a lower GDI
                        bestGDI = cutGDI;
                        value = (values(j) + values(j-1))/2;%added
                        bestCut.CutPoint = value; %swapped values(j)
                        bestCut.CutPredictorIndex = i;
                        bestCut.CutIndex = find(obj.X(:, i) == values(j), 1, 'first');
                    end
                end
            end
            if parentSplitVal <= bestGDI
                bestCut.ShouldCut = false;
                return
            end
        end

        % the fitting phase:
        function treenode = buildTree(obj,node)
            CutPoint = findBestCutPoint(obj,node);
            if node.Size <= obj.MinParentSize || obj.CurrentNumSplits >= obj.MaxNumSplits  || CutPoint.ShouldCut == false
                node.Leaf = true;% Mark the node as a leaf node
                labels = obj.Y(node.StartIndex:node.EndIndex); %gather all the labels for the data in the nodes range
                node.NodeClass = mode(labels);%find the most frequent label and classify the node as such
                obj.Nodes{end+1} = node;%add the node to the Nodes cell array
                obj.Leaves{end+1} = node;
                treenode = node;%return the node so it can be added as a child
                return;
            end
            leftChild = Node(node.StartIndex, CutPoint.CutIndex - 1);%create a node called left child with the same start index as the original node and end index as the last one before the cut index
            rightChild = Node(CutPoint.CutIndex, node.EndIndex);% create the right child node with the cut index as sindex and the same eindex as the original node
            obj.CurrentNumSplits = obj.CurrentNumSplits + 1;%update the number of splits
            node.CutPoint = CutPoint.CutPoint;%save the cutpoint
            node.CutPredictorIndex = CutPoint.CutPredictorIndex;%save the cutpredictor index
            %labels = obj.Y(node.StartIndex:node.EndIndex); %gather all the labels for the data in the nodes range
            %node.NodeClass = mode(labels); %find the most frequent label and classify the node as such
            node.Left = buildTree(obj,leftChild);%recusively build the tree from the left child and save it as the original nodes left child changed from CHILDREN{1}
            node.Right = buildTree(obj,rightChild);%recusively build the tree from the right child and save it as the original nodes right child
            treenode = node;%return the node
            obj.Nodes{end+1} = treenode;%add the node to the nodes cell array
        end

And here is my predict()

 function predictions = predict(obj, test_examples)
            % get ready to store our predicted class labels:
            predictions = categorical;
            for i = 1:length(test_examples)
                thisNode = obj.Root;
                while thisNode.Leaf == false
                    if test_examples(i,thisNode.CutPredictorIndex) < thisNode.CutPoint
                        k = findNodeIndex(obj,thisNode.Left);
                        thisNode = obj.Nodes{k};
                        disp('Left Child')
                        disp(thisNode)
                    else
                        k = findNodeIndex(obj,thisNode.Right);
                        thisNode = obj.Nodes{k};
                        disp('Right Child')
                        disp(thisNode)
                    end
                end
                predictions(i,1) = thisNode.NodeClass;
                disp('leaf')
                disp(thisNode)
            end
        end

The data set I'm using is set out as a 90x2 array for training examples with 2 features and a 90x1 for the
training labels.
Testing data is 60x2 for the examples and 60x1 for the labels.

I am trying to train a decision tree based off the training data and labels to predict what labels the testing data has.
The testing data was predicted to be all the same label "setosa"


问:
I am not sure why I am getting a "Compile Error: Method or data member not found" for my code in VBA. It's highlighting "Sub AcronymParser()"
```<code>Sub AcronymParser()

    'Declare variables
    Dim AcronymList As New Collection
    Dim Acronym As String
    Dim Definition As String
    Dim Rng As Range
    Dim Doc As Document
    Dim AcroTable As Table

    'Set the document object
    Set Doc = ActiveDocument

    'Iterate through the document and find all acronyms
    For Each Rng In Doc.Words
        If Rng.Font.Bold And Rng.Characters(1).Font.AllCaps And Rng.Characters(2).Font.AllLower Then
            'Add the acronym to the list, along with its definition
            Acronym = Rng.Text
            Definition = Rng.Next.Text
            AcronymList.Add Definition, Acronym
        End If
    Next Rng

    'Create a new table
    Set AcroTable = Doc.Tables.Add(Range:=Doc.Content, NumRows:=AcronymList.Count + 1, NumColumns:=2)

    'Set the column widths
    AcroTable.Columns(1).SetWidth ColumnWidth:=InchesToPoints(1), RulerStyle:=wdAdjustNone
    AcroTable.Columns(2).SetWidth ColumnWidth:=InchesToPoints(3), RulerStyle:=wdAdjustNone

    'Add the headings for the table
    AcroTable.Cell(1, 1).Range.Text = "Acronym"
    AcroTable.Cell(1, 2).Range.Text = "Definition"

    'Iterate through the acronym list and add the acronyms and definitions to the table
    For i = 1 To AcronymList.Count
        AcroTable.Cell(i + 1, 1).Range.Text = AcronymList.Keys(i - 1)
        AcroTable.Cell(i + 1, 2).Range.Text = AcronymList(i)
    Next i
End Sub
</code>```

I tried the above script with the expectation that it would run. For some reason, I keep getting the same error. Not sure what to do here.

Body:
Sub AcronymParser()

    'Declare variables
    Dim AcronymList As New Collection
    Dim Acronym As String
    Dim Definition As String
    Dim Rng As Range
    Dim Doc As Document
    Dim AcroTable As Table

    'Set the document object
    Set Doc = ActiveDocument

    'Iterate through the document and find all acronyms
    For Each Rng In Doc.Words
        If Rng.Font.Bold And Rng.Characters(1).Font.AllCaps And Rng.Characters(2).Font.AllLower Then
            'Add the acronym to the list, along with its definition
            Acronym = Rng.Text
            Definition = Rng.Next.Text
            AcronymList.Add Definition, Acronym
        End If
    Next Rng

    'Create a new table
    Set AcroTable = Doc.Tables.Add(Range:=Doc.Content, NumRows:=AcronymList.Count + 1, NumColumns:=2)

    'Set the column widths
    AcroTable.Columns(1).SetWidth ColumnWidth:=InchesToPoints(1), RulerStyle:=wdAdjustNone
    AcroTable.Columns(2).SetWidth ColumnWidth:=InchesToPoints(3), RulerStyle:=wdAdjustNone

    'Add the headings for the table
    AcroTable.Cell(1, 1).Range.Text = "Acronym"
    AcroTable.Cell(1, 2).Range.Text = "Definition"

    'Iterate through the acronym list and add the acronyms and definitions to the table
    For i = 1 To AcronymList.Count
        AcroTable.Cell(i + 1, 1).Range.Text = AcronymList.Keys(i - 1)
        AcroTable.Cell(i + 1, 2).Range.Text = AcronymList(i)
    Next i
End Sub

I tried the above script with the expectation that it would run. For some reason, I keep getting the same error. Not sure what to do here.


问:
IBM MQ user access permission: put/get messages on a queue
How do I set MQ permissions for a windows user (username and password)
to be able to use a queue, so a java client can get and put messages ?

I already have a queue manager up and listening on (windows) port 1414 on locallost and a queue defined.


问:
Import module AND from module import in the same import
I'm trying to generate a way of storing and retriving results throughout my code.

Solution should:

Be able to store results (partial or final) easily, from any module in the code.

Should be nice beign able to retrive those results easily, from any routine in the code.

Be able to store results in any format (mainly DataFrames, Series, np arrays and custom objects).

Allow me to bypass data calculation to focus on output development.

My initial solution consisted on something of this sort:

output.py:

import pickle

results = {}

def store_res(result_key, result_data):
    """Store result for output processing."""
    if result_key in results:
        raise Exception('Key is already in dictionary')

    results[result_key] = result_data

def load_previous_res():
    """Load previously computed results for output processing."""
    global results
    results = pickle.load(open('results/results.pkl', 'rb'))
```
<p><strong>main.py</strong>:</p>
<pre class="lang-py prettyprint-override"><code>import pickle

from output import load_previous_res, results, store_res

def process_data():
    some_result = 42
    store_result('some_valuable_number', some_result)

    [...]

    # After all routines have been performed
    pickle.dump(results, open('results/results.pkl', 'wb'))

def main():
    response = input('Load and use the last computed results? [(Y)es, (N)o]')
    if response.lower() not in ['yes', 'y']:
        #Perform data processing and store resutls in pickle file
        process_data()
    else:
        load_previous_res() # <-- THIS IS NOT WORKING AS INTENDED
</code>```

Results are saved and pickled correctly, but when I run the program again and I want to bypass the calculations and just load the results. I except to get the same "results" that was pickled but I'm getting an empty dictionary.

If I change my import statemets (and calls) in main.py to

import pickle

from output import store_res
import output

def process_data():
    some_result = 42
    store_result('some_valuable_number', some_result)

    [...]

    # After all routines have been performed
    results.
    pickle.dump(output.results, open('results/results.pkl', 'wb'))

def main():
    response = input('Load and use the last computed results? [(Y)es, (N)o]')
    if response.lower() not in ['yes', 'y']:
        #Perform data processing and store results in pickle file
        process_data()
    else:
        output.load_previous_res() # <-- THIS WORKS AS INTENDED
```

I don't know why original solution doesn't work, and also I don't know if importing both a module and a function of that module in the same import block is correct.

Sorry for the long quesiton!

Body:
I'm trying to generate a way of storing and retriving results throughout my code.

Solution should:

Be able to store results (partial or final) easily, from any module in the code.

Should be nice beign able to retrive those results easily, from any routine in the code.

Be able to store results in any format (mainly DataFrames, Series, np arrays and custom objects).

Allow me to bypass data calculation to focus on output development.

My initial solution consisted on something of this sort:

output.py:

import pickle

results = {}

def store_res(result_key, result_data):
    """Store result for output processing."""
    if result_key in results:
        raise Exception('Key is already in dictionary')

    results[result_key] = result_data

def load_previous_res():
    """Load previously computed results for output processing."""
    global results
    results = pickle.load(open('results/results.pkl', 'rb'))

main.py:

import pickle

from output import load_previous_res, results, store_res

def process_data():
    some_result = 42
    store_result('some_valuable_number', some_result)

    [...]

    # After all routines have been performed
    pickle.dump(results, open('results/results.pkl', 'wb'))

def main():
    response = input('Load and use the last computed results? [(Y)es, (N)o]')
    if response.lower() not in ['yes', 'y']:
        #Perform data processing and store resutls in pickle file
        process_data()
    else:
        load_previous_res() # <-- THIS IS NOT WORKING AS INTENDED

Results are saved and pickled correctly, but when I run the program again and I want to bypass the calculations and just load the results. I except to get the same "results" that was pickled but I'm getting an empty dictionary.

If I change my import statemets (and calls) in main.py to

import pickle

from output import store_res
import output

def process_data():
    some_result = 42
    store_result('some_valuable_number', some_result)

    [...]

    # After all routines have been performed
    results.
    pickle.dump(output.results, open('results/results.pkl', 'wb'))

def main():
    response = input('Load and use the last computed results? [(Y)es, (N)o]')
    if response.lower() not in ['yes', 'y']:
        #Perform data processing and store results in pickle file
        process_data()
    else:
        output.load_previous_res() # <-- THIS WORKS AS INTENDED

I don't know why original solution doesn't work, and also I don't know if importing both a module and a function of that module in the same import block is correct.

Sorry for the long quesiton!


问:
How to close websocket with puppeteer?
I want close websocket using puppeteer. I tried to find on the Internet how to close the websocket through puppeteer, but I did not find.

I have such code:

```<code>let Network = page._client();

Network.on("Network.webSocketCreated", ({requestId, url}) => {
    if(url === "ws://127.0.0.1:6463/?v=1") {
        //close this websocket
    }
});
</code>```

If the websocket opens I need to close it.

Title: How to close websocket with puppeteer?

Body:
I want close websocket using puppeteer. I tried to find on the Internet how to close the websocket through puppeteer, but I did not find.

I have such code:

let Network = page._client();

Network.on("Network.webSocketCreated", ({requestId, url}) => {
    if(url === "ws://127.0.0.1:6463/?v=1") {
        //close this websocket
    }
});

If the websocket opens I need to close it.


问:
First time install of Laravel with Breeze inside Homestead - npm symlink issue with acorn
I'm still new to Laravel and Homestead but have been working through all the Laracast tutorials with no problems in the past couple of weeks.

Now we've come to starting a brand new project using laravel/breeze instead of doing all the authentication by hand.

I'm using Homestead 13.3.2 and Vagrant 2.3.3 on a Windows 10 machine.

The error occurs when I run the install command:

php artisan breeze:install

```<code>npm ERR! code EPROTO
npm ERR! syscall symlink
npm ERR! path ../acorn/bin/acorn
npm ERR! dest /home/vagrant/Code/flashcards/node_modules/.bin/acorn
npm ERR! errno -71
npm ERR! EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/home/vagrant/Code/flashcards/node_modules/.bin/acorn'

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2022-12-30T14_42_25_106Z-debug-0.log

   INFO  Breeze scaffolding installed successfully.
</code>```

I'm running node v14.20.0 npm 8.16.0.

the slightly more verbose error from the log says

```<code>08 verbose stack Error: EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/home/vagrant/Code/flashcards/node_modules/.bin/acorn'
709 verbose cwd /home/vagrant/Code/flashcards
710 verbose Linux 5.4.0-124-generic
711 verbose node v14.20.0
712 verbose npm  v8.16.0
713 error code EPROTO
714 error syscall symlink
715 error path ../acorn/bin/acorn
716 error dest /home/vagrant/Code/flashcards/node_modules/.bin/acorn
717 error errno -71
718 error EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/home/vagrant/Code/flashcards/node_modules/.bin/acorn'
719 verbose exit -71
</code>```

Body:
I'm still new to Laravel and Homestead but have been working through all the Laracast tutorials with no problems in the past couple of weeks.

Now we've come to starting a brand new project using laravel/breeze instead of doing all the authentication by hand.

I'm using Homestead 13.3.2 and Vagrant 2.3.3 on a Windows 10 machine.

The error occurs when I run the install command:

php artisan breeze:install

npm ERR! code EPROTO
npm ERR! syscall symlink
npm ERR! path ../acorn/bin/acorn
npm ERR! dest /home/vagrant/Code/flashcards/node_modules/.bin/acorn
npm ERR! errno -71
npm ERR! EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/home/vagrant/Code/flashcards/node_modules/.bin/acorn'

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2022-12-30T14_42_25_106Z-debug-0.log

   INFO  Breeze scaffolding installed successfully.

I'm running node v14.20.0 npm 8.16.0.

the slightly more verbose error from the log says

08 verbose stack Error: EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/home/vagrant/Code/flashcards/node_modules/.bin/acorn'
709 verbose cwd /home/vagrant/Code/flashcards
710 verbose Linux 5.4.0-124-generic
711 verbose node v14.20.0
712 verbose npm  v8.16.0
713 error code EPROTO
714 error syscall symlink
715 error path ../acorn/bin/acorn
716 error dest /home/vagrant/Code/flashcards/node_modules/.bin/acorn
717 error errno -71
718 error EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/home/vagrant/Code/flashcards/node_modules/.bin/acorn'
719 verbose exit -71


问:
How to exit and remove Pssession without prompt for session number
The suggested post does not discuss exiting and removing the pssession.

This code snippet is going to be used as part of a GUI toolbox, so the user will not have access to the PS console. The script performs almost perfect except for exiting and removing the Pssession at the end.

```<code>$name = "Remote PC Name"
CMD /C SC \\$name Start WinRM
New-PSSession -ComputerName $name
Get-PSSession
Enter-PSSession -ComputerName $name
(Get-BitLockerVolume -MountPoint C).Keyprotector  | Out-GridView
Get-BitLockerVolume
exit-pssession
Get-pssession
Remove-PSSession
CMD /C SC \\$name Stop WinRM
</code>```

Body:
The suggested post does not discuss exiting and removing the pssession.

This code snippet is going to be used as part of a GUI toolbox, so the user will not have access to the PS console. The script performs almost perfect except for exiting and removing the Pssession at the end.

$name = "Remote PC Name"
CMD /C SC \\$name Start WinRM
New-PSSession -ComputerName $name
Get-PSSession
Enter-PSSession -ComputerName $name
(Get-BitLockerVolume -MountPoint C).Keyprotector  | Out-GridView
Get-BitLockerVolume
exit-pssession
Get-pssession
Remove-PSSession
CMD /C SC \\$name Stop WinRM


问:
BrowserRouter to HashRouter for Github pages
I have a React app that was using BrowserRouter and was working fine, but I switched to HashRouter because I want to host the app on GitHub Pages. Now, when I try to navigate to a route using a button or a link, the app gives an error because it is trying to find a page with the access token in the URL hash, like http://example.com/#access_token=something. How can I prevent the app from trying to render this route and instead redirect the user to the login component?

I'm using Spotify auth API to authenticate the users. Here is my AppRouter:

```<code><HashRouter basename={process.env.REACT_APP_BASE_NAME}>
            <Routes>
              <Route
                path="/"
                element={
                  <Guard>
                    <Login />
                  </Guard>
                }
              />
              <Route path="/login" element={<Login />} exact />
              <Route path="/profile" element={<ProfilePage />} exact />
              <Route path="/artists" element={<ArtistsPage />} exact />
              <Route path="/artist/:id" element={<ArtistDetailsPage />} exact />
              <Route path="/tracks" element={<TracksPage />} exact />
              <Route
                path="/recent-tracks"
                element={<RecentTracksPage />}
                exact
              />
              <Route path="/spotify-stats" exact component={Login} />

              <Route path="*" element={<PageNotFound />} />
            </Routes>
</HashRouter>
</code>```

Body:
I have a React app that was using BrowserRouter and was working fine, but I switched to HashRouter because I want to host the app on GitHub Pages. Now, when I try to navigate to a route using a button or a link, the app gives an error because it is trying to find a page with the access token in the URL hash, like http://example.com/#access_token=something. How can I prevent the app from trying to render this route and instead redirect the user to the login component?

I'm using Spotify auth API to authenticate the users. Here is my AppRouter:

<HashRouter basename={process.env.REACT_APP_BASE_NAME}>
            <Routes>
              <Route
                path="/"
                element={
                  <Guard>
                    <Login />
                  </Guard>
                }
              />
              <Route path="/login" element={<Login />} exact />
              <Route path="/profile" element={<ProfilePage />} exact />
              <Route path="/artists" element={<ArtistsPage />} exact />
              <Route path="/artist/:id" element={<ArtistDetailsPage />} exact />
              <Route path="/tracks" element={<TracksPage />} exact />
              <Route
                path="/recent-tracks"
                element={<RecentTracksPage />}
                exact
              />
              <Route path="/spotify-stats" exact component={Login} />

              <Route path="*" element={<PageNotFound />} />
            </Routes>
</HashRouter>


问:
VS Code Files in Staging area
I am not too sure what I have done, I am starting a new project, I have been using VS Code and Git for a while now on my laptop and I have not yet come across such a problem, my intial commit is full of files I have never seen or used, how do I remove these as the commands I know to reset the staging area etc are not removing these, these look like very important files,

Can you help me?

Title: VS Code Files in Staging area


问:
how can i move widget and when it arrive to max border it pop up again from other side
i have the following image

i need to auto move the text and when it arrive to end it pop up  again from left side

you can understand this like marquee plugin . https://pub.dev/packages/marquee

how could i implement this


问:
How to run unit tests that are outside Angular project
How to run unit tests that are outside Angular project?

Project structure:

projects/app1

projects/app2

projects/app3

shared (here we have shared code between apps - this is NOT a project defined in angular.json)

I want to run the the tests from the shared folder as part of one of our projects or even independently. I want to avoid creating a separate project in angular.json for the shared code (because it does not make sense)

I have this problem only after the upgrade to version 15:

Since Angular v15 the require.context function from test.ts configuration file was removed.

I was using require.context to make tests outside Angular project visible to Karma. Now this was removed:

```<code>const contextGlobal = require.context('../../../folderOutsideProject/', true, /\.spec\.ts$/);
contextGlobal.keys().map(contextGlobal);
</code>```

I tried creating a symlink between outsideFolder and project folder. It's not working.

Body:
How to run unit tests that are outside Angular project?

Project structure:

projects/app1

projects/app2

projects/app3

shared (here we have shared code between apps - this is NOT a project defined in angular.json)

I want to run the the tests from the shared folder as part of one of our projects or even independently. I want to avoid creating a separate project in angular.json for the shared code (because it does not make sense)

I have this problem only after the upgrade to version 15:

Since Angular v15 the require.context function from test.ts configuration file was removed.

I was using require.context to make tests outside Angular project visible to Karma. Now this was removed:

const contextGlobal = require.context('../../../folderOutsideProject/', true, /\.spec\.ts$/);
contextGlobal.keys().map(contextGlobal);

I tried creating a symlink between outsideFolder and project folder. It's not working.