问:
.jar file is not running in Linux Mint
Trying to run Pamguard 2.01.05 on Linux Mint 21.

After running .jar file I got a message:

```<code>Note - ignore the following SLF4J warn/error messages, they are not applicable to this application
java.lang.ClassNotFoundException: com.sun.glass.ui.gtk.GtkPlatformFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:383)
    at java.base/java.lang.Class.forName(Class.java:376)
    at com.sun.glass.ui.PlatformFactory.getPlatformFactory(PlatformFactory.java:42)
    at com.sun.glass.ui.Application.run(Application.java:144)
    at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:280)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:269)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:158)
    at javafx.embed.swing.JFXPanel.lambda$initFx$1(JFXPanel.java:224)
    at java.base/java.lang.Thread.run(Thread.java:833)
Failed to load Glass factory class

PamExceptionHandler: Caught Exception on thread AWT-EventQueue-0
***** Heap utilization statistics [MB] *****
Total Memory Java has allocated: 67
Free Memory: 46
Used Memory: 20
Max Memory Java can allocate: 1850
java.lang.NullPointerException: Cannot invoke "com.sun.glass.ui.PlatformFactory.createApplication()" because the return value of "com.sun.glass.ui.PlatformFactory.getPlatformFactory()" is null
    at com.sun.glass.ui.Application.run(Application.java:144)
    at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:280)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:269)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:158)
    at javafx.embed.swing.JFXPanel.lambda$initFx$1(JFXPanel.java:224)
    at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

I tried to use jdk11, jdk16 and jdk18

I have libgtk-3-dev and openjfx

But it didn't help

Also, the manufacturer does not support versions for Linux.

With different versions of Pamguard and different versions of java error message the same.

How can I solve this problem? Thanks for any help.

Title: .jar file is not running in Linux Mint

Body:
Trying to run Pamguard 2.01.05 on Linux Mint 21.

After running .jar file I got a message:

Note - ignore the following SLF4J warn/error messages, they are not applicable to this application
java.lang.ClassNotFoundException: com.sun.glass.ui.gtk.GtkPlatformFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:383)
    at java.base/java.lang.Class.forName(Class.java:376)
    at com.sun.glass.ui.PlatformFactory.getPlatformFactory(PlatformFactory.java:42)
    at com.sun.glass.ui.Application.run(Application.java:144)
    at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:280)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:269)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:158)
    at javafx.embed.swing.JFXPanel.lambda$initFx$1(JFXPanel.java:224)
    at java.base/java.lang.Thread.run(Thread.java:833)
Failed to load Glass factory class

PamExceptionHandler: Caught Exception on thread AWT-EventQueue-0
***** Heap utilization statistics [MB] *****
Total Memory Java has allocated: 67
Free Memory: 46
Used Memory: 20
Max Memory Java can allocate: 1850
java.lang.NullPointerException: Cannot invoke "com.sun.glass.ui.PlatformFactory.createApplication()" because the return value of "com.sun.glass.ui.PlatformFactory.getPlatformFactory()" is null
    at com.sun.glass.ui.Application.run(Application.java:144)
    at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:280)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:269)
    at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:158)
    at javafx.embed.swing.JFXPanel.lambda$initFx$1(JFXPanel.java:224)
    at java.base/java.lang.Thread.run(Thread.java:833)

I tried to use jdk11, jdk16 and jdk18

I have libgtk-3-dev and openjfx

But it didn't help

Also, the manufacturer does not support versions for Linux.

With different versions of Pamguard and different versions of java error message the same.

How can I solve this problem? Thanks for any help.


来源: stackexchange

问:
javascript bookmarklet - window.location.href passes about:srcdoc instead of url - how to move inline

                                ×

Submit an IDQ Request

                                    <form id="papercutForm" method="get" action="https://internal_ticketsystem.com/create/options?" target="_blank">
                                        <input type="hidden" name="title" value="Colour Change"/>
                                        <input type="hidden" name="ticket_type" value="Regular+Ticket"/>
                                        <input type="hidden" name="severity" value="TWENTY"/>
                                        <input type="hidden" name="cat" value="Catalogue"/>
                                        <input type="hidden" name="subcat" value="Support"/>
                                        <input type="hidden" name="topic" value="Changes"/>
                                        <input type="hidden" name="description" value="Hello,
                                    I have the following issue:
                                    "/>

Which Issue do you see?

<textarea name="description" required="required" class="inputBox"></textarea>

Which country is affected?

                                            <select name="title" class="inputBox selectDropdown">
                                                <option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
                                                <option value="24">DM</option>
                                                <option value="15">TR</option>
                                                <option value="36">US</option>
                                                <option value="79">FR</option>
                                                </select>

Which company is affected?

                                            <select name="title" class="inputBox selectDropdown">
                                                <option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
                                                <option value="123">company A</option>
                                                <option value="456">company B</option>
                                                <option value="789">company C</option>

                                            </select>

                                            <input type="hidden" name="description" value="

                                            ***CHOOSE THE DEFECT:***
                                            "/>

Which area is impacted?

                                                <select name="description" class="inputBox selectDropdown">
                                                    <option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
                                                    <option value="blue">Image is blue but shouldnt</option>
                                                    <option value="red">Image is red but shouldnt</option>
                                                    <option value="green">Image is green but shouldnt</option>

                                            <input type="hidden" name="description" value="

                                            on following URL
                                            "/>

                                            <input id="ProductInput" type="hidden" name="description" value=""/>

                                            <input type="submit" value="Submit" class="btn btn-primary" />

                                        <button type="button" onclick="window.parent.closePapercut();" class="btn">Close</button>
                                    </form>

                            <script type="text/javascript">
                                    $("#papercutForm").submit(function(event){
                                        console.log("Preventing default form submission")
                                        event.preventDefault();

                                        $("#ProductInput")[0].setAttribute("value", window.location.href.substr(0,250));

                                        /////// Handle inputs which have duplicate "name" attributes ///////

                                        // Handle multiple "title" query params
                                        var titleInputs = $("#papercutForm [name=title]")
                                        var titleInputsValues = $.map(titleInputs, function(elem) {
                                            return elem.classList.contains("selectDropdown") ?
                                                ( elem.options[elem.selectedIndex].text + "(" + elem.options[elem.selectedIndex].value + ")" )
                                                : elem.value;
                                        });
                                        var formTitleValuesCombined = titleInputsValues.join(",");

                                        console.log(formTitleValuesCombined);

                                        // Handle multiple "description" query params
                                        var descriptionInputs = $("#papercutForm [name=description]")
                                        var descriptionInputsValues = $.map(descriptionInputs, function(elem) {
                                            return elem.classList.contains("selectDropdown") ? elem.options[elem.selectedIndex].text : elem.value;
                                        });
                                        // Join the different descriptions with no space "" since the form-provided descriptions (non-user provided descriptions)
                                        // have newline character "\\n" at the beginning and end.
                                        // You could also delimit by newline character "\\n" just to be sure the descriptions show up on different lines.
                                        var formDescriptionValuesCombined = descriptionInputsValues.join("").replace(/\t/g, ""); // Replace tab characters

                                        console.log(formDescriptionValuesCombined);

                                        ////////////////////////////////////////////////////////////////////

                                        // Inputs which have unique "name" attribute

                                        var allOtherInputs = $("#papercutForm [name]").not("[name=description]").not("[name=title]");

                                        ////////////////////////////////////////////////////////////////////
                                        // Build the target URL such that "title" and "description" both only appear once,
                                        // so that each is interpretted as a single entiy rather than an array of inputs

                                        var url = new URL("https://internal_ticketsystem.com/create/options?");
                                        url.searchParams.append("title", formTitleValuesCombined);
                                        url.searchParams.append("description", formDescriptionValuesCombined);
                                        allOtherInputs.toArray().forEach( (elem) => {
                                            url.searchParams.append(elem.name, elem.value);
                                        });

                                        console.log("Redirecting to :", url.href);
                                        window.open(url.href, "_blank"); // Open the ticket form in new window
                                    });

                                document.querySelector("#papercutForm").addEventListener("submit", function(e){
                                    setTimeout(function() {
                                        window.parent.submittedPapercut();
                                    }, 1);
                                });
                            </script>

                        '>

            `).hide().appendTo('body').fadeIn(300);

            window.closePapercut = function() {
                $('#papercutModal').fadeOut(300, function() { $(this).remove(); });
            }

            window.submittedPapercut = function() {
                    $('#papercutFrame').contents().find('#papercutBox').html('
Thanks for sending 🙂
');
                $('#papercutCard').height(300);
            }

            $('#papercutModal').click(function() {
                window.closePapercut();
            });
      }
    );})()
```
<p>I already found some useful results on stackoverflow, but I really struggle with the implementation :(</p>
<p>E.g. I found On my webpage, using "window.location.href" returns "about:srcdoc" instead of the URL name - but if I enter i.e.</p>
```  let iframe = document.querySelector('iframe')
  $("#ProductInput")[0].setAttribute("value",iframe.contentDocument.baseURI);
```
<p>instead of</p>
```  $("#ProductInput")[0].setAttribute("value", window.location.href.substr(0,250));
```

my code breaks :(

Can anyone help me understanding how I need to tweak the script to get the URL instead of 'about:srcdoc'?

Thank you!

ContentLicense: CC BY-SA 4.0

Title: javascript bookmarklet - window.location.href passes about:srcdoc instead of url - how to move inline <script> outside the Iframe

Body:
I having issue with the code below. What I try to achieve is a javascript bookmarklet (I use the code below in https://katanya.co.uk/labs/bookmarklet-generator), which opens a popup, asked the user for some input (Where is the problem, what is the problem) and passes the input into a URL, together with some static values - which looks like this:

https://internal_ticketsystem.com/create/options?title=Colour+Change%2CTR%2815%29%2Ccompany+A%28123%29&description=Hello%2C%0AI+have+the+following+issue%3A%0Atest%0A%0ACHOOSE+THE+DEFECT%3A%0AImage+is+red+but+shouldnt%0A%0Aon+following+URL+%0Aabout%3Asrcdoc&ticket_type=Regular%2BTicket&severity=TWENTY&cat=Catalogue&subcat=Support&topic=Changes

The problem that I currently have is, getting the current user location (I use window.location.href) into the result. I only get 'about:srcdoc' instead of the URL.

javascript:(function(){

   (function( window, document, req_version, callback, $, script, done, readystate ){

      if ( !($ = window.jQuery) || req_version > $.fn.jquery || callback( $ ) ) {

        script = document.createElement( 'script' );
        script.type = 'text/javascript';

        script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/' + req_version + '/jquery.min.js';

        script.onload = script.onreadystatechange = function() {
          if ( !done && ( !( readystate = this.readyState )
            || readystate == 'loaded' || readystate == 'complete' ) ) {

            callback( ($ = window.jQuery).noConflict(1), done = 1 );

            $( script ).remove();
          }
        };

        document.documentElement.childNodes[0].appendChild( script );
      }

    })( window, document, '1.3.2',

      function( $, L ) {
        '$:nomunge, L:nomunge';
            $('#papercutModal').remove();
            $(`

                        <iframe id="papercutFrame" style='border:none;' width='100%' height='100%' srcdoc='

                            <meta charset="UTF-8">

                                ×

Submit an IDQ Request

                                    <form id="papercutForm" method="get" action="https://internal_ticketsystem.com/create/options?" target="_blank">
                                        <input type="hidden" name="title" value="Colour Change"/>
                                        <input type="hidden" name="ticket_type" value="Regular+Ticket"/>
                                        <input type="hidden" name="severity" value="TWENTY"/>
                                        <input type="hidden" name="cat" value="Catalogue"/>
                                        <input type="hidden" name="subcat" value="Support"/>
                                        <input type="hidden" name="topic" value="Changes"/>
                                        <input type="hidden" name="description" value="Hello,
                                    I have the following issue:
                                    "/>

Which Issue do you see?

<textarea name="description" required="required" class="inputBox"></textarea>

Which country is affected?

                                            <select name="title" class="inputBox selectDropdown">
                                                <option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
                                                <option value="24">DM</option>
                                                <option value="15">TR</option>
                                                <option value="36">US</option>
                                                <option value="79">FR</option>
                                                </select>

Which company is affected?

                                            <select name="title" class="inputBox selectDropdown">
                                                <option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
                                                <option value="123">company A</option>
                                                <option value="456">company B</option>
                                                <option value="789">company C</option>

                                            </select>

                                            <input type="hidden" name="description" value="

                                            ***CHOOSE THE DEFECT:***
                                            "/>

Which area is impacted?

                                                <select name="description" class="inputBox selectDropdown">
                                                    <option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
                                                    <option value="blue">Image is blue but shouldnt</option>
                                                    <option value="red">Image is red but shouldnt</option>
                                                    <option value="green">Image is green but shouldnt</option>

                                            <input type="hidden" name="description" value="

                                            on following URL
                                            "/>

                                            <input id="ProductInput" type="hidden" name="description" value=""/>

                                            <input type="submit" value="Submit" class="btn btn-primary" />

                                        <button type="button" onclick="window.parent.closePapercut();" class="btn">Close</button>
                                    </form>

                        '>

            `).hide().appendTo('body').fadeIn(300);

            window.closePapercut = function() {
                $('#papercutModal').fadeOut(300, function() { $(this).remove(); });
            }

            window.submittedPapercut = function() {
                    $('#papercutFrame').contents().find('#papercutBox').html('
Thanks for sending 🙂
');
                $('#papercutCard').height(300);
            }

            $('#papercutModal').click(function() {
                window.closePapercut();
            });
      }
    );})()

I already found some useful results on stackoverflow, but I really struggle with the implementation :(

E.g. I found On my webpage, using "window.location.href" returns "about:srcdoc" instead of the URL name - but if I enter i.e.

  let iframe = document.querySelector('iframe')
  $("#ProductInput")[0].setAttribute("value",iframe.contentDocument.baseURI);

instead of

  $("#ProductInput")[0].setAttribute("value", window.location.href.substr(0,250));

my code breaks :(

Can anyone help me understanding how I need to tweak the script to get the URL instead of 'about:srcdoc'?

Thank you!


问:
Is there any way to resolve Error: b'{"error_code":"DIRECTORY_PROTECTED","message":"Folder Users is protected"}' in azure databricks
I am using CI/CD for Azure data bricks to import note books to Workspace. Previously I used master/main branch to deploy in the Dev environment. But recently created a branch named "DEV" and using this for deploying to the dev environment. I am getting below error.

Additional information:

"DEV" branch have branch policies

I am using "Deploy Databricks Notebooks" tasks to import notebooks


问:
How to deal with big dataset when using pyG?
I am a beginer learning to using torch_geometric to build my GNN models. I refered the sample of the pyG example of node classification and build my own dataset, however, I tried to use my GPU to run the code and it tells me that it run out of memory, maybe my dataset is too large to allocate the GPU memory? I don't know. I shared an machine of 8 A100 with my classmates. Could you please give me some suggestions, thank you!

from torch_geometric.nn import GATConv,GCNConv
from torch_geometric.data import Dataset,DataLoader,HeteroData,Data
import torch.nn as nn
from torch_geometric.nn import DataParallel
from torch_geometric.loader import DataListLoader
import torch.nn.functional as F
import torch
import pandas as pd
from transformers import BertTokenizer,BertModel
import pickle
import time
from tqdm import tqdm
from numba import jit
import json
from torch.optim import lr_scheduler
import matplotlib.pyplot as plt
import os

os.environ["CUDA_VISIBLE_DEVICES"] = "4,5,6,7"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

plt.grid(True)
plt.grid(color='gray',
         linestyle='--',
         linewidth=1,
         alpha=0.3)
begin = time.time()
punctuation = "!#$%&'\(\)－*+,-./:;<=>?@\\\[\]^_`{|}~（）：；，。【】·、“”‘’《》\"%……——·"
def dataCleanifier(s):
    for i in punctuation:
        s.replace(i," ")
    s = s.replace("  "," ")
    s = s.replace("\n","")
    return s

class BertClassifier(nn.Module):
    def __init__(self,bertType:str,max_length,tag_size):
        super(BertClassifier,self).__init__()
        self.bertType = bertType
        self.tokenizer = BertTokenizer.from_pretrained(self.bertType)
        self.encoder = BertModel.from_pretrained(self.bertType)
        self.outputDim = self.encoder.pooler.dense.out_features
        self.max_length = max_length
        self.tag_size = tag_size
        self.dropout = nn.Dropout(0.1)
        self.activation = nn.LeakyReLU(0.1)
        self.convs = nn.ModuleList(
            [nn.Conv2d(1, 512, (k, self.outputDim)) for k in (2,3,4)])
        self.fc_cnn = nn.Linear(512 * len((2,3,4)), self.tag_size)
    def conv_and_pool(self, x, conv):
        x = F.relu(conv(x)).squeeze(3)
        x = F.max_pool1d(x, x.size(2)).squeeze(2)
        return x
    def forward(self,x):

        x = self.tokenizer.batch_encode_plus(x,return_tensors="pt",max_length=self.max_length,truncation=True,padding="max_length")
        attention = x["attention_mask"]
        x = x["input_ids"]

        x = x.cuda(2)
        x = self.encoder(x,attention_mask=attention.cuda(2))['last_hidden_state'][:]
        x = x.unsqueeze(1)
        encoded = torch.cat([self.conv_and_pool(x,conv) for conv in self.convs],1)

        x = self.fc_cnn(encoded)
        x = self.activation(x)

        # x = F.softmax(x,dim=1)
        return x,encoded

class ContrastiveLoss(nn.Module):
    def __init__(self):
        super(ContrastiveLoss, self).__init__()
    def forward(self,representations,label,y_hat):
        n = label.shape[0]
        T = 0.5
        similarity_matrix = F.cosine_similarity(representations.unsqueeze(1), representations.unsqueeze(0), dim=2)
        mask = torch.ones_like(similarity_matrix) * (label.expand(n, n).eq(label.expand(n, n).t()))
        mask_no_sim = torch.ones_like(mask) - mask
        mask_dui_jiao_0 = torch.ones(n ,n) - torch.eye(n, n )
        similarity_matrix = torch.exp(similarity_matrix/T)
        similarity_matrix = similarity_matrix*mask_dui_jiao_0

        sim = mask*similarity_matrix

        no_sim = similarity_matrix - sim

        no_sim_sum = torch.sum(no_sim , dim=1)

        no_sim_sum_expend = no_sim_sum.repeat(n, 1).T
        sim_sum  = sim + no_sim_sum_expend
        loss = torch.div(sim , sim_sum)

        loss = mask_no_sim + loss + torch.eye(n, n )
        #接下来就是算一个批次中的loss了
        loss = -torch.log(loss)  #求-log
        loss = torch.sum(torch.sum(loss, dim=1) )/(2*n)+nn.CrossEntropyLoss()(y_hat,label)
        return loss

class GAT(nn.Module):
    def __init__(self, hidden_channels) -> None:
        super().__init__()
        self.conv1 = GATConv(data.num_features,hidden_channels)
        self.conv2 = GATConv(hidden_channels,9)
        self.activation = nn.ReLU()
    def forward(self,x,edge_index):

        x = self.conv1(x,edge_index)
        x = self.activation(x)
        # print(x)
        # x = F.dropout(x,p=0.2)
        x = self.conv2(x,edge_index)
        return x

x=None
y=None
edge_index = None
train_mask = None
with open("X.pkl","rb") as f1:
    x = pickle.load(f1)

with open("Y.pkl","rb") as f2:
    y = pickle.load(f2)
    y = y.long()

with open("edge_index.pkl","rb") as f3:
    edge_index = pickle.load(f3)

    # print(edge_index.shape)

with open("train_mask.pkl","rb") as f4:
    train_mask = pickle.load(f4)

data = Data(x=x,y=y,edge_index=edge_index)

data.train_mask = train_mask

model = GAT(hidden_channels=32)
model.cuda()

optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
scheduler = lr_scheduler.StepLR(optimizer, 100, 0.8)

criterion = ContrastiveLoss()
def train():
    model.train()
    optimizer.zero_grad()  # Clear gradients.
    out = model(data.x,data.edge_index)  # Perform a single forward pass.

    loss = criterion(data.x[data.train_mask], data.y[data.train_mask],out[data.train_mask])  # Compute the loss solely based on the training nodes.
    loss.backward()  # Derive gradients.
    optimizer.step()  # Update parameters based on gradients.
    return loss

def test():
    model.eval()
    out = model(data.x, data.edge_index)
    pred = out.argmax(dim=1)  # Use the class with highest probability.
    test_correct = pred[data.train_mask] == data.y[data.train_mask]  # Check against ground-truth labels.
    test_acc = int(test_correct.sum()) / int(data.train_mask.sum())  # Derive ratio of correct predictions.
    return test_acc

accs = []
for epoch in range(1, 1025):
    loss = train()
    print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}',end=" ")
    acc = test()
    print("acc:",acc)
    accs.append(acc)
    scheduler.step()
plt.plot(range(len(accs)),accs)
print(time.time()-begin)
with open("./accs_gat_GCL.pkl","wb") as f1:
    pickle.dump(accs,f1)
plt.savefig("./res_GAT_GCL.png",dpi=600)

```

I have tried to use DataPararel to use multiple GPU to load my model and dataset but failed.

Body:
I am a beginer learning to using torch_geometric to build my GNN models. I refered the sample of the pyG example of node classification and build my own dataset, however, I tried to use my GPU to run the code and it tells me that it run out of memory, maybe my dataset is too large to allocate the GPU memory? I don't know. I shared an machine of 8 A100 with my classmates. Could you please give me some suggestions, thank you!

from torch_geometric.nn import GATConv,GCNConv
from torch_geometric.data import Dataset,DataLoader,HeteroData,Data
import torch.nn as nn
from torch_geometric.nn import DataParallel
from torch_geometric.loader import DataListLoader
import torch.nn.functional as F
import torch
import pandas as pd
from transformers import BertTokenizer,BertModel
import pickle
import time
from tqdm import tqdm
from numba import jit
import json
from torch.optim import lr_scheduler
import matplotlib.pyplot as plt
import os

os.environ["CUDA_VISIBLE_DEVICES"] = "4,5,6,7"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

plt.grid(True)
plt.grid(color='gray',
         linestyle='--',
         linewidth=1,
         alpha=0.3)
begin = time.time()
punctuation = "!#$%&'\(\)－*+,-./:;<=>?@\\\[\]^_`{|}~（）：；，。【】·、“”‘’《》\"%……——·"
def dataCleanifier(s):
    for i in punctuation:
        s.replace(i," ")
    s = s.replace("  "," ")
    s = s.replace("\n","")
    return s

class BertClassifier(nn.Module):
    def __init__(self,bertType:str,max_length,tag_size):
        super(BertClassifier,self).__init__()
        self.bertType = bertType
        self.tokenizer = BertTokenizer.from_pretrained(self.bertType)
        self.encoder = BertModel.from_pretrained(self.bertType)
        self.outputDim = self.encoder.pooler.dense.out_features
        self.max_length = max_length
        self.tag_size = tag_size
        self.dropout = nn.Dropout(0.1)
        self.activation = nn.LeakyReLU(0.1)
        self.convs = nn.ModuleList(
            [nn.Conv2d(1, 512, (k, self.outputDim)) for k in (2,3,4)])
        self.fc_cnn = nn.Linear(512 * len((2,3,4)), self.tag_size)
    def conv_and_pool(self, x, conv):
        x = F.relu(conv(x)).squeeze(3)
        x = F.max_pool1d(x, x.size(2)).squeeze(2)
        return x
    def forward(self,x):

        x = self.tokenizer.batch_encode_plus(x,return_tensors="pt",max_length=self.max_length,truncation=True,padding="max_length")
        attention = x["attention_mask"]
        x = x["input_ids"]

        x = x.cuda(2)
        x = self.encoder(x,attention_mask=attention.cuda(2))['last_hidden_state'][:]
        x = x.unsqueeze(1)
        encoded = torch.cat([self.conv_and_pool(x,conv) for conv in self.convs],1)

        x = self.fc_cnn(encoded)
        x = self.activation(x)

        # x = F.softmax(x,dim=1)
        return x,encoded

class ContrastiveLoss(nn.Module):
    def __init__(self):
        super(ContrastiveLoss, self).__init__()
    def forward(self,representations,label,y_hat):
        n = label.shape[0]
        T = 0.5
        similarity_matrix = F.cosine_similarity(representations.unsqueeze(1), representations.unsqueeze(0), dim=2)
        mask = torch.ones_like(similarity_matrix) * (label.expand(n, n).eq(label.expand(n, n).t()))
        mask_no_sim = torch.ones_like(mask) - mask
        mask_dui_jiao_0 = torch.ones(n ,n) - torch.eye(n, n )
        similarity_matrix = torch.exp(similarity_matrix/T)
        similarity_matrix = similarity_matrix*mask_dui_jiao_0

        sim = mask*similarity_matrix

        no_sim = similarity_matrix - sim

        no_sim_sum = torch.sum(no_sim , dim=1)

        no_sim_sum_expend = no_sim_sum.repeat(n, 1).T
        sim_sum  = sim + no_sim_sum_expend
        loss = torch.div(sim , sim_sum)

        loss = mask_no_sim + loss + torch.eye(n, n )
        #接下来就是算一个批次中的loss了
        loss = -torch.log(loss)  #求-log
        loss = torch.sum(torch.sum(loss, dim=1) )/(2*n)+nn.CrossEntropyLoss()(y_hat,label)
        return loss

class GAT(nn.Module):
    def __init__(self, hidden_channels) -> None:
        super().__init__()
        self.conv1 = GATConv(data.num_features,hidden_channels)
        self.conv2 = GATConv(hidden_channels,9)
        self.activation = nn.ReLU()
    def forward(self,x,edge_index):

        x = self.conv1(x,edge_index)
        x = self.activation(x)
        # print(x)
        # x = F.dropout(x,p=0.2)
        x = self.conv2(x,edge_index)
        return x

x=None
y=None
edge_index = None
train_mask = None
with open("X.pkl","rb") as f1:
    x = pickle.load(f1)

with open("Y.pkl","rb") as f2:
    y = pickle.load(f2)
    y = y.long()

with open("edge_index.pkl","rb") as f3:
    edge_index = pickle.load(f3)

    # print(edge_index.shape)

with open("train_mask.pkl","rb") as f4:
    train_mask = pickle.load(f4)

data = Data(x=x,y=y,edge_index=edge_index)

data.train_mask = train_mask

model = GAT(hidden_channels=32)
model.cuda()

optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
scheduler = lr_scheduler.StepLR(optimizer, 100, 0.8)

criterion = ContrastiveLoss()
def train():
    model.train()
    optimizer.zero_grad()  # Clear gradients.
    out = model(data.x,data.edge_index)  # Perform a single forward pass.

    loss = criterion(data.x[data.train_mask], data.y[data.train_mask],out[data.train_mask])  # Compute the loss solely based on the training nodes.
    loss.backward()  # Derive gradients.
    optimizer.step()  # Update parameters based on gradients.
    return loss

def test():
    model.eval()
    out = model(data.x, data.edge_index)
    pred = out.argmax(dim=1)  # Use the class with highest probability.
    test_correct = pred[data.train_mask] == data.y[data.train_mask]  # Check against ground-truth labels.
    test_acc = int(test_correct.sum()) / int(data.train_mask.sum())  # Derive ratio of correct predictions.
    return test_acc

accs = []
for epoch in range(1, 1025):
    loss = train()
    print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}',end=" ")
    acc = test()
    print("acc:",acc)
    accs.append(acc)
    scheduler.step()
plt.plot(range(len(accs)),accs)
print(time.time()-begin)
with open("./accs_gat_GCL.pkl","wb") as f1:
    pickle.dump(accs,f1)
plt.savefig("./res_GAT_GCL.png",dpi=600)

I have tried to use DataPararel to use multiple GPU to load my model and dataset but failed.


问:
What are options for Azure QnA Maker to access private data?
I'm creating a QnA Service using the Language Studio.  I'm trying to create my source by connecting to a private URL.  The wizard is failing with the message:

```<code>BadArgument
1:34 AM
Failed to extract QnAs from the source
 - ExtractionFailure: Unsupported / Invalid url(s). Failed to extract Q&A from the source
</code>```

I'm assuming this error is because I have to authenticate to my source.  I see the documentation states that the source has to be a public URL.  Is there an update to access private data?  If not, I am wondering if there are any workarounds such as a code solution or exporting the content from my web page to a PDF document and creating an internal SharePoint site to contain this file.  My preference would be the code solution.

Body:
I'm creating a QnA Service using the Language Studio.  I'm trying to create my source by connecting to a private URL.  The wizard is failing with the message:

BadArgument
1:34 AM
Failed to extract QnAs from the source
 - ExtractionFailure: Unsupported / Invalid url(s). Failed to extract Q&A from the source

I'm assuming this error is because I have to authenticate to my source.  I see the documentation states that the source has to be a public URL.  Is there an update to access private data?  If not, I am wondering if there are any workarounds such as a code solution or exporting the content from my web page to a PDF document and creating an internal SharePoint site to contain this file.  My preference would be the code solution.


问:
How do I pass a method with my own constraints in a controller that uses request pattern to display data
Merry Christmass team!
I have a problem trying to figure out how to pass a method with my own constraints in a controller that is bound to request patter paradigm:

Sample Controller Code:

```<code>class SampleController
{
    protected $model = SampleModel::class;
    protected $indexRequest = IndexRequest::class;

}
</code>```

Request Class

```<code>class IndexRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */

    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [];
    }
</code>```

Assume I have a method that I want to do something different.Say I want to fetch some data based on some column constraints.
Whats the approach?

Body:
Merry Christmass team!
I have a problem trying to figure out how to pass a method with my own constraints in a controller that is bound to request patter paradigm:

Sample Controller Code:

class SampleController
{
    protected $model = SampleModel::class;
    protected $indexRequest = IndexRequest::class;

}

Request Class

class IndexRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */

    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [];
    }

Assume I have a method that I want to do something different.Say I want to fetch some data based on some column constraints.
Whats the approach?


问:
Directions from shortest path in array using BFS
I have an array consisting of 0s, 1s, 2 and 4. I start where there is 2 and my desired end is at 4. 1s are a obstacles and 0s are allowed moves. My program should output which direction of moves is the shortest path in my program it is JZS(South, West, North). Like first I moved South than west and to get to 4 I moved north.

I am trying to use BFS but have trouble getting it done. My biggest problem is how I should move in the array and also my program shows a few errors.Especially angry about line 63 "isKnown[str(actual.position)] = 1". This is the array I am writing about. Thank you for helping me in advance.

```<code>0 0 0 0 1 0
1 0 2 0 0 0
4 1 0 0 0 0
0 0 0 0 1 0
</code>```

In my program test.txt is the array.

```<code>import sys

#filename = sys.argv[1]
filename = "test.txt"

def loadBoard(filename):
    global b
    b = []
    f = open(filename, "r")
    for line in f:
        b.append(line.strip().split())
    f.close()
    return b
print (b)
def start():
    for i in range(len(b)):
        for j in range(len(b[i])):
            if [i][j] == "2":
                start = [i, j]
    return start

def finish():
    for i in range(len(b)):
        for j in range(len(b[i])):
            if [i][j] == "4":
                finish = [i, j]
    return finish

class State:
    def __init__(self, position, action = "", previous = None):
        self.position = position
        self.action = action
        self.previous = previous

    def expand(self):
        global new_dir
        action = ["S", "V", "J", "Z"]
        moves = [[[-1, 0], [0, 1], [1, 0], [0, -1]]]
        res = []

        for dir in range(4):
            new_dir = self.position

        while True:
            new_dir = [new_dir[0] + moves[dir][0], [new_dir[1] + moves[dir][1]]]

            if 0 <= new_dir[0] < len(b) and 0 <= new_dir[1] <= len(b[0]) and b[new_dir[0][new_dir[1]]] != 1:
                continue
            else:
                new_dir = [new_dir[0] - moves[dir][0], [new_dir[1] - moves[dir][1]]]
                break
        res.append(expand(new_dir, self, action[dir]))
        return res

if __name__ == "__main__":
    position = start()
    end = finish
    openList = [start]
    isKnown = {}
    while len(openList) > 0:
        actual = openList.pop(0)# BFS
        isKnown[str(actual.position)] = 1
        if actual.position == finish:
            tmp = actual
            res = " "
            while tmp != None:
                res = tmp.action + res
                tmp = tmp.previous
            print(res)
            break

        newNodes = actual.expand()
        for node in newNodes:#pole v objektu
            if not str(node.position) in isKnown:
                openList.append(node)

</code>```

Body:
I have an array consisting of 0s, 1s, 2 and 4. I start where there is 2 and my desired end is at 4. 1s are a obstacles and 0s are allowed moves. My program should output which direction of moves is the shortest path in my program it is JZS(South, West, North). Like first I moved South than west and to get to 4 I moved north.

I am trying to use BFS but have trouble getting it done. My biggest problem is how I should move in the array and also my program shows a few errors.Especially angry about line 63 "isKnown[str(actual.position)] = 1". This is the array I am writing about. Thank you for helping me in advance.

0 0 0 0 1 0
1 0 2 0 0 0
4 1 0 0 0 0
0 0 0 0 1 0

In my program test.txt is the array.

import sys

#filename = sys.argv[1]
filename = "test.txt"

def loadBoard(filename):
    global b
    b = []
    f = open(filename, "r")
    for line in f:
        b.append(line.strip().split())
    f.close()
    return b
print (b)
def start():
    for i in range(len(b)):
        for j in range(len(b[i])):
            if [i][j] == "2":
                start = [i, j]
    return start

def finish():
    for i in range(len(b)):
        for j in range(len(b[i])):
            if [i][j] == "4":
                finish = [i, j]
    return finish

class State:
    def __init__(self, position, action = "", previous = None):
        self.position = position
        self.action = action
        self.previous = previous

    def expand(self):
        global new_dir
        action = ["S", "V", "J", "Z"]
        moves = [[[-1, 0], [0, 1], [1, 0], [0, -1]]]
        res = []

        for dir in range(4):
            new_dir = self.position

        while True:
            new_dir = [new_dir[0] + moves[dir][0], [new_dir[1] + moves[dir][1]]]

            if 0 <= new_dir[0] < len(b) and 0 <= new_dir[1] <= len(b[0]) and b[new_dir[0][new_dir[1]]] != 1:
                continue
            else:
                new_dir = [new_dir[0] - moves[dir][0], [new_dir[1] - moves[dir][1]]]
                break
        res.append(expand(new_dir, self, action[dir]))
        return res

if __name__ == "__main__":
    position = start()
    end = finish
    openList = [start]
    isKnown = {}
    while len(openList) > 0:
        actual = openList.pop(0)# BFS
        isKnown[str(actual.position)] = 1
        if actual.position == finish:
            tmp = actual
            res = " "
            while tmp != None:
                res = tmp.action + res
                tmp = tmp.previous
            print(res)
            break

        newNodes = actual.expand()
        for node in newNodes:#pole v objektu
            if not str(node.position) in isKnown:
                openList.append(node)


问:
Device calendar accounts is not display in flutter
Calendars from my device and local accounts are not displayed on my screen The calendar is correctly presented when I execute my code using USB, however when I generate an apk and then install it on my device, the calendar is not visible.i am using device calendar plugin i get this code from there account Can anyone assist in identifying the problem?</p>
```<code>class CalendarsPage extends StatefulWidget {
  const CalendarsPage(
      {Key? key,
      required String calendarName,
      required void Function() opendrawer,
      required double animationtime})
      : super(key: key);

  @override
  _CalendarsPageState createState() {
    return _DoctorCalendarsPageState();
  }
}

class _CalendarsPageState extends State<CalendarsPage> {
  late CalendarPlugin _CalendarPlugin;
  List<Calendar> _calendar = [];
  List<Calendar> get _writableCalendars =>
      _calendar.where((c) => c.isReadOnly == false).toList();

  List<Calendar> get _readOnlyCalendars =>
      _calendar.where((c) => c.isReadOnly == true).toList();

  _CalendarsPageState() {
    _deviceCalendarPlugin = DeviceCalendarPlugin();
  }

  @override
  void initState() {
    super.initState();
    _retrieveCalendars();
    _CalendarsPageState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            flex: 1,
            child: ListView.builder(
              itemCount: _calendar.length,
              itemBuilder: (BuildContext context, int index) {
                return GestureDetector(
                  key: Key(_calendar[index].isReadOnly == true
                      ? 'readOnlyCalendar${_readOnlyCalendars.indexWhere((c) => c.id == _calendar[index].id)}'
                      : 'writableCalendar${_writableCalendars.indexWhere((c) => c.id == _calendar[index].id)}'),
                  onTap: () async {
                    await Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return DoctorEventsPage(_calendar[index],
                          key: const Key('calendarEventsPage'));
                    }));
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Container(
                      height: 22,
                      child: Row(
                        children: [
                          Expanded(
                            flex: 1,
                            child: Text(
                              _calendar[index].name!,
                              style: Theme.of(context).textTheme.subtitle1,
                            ),
                          ),
                          Container(
                            width: 15,
                            height: 15,
                            decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: Color(_calendar[index].color!)),
                          ),
                          const SizedBox(width: 10),
                          // Container(
                          //   margin: const EdgeInsets.fromLTRB(0, 0, 5.0, 0),
                          //   padding: const EdgeInsets.all(3.0),
                          //   decoration: BoxDecoration(
                          //       border: Border.all(color: Colors.blueAccent)),
                          //   // child: const Text('Default'),
                          // ),
                          Icon(_calendar[index].isReadOnly == true
                              ? Icons.lock
                              : Icons.lock_open)
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final createCalendar = await Navigator.push(context,
              MaterialPageRoute(builder: (BuildContext context) {
            return DoctorCalendarAddPage();
          }));

          if (createCalendar == true) {
            _retrieveCalendars();
          }
        },
        child: const Icon(Icons.add),
        backgroundColor: Colors.green,
      ),
    );
  }

  void _retrieveCalendars() async {
    try {
      var permissionsGranted = await _deviceCalendarPlugin.hasPermissions();
      if (permissionsGranted.isSuccess &&
          (permissionsGranted.data == null ||
              permissionsGranted.data == false)) {
        permissionsGranted = await _deviceCalendarPlugin.requestPermissions();
        if (!permissionsGranted.isSuccess ||
            permissionsGranted.data == null ||
            permissionsGranted.data == false) {
          return;
        }
      }

      final calendarsResult = await _deviceCalendarPlugin.retrieveCalendars();
      setState(() {
        _calendar = calendarsResult.data as List<Calendar>;
      });
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }
}

</code>```

Body:
Calendars from my device and local accounts are not displayed on my screen The calendar is correctly presented when I execute my code using USB, however when I generate an apk and then install it on my device, the calendar is not visible.i am using device calendar plugin i get this code from there account Can anyone assist in identifying the problem?

class CalendarsPage extends StatefulWidget {
  const CalendarsPage(
      {Key? key,
      required String calendarName,
      required void Function() opendrawer,
      required double animationtime})
      : super(key: key);

  @override
  _CalendarsPageState createState() {
    return _DoctorCalendarsPageState();
  }
}

class _CalendarsPageState extends State<CalendarsPage> {
  late CalendarPlugin _CalendarPlugin;
  List<Calendar> _calendar = [];
  List<Calendar> get _writableCalendars =>
      _calendar.where((c) => c.isReadOnly == false).toList();

  List<Calendar> get _readOnlyCalendars =>
      _calendar.where((c) => c.isReadOnly == true).toList();

  _CalendarsPageState() {
    _deviceCalendarPlugin = DeviceCalendarPlugin();
  }

  @override
  void initState() {
    super.initState();
    _retrieveCalendars();
    _CalendarsPageState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            flex: 1,
            child: ListView.builder(
              itemCount: _calendar.length,
              itemBuilder: (BuildContext context, int index) {
                return GestureDetector(
                  key: Key(_calendar[index].isReadOnly == true
                      ? 'readOnlyCalendar${_readOnlyCalendars.indexWhere((c) => c.id == _calendar[index].id)}'
                      : 'writableCalendar${_writableCalendars.indexWhere((c) => c.id == _calendar[index].id)}'),
                  onTap: () async {
                    await Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return DoctorEventsPage(_calendar[index],
                          key: const Key('calendarEventsPage'));
                    }));
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Container(
                      height: 22,
                      child: Row(
                        children: [
                          Expanded(
                            flex: 1,
                            child: Text(
                              _calendar[index].name!,
                              style: Theme.of(context).textTheme.subtitle1,
                            ),
                          ),
                          Container(
                            width: 15,
                            height: 15,
                            decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: Color(_calendar[index].color!)),
                          ),
                          const SizedBox(width: 10),
                          // Container(
                          //   margin: const EdgeInsets.fromLTRB(0, 0, 5.0, 0),
                          //   padding: const EdgeInsets.all(3.0),
                          //   decoration: BoxDecoration(
                          //       border: Border.all(color: Colors.blueAccent)),
                          //   // child: const Text('Default'),
                          // ),
                          Icon(_calendar[index].isReadOnly == true
                              ? Icons.lock
                              : Icons.lock_open)
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final createCalendar = await Navigator.push(context,
              MaterialPageRoute(builder: (BuildContext context) {
            return DoctorCalendarAddPage();
          }));

          if (createCalendar == true) {
            _retrieveCalendars();
          }
        },
        child: const Icon(Icons.add),
        backgroundColor: Colors.green,
      ),
    );
  }

  void _retrieveCalendars() async {
    try {
      var permissionsGranted = await _deviceCalendarPlugin.hasPermissions();
      if (permissionsGranted.isSuccess &&
          (permissionsGranted.data == null ||
              permissionsGranted.data == false)) {
        permissionsGranted = await _deviceCalendarPlugin.requestPermissions();
        if (!permissionsGranted.isSuccess ||
            permissionsGranted.data == null ||
            permissionsGranted.data == false) {
          return;
        }
      }

      final calendarsResult = await _deviceCalendarPlugin.retrieveCalendars();
      setState(() {
        _calendar = calendarsResult.data as List<Calendar>;
      });
    } on PlatformException catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }
}


问:
Lack of documentation for List<DateTimeComponents> values in flutter
How to schedule yearly notifications in flutter using the "flutter_local_notifications" library

```<code>String repeatType = "Yearly";

await flutterLocalNotificationsPlugin.zonedSchedule(
    _id,
    "Title",
    "Body",
    _nextInstanceOfTenAM(time, true),
    NotificationDetails(
      android: AndroidNotificationDetails(_id, "Title", channelDescription: "Body"),
    ),
    androidAllowWhileIdle: true,
    uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
    matchDateTimeComponents: repeatType == "Daily"
    ? DateTimeComponents.time
    : repeatType == "Weekly"
        ? DateTimeComponents.dayOfWeekAndTime
        : repeatType == "Monthly"
            ? DateTimeComponents.dayOfMonthAndTime
            : *<CODE HERE>*,
);
</code>```

Examples of recurring notifications

```<code>DateTimeComponents.time (Daily)
DateTimeComponents.dayOfWeekAndTime (Weekly)
DateTimeComponents.dayOfMonthAndTime (Monthly)
</code>```

I'm trying to implement Yearly notifications using the constant values

```<code>DateTimeComponents.values.
</code>```

It accepts a List of DateTimeComponents. But there is no documentation about how the variable would look like

Does anybody know the solution to this?

Body:
How to schedule yearly notifications in flutter using the "flutter_local_notifications" library

String repeatType = "Yearly";

await flutterLocalNotificationsPlugin.zonedSchedule(
    _id,
    "Title",
    "Body",
    _nextInstanceOfTenAM(time, true),
    NotificationDetails(
      android: AndroidNotificationDetails(_id, "Title", channelDescription: "Body"),
    ),
    androidAllowWhileIdle: true,
    uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
    matchDateTimeComponents: repeatType == "Daily"
    ? DateTimeComponents.time
    : repeatType == "Weekly"
        ? DateTimeComponents.dayOfWeekAndTime
        : repeatType == "Monthly"
            ? DateTimeComponents.dayOfMonthAndTime
            : **,
);

Examples of recurring notifications

DateTimeComponents.time (Daily)
DateTimeComponents.dayOfWeekAndTime (Weekly)
DateTimeComponents.dayOfMonthAndTime (Monthly)

I'm trying to implement Yearly notifications using the constant values

DateTimeComponents.values.

It accepts a List of DateTimeComponents. But there is no documentation about how the variable would look like

Does anybody know the solution to this?


问:
In dokan plugin how to add a image/file custom field in vendor registration form
I am using Dokan Multivendor plugin for my wordpress e-commerce website. I want to add a custom upload image/file field in the vendor registration form so that the vendors can upload their Pan & Aadhar card photos on the website while registering for verification.</p>


问:
Could not find a Coverage file! Searched for lcov.info, cov.xml, coverage.xml, jacoco.xml, coverage.cobertura.xml
I have installed Coverage gutter https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters and .NET Core Test Explorer https://marketplace.visualstudio.com/items?itemName=formulahendry.dotnet-test-explorer

When I try to watch the test covered code, I got below alert message.
Could not find a Coverage file! Searched for lcov.info, cov.xml, coverage.xml, jacoco.xml, coverage.cobertura.xml

Do I need to create file named as lcov.info? If yes, where should I create (Path)?


问:
Firebase cloud functions - Can't create an array from the data after fetching from 3rd party API inside the function
I've been trying to implement firebase cloud functions on my project, currently cloud functions are working fine but whenever I try to fetch something from the third-party API the data is fetched but the data isn't being pushed to the array firestoreValues.
I don't think this is a problem related to firebase cloud function, rather some mistake on my end with javascript.

```<code>const functions = require("firebase-functions");
const fetch = require("node-fetch");
const admin = require("firebase-admin");
admin.initializeApp();
exports.executeTask = functions.firestore
  .document("tasks/{taskId}")
  .onCreate(async (doc, ctx) => {
    const { service, uid, request } = doc.data();

    //firestoreValues initialised wrong?

    var firestoreValues = [];

    if (service == "Email Validator") {
      const emails = request;
      emails.forEach((element) => {
        const options = {
          method: "GET",
          headers: {
            "X-RapidAPI-Key":
              "RAPID-API-KEY",
            "X-RapidAPI-Host": "RAPID-API-host",
          },
        };
        const fetchFromURL = async () =>
          await (
            await fetch(
              `https://domain/?domain=${element}`,
              options
            )
          ).json();

        fetchFromURL().then((data) => {
          console.log("data", data);
          console.log("firestoreValuesinside", firestoreValues);
          firestoreValues.push(data);
        });
      });
    }
    return admin
      .firestore()
      .collection("taskResults")
      .doc(doc.id)
      .set({ uid: uid, taskId: doc.id, result: firestoreValues });
  });
</code>```

the firestoreValues variable isnt changing and on the task results result an empty array is being written. How can I store the response data after every response to the firestoreValues

Ive tried to change the var to const and let for firestoreValues but the data isnt being pushed and the final result:firestoreValues on the .set() remains empty.

Body:
I've been trying to implement firebase cloud functions on my project, currently cloud functions are working fine but whenever I try to fetch something from the third-party API the data is fetched but the data isn't being pushed to the array firestoreValues.
I don't think this is a problem related to firebase cloud function, rather some mistake on my end with javascript.

const functions = require("firebase-functions");
const fetch = require("node-fetch");
const admin = require("firebase-admin");
admin.initializeApp();
exports.executeTask = functions.firestore
  .document("tasks/{taskId}")
  .onCreate(async (doc, ctx) => {
    const { service, uid, request } = doc.data();

    //firestoreValues initialised wrong?

    var firestoreValues = [];

    if (service == "Email Validator") {
      const emails = request;
      emails.forEach((element) => {
        const options = {
          method: "GET",
          headers: {
            "X-RapidAPI-Key":
              "RAPID-API-KEY",
            "X-RapidAPI-Host": "RAPID-API-host",
          },
        };
        const fetchFromURL = async () =>
          await (
            await fetch(
              `https://domain/?domain=${element}`,
              options
            )
          ).json();

        fetchFromURL().then((data) => {
          console.log("data", data);
          console.log("firestoreValuesinside", firestoreValues);
          firestoreValues.push(data);
        });
      });
    }
    return admin
      .firestore()
      .collection("taskResults")
      .doc(doc.id)
      .set({ uid: uid, taskId: doc.id, result: firestoreValues });
  });

the firestoreValues variable isnt changing and on the task results result an empty array is being written. How can I store the response data after every response to the firestoreValues

Ive tried to change the var to const and let for firestoreValues but the data isnt being pushed and the final result:firestoreValues on the .set() remains empty.


问:
How to go to Another dropdown when option is selected in select2
I created a function which goes to another select2 if not opened but I want to open the select2 dropdown and when user selects value with keypress enter goes to another select2 or any other inputs

$('#Form').on('keydown', 'select', function(event) {
  if (event.which == 13) {

    var $this = $(event.target);

    var select = ($this.attr('id'));
    var final = "#" + select;
    alert(final);
    $(`${final}`).select2('open');
    var index = parseFloat($this.attr('data-index'));
    $('[data-index="' + (index + 1).toString() + '"]').focus();
    event.preventDefault();

  }
});
```

If I remove $(`${final}`).select2('open'); it is focusing on another select2 on enter

Body:
I created a function which goes to another select2 if not opened but I want to open the select2 dropdown and when user selects value with keypress enter goes to another select2 or any other inputs

$('#Form').on('keydown', 'select', function(event) {
  if (event.which == 13) {

    var $this = $(event.target);

    var select = ($this.attr('id'));
    var final = "#" + select;
    alert(final);
    $(`${final}`).select2('open');
    var index = parseFloat($this.attr('data-index'));
    $('[data-index="' + (index + 1).toString() + '"]').focus();
    event.preventDefault();

  }
});

If I remove $(`${final}`).select2('open'); it is focusing on another select2 on enter


问:
How to properly make Google Ads client on AWS Lambda?
This code is being used on aws lambda for making Google ads client

```<code>try:
    googleads_client = GoogleAdsClient.load_from_dict(credentials, version="v11",)
except GoogleAdsException as e:
    print(f"Google Ads Exception: {e.message}")
</code>```

Unfortunately this is running into time out issue even if the time is set to 3 minutes. As there is no error, It is not possible to debug the issue.
Any experienced developer can share some tips?
Thanks alot

Body:
This code is being used on aws lambda for making Google ads client

try:
    googleads_client = GoogleAdsClient.load_from_dict(credentials, version="v11",)
except GoogleAdsException as e:
    print(f"Google Ads Exception: {e.message}")

Unfortunately this is running into time out issue even if the time is set to 3 minutes. As there is no error, It is not possible to debug the issue.
Any experienced developer can share some tips?
Thanks alot


问:
While taking a nn.Module (which consists of other nn.Modules) to cuda, aren't all the internal nn.Modules supposed to go to CUDA too?
I have this module VideoSegmentationNetwork which consists of 3 nn.Modules

CNNEncoder(nn.Module)

TransformerEncoder(nn.Module)

CNNDecoder(nn.Module)

```<code>class VideoSegmentationNetwork(nn.Module):
    def __init__(self):
        super(VideoSegmentationNetwork, self).__init__()
        self.cnnencoder = CNN_Encoder()
        self.transenc = TransformerEncoder(input_dim=EMBEDDED_DIMENSION, num_layers=2, num_heads=2)
        self.cnndecoder = CNN_Decoder()
</code>```

I have defined this network as:

```<code>   model = VideoSegmentationNetwork()
   model.to("cuda:0")
</code>```

While doing this, all three Classes are in CUDA when I check.

"SO WHERE IS THE PROBLEM? o.O" - You might ask.

Well, it comes inside TransformerEncoder(nn.Module) class, which is another class. It has a custom made MultiHeadAttention(nn.Module) class. The error exactly pops in, the MultiHeadAttention(nn.Module) class.

The MultiHeadAttention class is like this:

```<code>class MultiheadAttention(nn.Module):
    def __init__(self, input_dim, num_heads):
        super(MultiheadAttention, self).__init__()
        self.query_layer = nn.Linear(input_dim, input_dim)
        self.key_layer = nn.Linear(input_dim, input_dim)
        self.value_layer = nn.Linear(input_dim, input_dim)
        self.output_layer = nn.Linear(input_dim, input_dim)
</code>```

The error exactly pops in forward(self, x) method in the class. The error exactly says this:

So I was wondering, doesn't taking VideoSegmentationNetwork to cuda, take everything inside it to cuda too? Or I am missing something here, and you guys have some suggestions on what I should do?

Body:
I have this module VideoSegmentationNetwork which consists of 3 nn.Modules

CNNEncoder(nn.Module)

TransformerEncoder(nn.Module)

CNNDecoder(nn.Module)

class VideoSegmentationNetwork(nn.Module):
    def __init__(self):
        super(VideoSegmentationNetwork, self).__init__()
        self.cnnencoder = CNN_Encoder()
        self.transenc = TransformerEncoder(input_dim=EMBEDDED_DIMENSION, num_layers=2, num_heads=2)
        self.cnndecoder = CNN_Decoder()

I have defined this network as:

   model = VideoSegmentationNetwork()
   model.to("cuda:0")

While doing this, all three Classes are in CUDA when I check.

"SO WHERE IS THE PROBLEM? o.O" - You might ask.

Well, it comes inside TransformerEncoder(nn.Module) class, which is another class. It has a custom made MultiHeadAttention(nn.Module) class. The error exactly pops in, the MultiHeadAttention(nn.Module) class.

The MultiHeadAttention class is like this:

class MultiheadAttention(nn.Module):
    def __init__(self, input_dim, num_heads):
        super(MultiheadAttention, self).__init__()
        self.query_layer = nn.Linear(input_dim, input_dim)
        self.key_layer = nn.Linear(input_dim, input_dim)
        self.value_layer = nn.Linear(input_dim, input_dim)
        self.output_layer = nn.Linear(input_dim, input_dim)

The error exactly pops in forward(self, x) method in the class. The error exactly says this:

So I was wondering, doesn't taking VideoSegmentationNetwork to cuda, take everything inside it to cuda too? Or I am missing something here, and you guys have some suggestions on what I should do?


问:
Set Shutter Speed And Iso use camerax library when record video
I'm working on project that require feature change iso and shutter speed when recording video. I read camerax but nothing related. the only choose i have is use hardware.camera2 which too complexity. anyone know how to do this or even access camera device from camerax library</p>
```<code>previewBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, exposureTime);
previewBuilder.set(CaptureRequest.SENSOR_SENSITIVITY, sensitivity);
previewBuilder.set(CaptureRequest.SENSOR_FRAME_DURATION, frameDuration);
</code>```

Body:
I'm working on project that require feature change iso and shutter speed when recording video. I read camerax but nothing related. the only choose i have is use hardware.camera2 which too complexity. anyone know how to do this or even access camera device from camerax library

previewBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, exposureTime);
previewBuilder.set(CaptureRequest.SENSOR_SENSITIVITY, sensitivity);
previewBuilder.set(CaptureRequest.SENSOR_FRAME_DURATION, frameDuration);


问:
Defining a variable with a part inside a function
I need help with defining a variable,
I want to make a new variable named mainPendingTotal
I want it to be equal to the pendingTotal if (x.Username == config.mainAccount)
How do I do this? Below is code. It is not full code.

```<code>            .then(
                axios.spread((current, pending) => {
                    console.log(`${x.Username.cyan}\nCurrent: ${current.data.robux} R$\n${`Pending: ${pending.data.pendingRobuxTotal} R$`.gray}`);
                    if (x.Username == config.mainAccount) {
                        total.push(current.data.robux);
                        pendingTotal.push(pending.data.pendingRobuxTotal);
                    } else {
                        total.push(current.data.robux);
                        pendingTotal.push(pending.data.pendingRobuxTotal);
                    }
                })
            )
            .catch((message) => {
                console.log(`${x.Username}: Error ${message.response}`.red);
                total.push(0);
                pendingTotal.push(0);
            });
    }
    while (total.length !== file.length || pendingTotal.length !== file.length) {
        await new Promise((r) => setTimeout(r, 100));
    }
    let totalAdded = total.reduce((a, b) => a + b, 0);
    let pendingTotalAdded = pendingTotal.reduce((a, b) => a + b, 0);
    let allTotal = totalAdded + pendingTotalAdded;
    console.log(`${`\nTotal`.cyan}\nCurrent: ${totalAdded} R$\n${`Pending: ${pendingTotalAdded} R$`.gray}\n${`${allTotal} R$`.green}\n\nAfter Transfer: ${Math.round(allTotal * 0.7)} R$`);
</code>```

I tried playing around with the code, making the variable being equal to what I already had for the if (x.Username == config.mainAccount), I was expecting it to be able to define it, but it ended up giving me an error.

Body:
I need help with defining a variable,
I want to make a new variable named mainPendingTotal
I want it to be equal to the pendingTotal if (x.Username == config.mainAccount)
How do I do this? Below is code. It is not full code.

            .then(
                axios.spread((current, pending) => {
                    console.log(`${x.Username.cyan}\nCurrent: ${current.data.robux} R$\n${`Pending: ${pending.data.pendingRobuxTotal} R$`.gray}`);
                    if (x.Username == config.mainAccount) {
                        total.push(current.data.robux);
                        pendingTotal.push(pending.data.pendingRobuxTotal);
                    } else {
                        total.push(current.data.robux);
                        pendingTotal.push(pending.data.pendingRobuxTotal);
                    }
                })
            )
            .catch((message) => {
                console.log(`${x.Username}: Error ${message.response}`.red);
                total.push(0);
                pendingTotal.push(0);
            });
    }
    while (total.length !== file.length || pendingTotal.length !== file.length) {
        await new Promise((r) => setTimeout(r, 100));
    }
    let totalAdded = total.reduce((a, b) => a + b, 0);
    let pendingTotalAdded = pendingTotal.reduce((a, b) => a + b, 0);
    let allTotal = totalAdded + pendingTotalAdded;
    console.log(`${`\nTotal`.cyan}\nCurrent: ${totalAdded} R$\n${`Pending: ${pendingTotalAdded} R$`.gray}\n${`${allTotal} R$`.green}\n\nAfter Transfer: ${Math.round(allTotal * 0.7)} R$`);

I tried playing around with the code, making the variable being equal to what I already had for the if (x.Username == config.mainAccount), I was expecting it to be able to define it, but it ended up giving me an error.


问:
not found at http://cdn.sencha.com/cmd/7.6.0.87/
I am upgrading from Ubuntu 16.04 to 22.04.
The following command was entered to upgrade sencha 4.0.5 version used in Ubuntu 16.04 to the latest version of sencha 7.6.0

```<code>sencha upgrade
</code>```

An error occurred that supposedly failed to find the path to download

```<code>Sencha Cmd v4.0.5.87
[INF] Determining the latest version of Sencha Cmd
[INF] The latest version of Sencha Cmd is 7.6.0.87
[INF] Downloading SenchaCmd-7.6.0.87-linux-x64.run.zip from http://cdn.sencha.com/cmd/7.6.0.87/ to temp folder /tmp/sencha1672128222771
[INF] Cleaning up temporary files in /tmp/sencha1672128222771
[ERR] Cannot download SenchaCmd-7.6.0.87-linux-x64.run.zip - not found at http://cdn.sencha.com/cmd/7.6.0.87/
</code>```

I looked at the sencha document and entered the command instructed there.

The above error does not seem to have a proper solution even if it is googled.

I would appreciate any response I need your help

Body:
I am upgrading from Ubuntu 16.04 to 22.04.
The following command was entered to upgrade sencha 4.0.5 version used in Ubuntu 16.04 to the latest version of sencha 7.6.0

sencha upgrade

An error occurred that supposedly failed to find the path to download

Sencha Cmd v4.0.5.87
[INF] Determining the latest version of Sencha Cmd
[INF] The latest version of Sencha Cmd is 7.6.0.87
[INF] Downloading SenchaCmd-7.6.0.87-linux-x64.run.zip from http://cdn.sencha.com/cmd/7.6.0.87/ to temp folder /tmp/sencha1672128222771
[INF] Cleaning up temporary files in /tmp/sencha1672128222771
[ERR] Cannot download SenchaCmd-7.6.0.87-linux-x64.run.zip - not found at http://cdn.sencha.com/cmd/7.6.0.87/

I looked at the sencha document and entered the command instructed there.

The above error does not seem to have a proper solution even if it is googled.

I would appreciate any response I need your help


问:
How to add PDF files in wordpress?
I wan to add PDF files in wordpress website that help the user to read the book and user can also able to download the book easily.
I building website through elementor and now I have to upload and show pdf boos to the user.
If anyone know about this solution then share it.

Thanks!

Want to know the solution of uploading PDF files in Wordpress using elementor or any other method that help ther user to read it and download it.

Title: How to add PDF files in wordpress?


问:
Problem with export (download) into Excel-format with accented (central-european) charecters
I found and have read many answers here, but unfortunately none works for me. :(

So: I wanna export (and download) the array into Excel-format. Actually I try into CSV with .xls extension. But unfortunately only the following two cases occur:

OR the accented letters are well, but the columns are not separated (tab char is like a "normal" char)

OR the cell-separating is working, but the accented characters are wrong coded

I tried probably all the encodings, content-types, output-tpye (I mean bare echo, php://output, file-read etc.) with so many headers, but none of them works.


问:
DatePicker Widget with a button which runs all the below cells from jupyter lab for that selected date
I'm trying to create a DatePicker widget in Jupyter Lab with a button, when the user selects a date from the date picker and hits the button, all the below cells should start running for that date. I tried running below code and it is working as expected in the anaconda jupyter notebook but is not working in jupyter lab. Can you help me with the same?

```<code>from IPython.display import Javascript, display
import ipywidgets as widgets

fromDatePicker = widgets.DatePicker(description='fromdate')

ToDatePicker = widgets.DatePicker(description='fromdate')

def fromDate():
    return f"'{fromDatePicker.value}'"

def toDate():
    return f"'{ToDatePicker.value}'"

def run_all(ev):
    display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1, IPython.notebook.ncells())'))

button = widgets.Button(description="Run all")
button.on_click(run_all)
widgets.HBox([fromDatePicker, ToDatePicker, button])
</code>```

after this to check whether it is working or not I'm printing the start date below :

```<code>print("start date is :", fromDate())
</code>```

I expected that after clicking on the Run all button it should start executing the below cells but here I have to go to that cell and run it manually. Kindly please post your answers or suggestions below.

After using ipyab :

```<code>import ipywidgets as widgets
from ipylab import JupyterFrontEnd
from IPython.display  import Javascript, display
app = JupyterFrontEnd()

fromDatePicker = widgets.DatePicker(
    description='From Date'
)
ToDatePicker = widgets.DatePicker(
    description='To Date'
)

button = widgets.Button(
    description='Execute',
    disabled=False,
    button_style='success',
)

def fromDate():
    return f"'{fromDatePicker.value}'"

def toDate():
    return f"'{ToDatePicker.value}'"

def run_all(ev):
    app.commands.execute('notebook:run-all-below')

display(button)

button.on_click(run_all)
widgets.HBox([fromDatePicker, ToDatePicker, button])

</code>```

Above code is also running same as the first one

jupyter labextension list

JupyterLab v3.4.5
jupyterlab-execute-time v2.1.0 enabled OK (python, jupyterlab_execute_time)
jupyterlab_pygments v0.2.2 enabled OK (python, jupyterlab_pygments)
nbdime-jupyterlab v2.1.1 enabled OK
@jupyter-widgets/jupyterlab-manager v3.1.1 enabled OK (python, jupyterlab_widgets)
@jupyterlab/geojson-extension v3.1.2 enabled OK (python, jupyterlab-geojson)
@jupyterlab/git v0.32.4 enabled OK (python, jupyterlab-git)

Disabled extensions:
@jupyterlab/extensionmanager-extension (all plugins)
@jupyterlab/running-extension (all plugins)

Body:
I'm trying to create a DatePicker widget in Jupyter Lab with a button, when the user selects a date from the date picker and hits the button, all the below cells should start running for that date. I tried running below code and it is working as expected in the anaconda jupyter notebook but is not working in jupyter lab. Can you help me with the same?

from IPython.display import Javascript, display
import ipywidgets as widgets

fromDatePicker = widgets.DatePicker(description='fromdate')

ToDatePicker = widgets.DatePicker(description='fromdate')

def fromDate():
    return f"'{fromDatePicker.value}'"

def toDate():
    return f"'{ToDatePicker.value}'"

def run_all(ev):
    display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1, IPython.notebook.ncells())'))

button = widgets.Button(description="Run all")
button.on_click(run_all)
widgets.HBox([fromDatePicker, ToDatePicker, button])

after this to check whether it is working or not I'm printing the start date below :

print("start date is :", fromDate())

I expected that after clicking on the Run all button it should start executing the below cells but here I have to go to that cell and run it manually. Kindly please post your answers or suggestions below.

After using ipyab :

import ipywidgets as widgets
from ipylab import JupyterFrontEnd
from IPython.display  import Javascript, display
app = JupyterFrontEnd()

fromDatePicker = widgets.DatePicker(
    description='From Date'
)
ToDatePicker = widgets.DatePicker(
    description='To Date'
)

button = widgets.Button(
    description='Execute',
    disabled=False,
    button_style='success',
)

def fromDate():
    return f"'{fromDatePicker.value}'"

def toDate():
    return f"'{ToDatePicker.value}'"

def run_all(ev):
    app.commands.execute('notebook:run-all-below')

display(button)

button.on_click(run_all)
widgets.HBox([fromDatePicker, ToDatePicker, button])

Above code is also running same as the first one

jupyter labextension list

JupyterLab v3.4.5
jupyterlab-execute-time v2.1.0 enabled OK (python, jupyterlab_execute_time)
jupyterlab_pygments v0.2.2 enabled OK (python, jupyterlab_pygments)
nbdime-jupyterlab v2.1.1 enabled OK
@jupyter-widgets/jupyterlab-manager v3.1.1 enabled OK (python, jupyterlab_widgets)
@jupyterlab/geojson-extension v3.1.2 enabled OK (python, jupyterlab-geojson)
@jupyterlab/git v0.32.4 enabled OK (python, jupyterlab-git)

Disabled extensions:
@jupyterlab/extensionmanager-extension (all plugins)
@jupyterlab/running-extension (all plugins)


问:
Angular > 12: avoiding devDependencies for prod build
Developers in the 2020s live in a world of vulnerabilities and lots of dependencies. My mantra has been "If it isn't used in production, it should not be in production" for a while. I try to implement this in all aspects of my development, but I am having issues with an angular application:

During my CI/CD pipeline I execute the following commands:

During the staging step:

npm ci - installing the dependencies

ng build - building the angular application for testing

During the testing step:

npm run test-headless (translates to ng test --watch=false --browsers=ChromeHeadless) - perform headless testing

During Prod Deploy step: (different node)

npm ci --omit=dev - install w/o devDependencies

ng build --base-href "https://${SITE_FQDN}"

The issue is that the final ng build step fails on the postinstall phase since ngcc is not installed (because it is a devDependency)

Searching around there are many questions about production versions and devDependencies .. even articles about there no longer being a dev build

I am brimming with questions at this point, feeling that I have no control or overview of what I am putting in production, but the main question is:

How do I ensure that what I produce with ng build is production ready without all the development bindings and devDependencies?


问:
Building a Taxii Server at mitre ATT&CK
Is it essential to build a taxii server when you want to proceed with a tool or related project that automatically maps mitre ATT&CK?

I wonder if building a Taxii server is essential

Title: Building a Taxii Server at mitre ATT&CK


问:
java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@ea5bf3d #4983
I am using glide to load few images in my app

the glide that i am using is

com.github.bumptech.glide:glide:4.11.0

The code for loading glide image is

```<code>context?.let { context ->
            Glide.with(context)
                .load(story.url)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .placeholder(binding.ivStory.drawable)
                .listener(object: RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        binding.loader.visibility = View.GONE
                        animation.start()
                        return false
                    }
                }
                )
                .into(binding.ivStory)
</code>```

The exception that I am getting on firebase is as follows

```<code>Fatal Exception: java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@d7a7131
       at android.graphics.BaseCanvas.throwIfCannotDraw(BaseCanvas.java:55)
       at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:234)
       at android.view.RecordingCanvas.drawBitmap(RecordingCanvas.java:97)
       at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:529)
       at android.widget.ImageView.onDraw(ImageView.java:1376)
       at android.view.View.draw(View.java:19442)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)
       at android.view.View.draw(View.java:19445)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)
       at android.view.View.draw(View.java:19445)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at androidx.drawerlayout.widget.DrawerLayout.drawChild(DrawerLayout.java:1426)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.draw(View.java:19445)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.draw(View.java:19445)
       at com.android.internal.policy.DecorView.draw(DecorView.java:892)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:676)
       at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:682)
       at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:790)
       at android.view.ViewRootImpl.draw(ViewRootImpl.java:3503)
       at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3285)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2782)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1718)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7513)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1066)
       at android.view.Choreographer.doCallbacks(Choreographer.java:878)
       at android.view.Choreographer.doFrame(Choreographer.java:794)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1052)
       at android.os.Handler.handleCallback(Handler.java:790)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:210)
       at android.app.ActivityThread.main(ActivityThread.java:7080)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:863)
</code>```

I am not sure what is going wrong here can some one please give proper solution for this.

Body:
I am using glide to load few images in my app

the glide that i am using is

com.github.bumptech.glide:glide:4.11.0

The code for loading glide image is

context?.let { context ->
            Glide.with(context)
                .load(story.url)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .placeholder(binding.ivStory.drawable)
                .listener(object: RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        binding.loader.visibility = View.GONE
                        animation.start()
                        return false
                    }
                }
                )
                .into(binding.ivStory)

The exception that I am getting on firebase is as follows

Fatal Exception: java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@d7a7131
       at android.graphics.BaseCanvas.throwIfCannotDraw(BaseCanvas.java:55)
       at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:234)
       at android.view.RecordingCanvas.drawBitmap(RecordingCanvas.java:97)
       at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:529)
       at android.widget.ImageView.onDraw(ImageView.java:1376)
       at android.view.View.draw(View.java:19442)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)
       at android.view.View.draw(View.java:19445)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)
       at android.view.View.draw(View.java:19445)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at androidx.drawerlayout.widget.DrawerLayout.drawChild(DrawerLayout.java:1426)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.draw(View.java:19445)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.updateDisplayListIfDirty(View.java:18383)
       at android.view.View.draw(View.java:19170)
       at android.view.ViewGroup.drawChild(ViewGroup.java:4324)
       at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4087)
       at android.view.View.draw(View.java:19445)
       at com.android.internal.policy.DecorView.draw(DecorView.java:892)
       at android.view.View.updateDisplayListIfDirty(View.java:18392)
       at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:676)
       at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:682)
       at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:790)
       at android.view.ViewRootImpl.draw(ViewRootImpl.java:3503)
       at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3285)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2782)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1718)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7513)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1066)
       at android.view.Choreographer.doCallbacks(Choreographer.java:878)
       at android.view.Choreographer.doFrame(Choreographer.java:794)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1052)
       at android.os.Handler.handleCallback(Handler.java:790)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:210)
       at android.app.ActivityThread.main(ActivityThread.java:7080)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:863)

I am not sure what is going wrong here can some one please give proper solution for this.


问:
How to accept data from client into database
How to accept data from the client using a Post request (Login, password, email) with subsequent entry into the database for use when logging in

I used it, but I don't fully understand it correctly or not, most likely not because nothing is written to the database

Views.py

```<code>class Reqs:
    def __init__(self, user, password, email):
        self.user = user
        self.password = password
        self.email = email

class ReqsEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Reqs):
            return {
                "user": obj.user,
                "password": obj.password,
                "email": obj.email,
            }
        return super().default(obj)

def api_response(request):
    user = request.POST.get("user")
    password = request.POST.get("password")
    email_ = request.POST.get("email")
    data = Data(user, password, email_)
    data.save()
    try:
        return HttpResponse(data, safe=False, encoder=ReqsEncoder)
    except:
        return HttpResponse("G")
</code>```

Body:
How to accept data from the client using a Post request (Login, password, email) with subsequent entry into the database for use when logging in

I used it, but I don't fully understand it correctly or not, most likely not because nothing is written to the database

Views.py

class Reqs:
    def __init__(self, user, password, email):
        self.user = user
        self.password = password
        self.email = email

class ReqsEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Reqs):
            return {
                "user": obj.user,
                "password": obj.password,
                "email": obj.email,
            }
        return super().default(obj)

def api_response(request):
    user = request.POST.get("user")
    password = request.POST.get("password")
    email_ = request.POST.get("email")
    data = Data(user, password, email_)
    data.save()
    try:
        return HttpResponse(data, safe=False, encoder=ReqsEncoder)
    except:
        return HttpResponse("G")


问:
How to Detect Ad on Youtube Using Selenium in Python
I’ve been trying to use python selenium to watch YouTube videos for me and collect data.

Getting the data is fairly easy, however, I run into problems when an ad pops up in YouTube.

For some reason I can't figure out how to detect whether or not I have an ad

My current function is:

```<code>def check_ad():
 try:
            WebDriverWait(driver, 20).until(         EC.presence_of_element_located(driver.find_element_by_xpath('//*[@id="simple-ad-badge:g"]'))
            )
          print("Ad detected")
 except:
            print("No Ad")
</code>```

Does anyone know any other way I can do this?

I've tried multiple different element selections, including the advertisment website link, the presence of the skip ad button, the little ad blurb at the bottom but nothing seems to work. I've also tried look for class name and id.

Body:
I’ve been trying to use python selenium to watch YouTube videos for me and collect data.

Getting the data is fairly easy, however, I run into problems when an ad pops up in YouTube.

For some reason I can't figure out how to detect whether or not I have an ad

My current function is:

def check_ad():
 try:
            WebDriverWait(driver, 20).until(         EC.presence_of_element_located(driver.find_element_by_xpath('//*[@id="simple-ad-badge:g"]'))
            )
          print("Ad detected")
 except:
            print("No Ad")

Does anyone know any other way I can do this?

I've tried multiple different element selections, including the advertisment website link, the presence of the skip ad button, the little ad blurb at the bottom but nothing seems to work. I've also tried look for class name and id.