问:
How do i decide on the option parameters when using PSO pyswarms
im trying to use binary pso package from pyswarms to conduct a text classification.

however I am a bit stuck on what parameters i should use?

c1 :float

cognitive parameter

c2 :float

social parameter

w :float

inertia parameter

k :int

number of neighbors to be considered. Must be a positive integer less than n_particles
p: int {1,2}

These are the default parameters:

```<code>options = {'c1': 0.5, 'c2': 0.5, 'w':0.9, 'k': 30, 'p':2}

</code>```

is there a specific way i need to choose them? so far ive honestly playing around with different parameters randomly.

Body:
im trying to use binary pso package from pyswarms to conduct a text classification.

however I am a bit stuck on what parameters i should use?

c1 :float

cognitive parameter

c2 :float

social parameter

w :float

inertia parameter

k :int

number of neighbors to be considered. Must be a positive integer less than n_particles
p: int {1,2}

These are the default parameters:

options = {'c1': 0.5, 'c2': 0.5, 'w':0.9, 'k': 30, 'p':2}

is there a specific way i need to choose them? so far ive honestly playing around with different parameters randomly.


来源: stackexchange

问:
Animation speed on matplotlib
I'm trying to code a double pendulum using a data table calculated in .c files (don't ask me why, this is nonsense, it's the rules of the project). I'm trying to plot the kinetic, potential and mecanical energy using matplotlib and the "animate" function , but the animation is running too slow. I even tried to change the frames value but that didn't do anything. Here is my code :

```<code>import numpy as np
import matplotlib
from matplotlib import animation
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

#Téléchargement des donnés txt en tableau à 2 colonnes
Data3 = np.loadtxt('EnergieCinetique.txt')
Data4 = np.loadtxt('EnergiePotentiel.txt')

T = Data3[:,0] #Temps
EC= Data3[:,1]#Energie cinétique
print(EC)
EU = Data4[:,1] #energie Potentielle

# Longueur maximale des 2 tableaux
lens=[len(EC), len(EU)]
max_len=max(lens)

# Calcul de l'energie mecanique
E = []
for i in range (0, max_len):
    E.append(EC[i] + EU[i] )
    print(E[i])

def updateline(num, data1, line1, data2, line2, data3, line3):
    line1.set_data(data1[..., :num])
    line2.set_data(data2[..., :num])
    line3.set_data(data3[..., :num])

    return line1, line2, line3

#Data de EC en fonction de T
x = T
y = EC
data1 = np.array([x, y])

#Data de EU en fonction de T
x2 = T
y2 = EU
data2 = np.array([x2, y2])

# generating data of 100 elements
# each for line 2
x3 = T
y3 = E
data3 = np.array([x3, y3])

fig = plt.figure()
ax = fig.add_subplot(111)
l, = ax.plot([], [], 'r-', label="Energie cinétique")
ax2 = ax.twinx()
k = ax2.plot([], [], 'g-', label="Energie potentielle")[0]
ax3= ax.twinx()
w, = ax.plot([], [], 'b-', label="Energie mécanique")

ax.legend([l, k], [l.get_label(), k.get_label()], loc=0)
ax.legend([l, k, w], [l.get_label(), k.get_label(), w.get_label()], loc=0)

ax.set_xlabel("t [s]")
ax.set_ylabel("E [J]")

# Limites de l'axe 1
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)

# Limites de l'axe 2
ax2.set_ylim(-1, 1)
ax2.set_xlim(0, 5)

# Limites de l'axe 2
ax3.set_ylim(-1, 1)
ax3.set_xlim(0, 5)

plt.title('Energie cinétique et potentielle')
time_text = ax.text(0.1, 0.95, "", transform=ax.transAxes,fontsize=15, color='red')

# set line_animation variable to call the function recursively
line_animation = animation.FuncAnimation( fig, updateline, frames=1000, fargs=(data1, l, data2, k, data3, w ))

plt.show()
</code>```

Any help will be appreciated!

I tried to increase the frames (line 87) but the graph is still running slow. I expected to have a fatser animation

ContentLicense: CC BY-SA 4.0

Title: Animation speed on matplotlib

Body:
I'm trying to code a double pendulum using a data table calculated in .c files (don't ask me why, this is nonsense, it's the rules of the project). I'm trying to plot the kinetic, potential and mecanical energy using matplotlib and the "animate" function , but the animation is running too slow. I even tried to change the frames value but that didn't do anything. Here is my code :

import numpy as np
import matplotlib
from matplotlib import animation
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

#Téléchargement des donnés txt en tableau à 2 colonnes
Data3 = np.loadtxt('EnergieCinetique.txt')
Data4 = np.loadtxt('EnergiePotentiel.txt')

T = Data3[:,0] #Temps
EC= Data3[:,1]#Energie cinétique
print(EC)
EU = Data4[:,1] #energie Potentielle

# Longueur maximale des 2 tableaux
lens=[len(EC), len(EU)]
max_len=max(lens)

# Calcul de l'energie mecanique
E = []
for i in range (0, max_len):
    E.append(EC[i] + EU[i] )
    print(E[i])

def updateline(num, data1, line1, data2, line2, data3, line3):
    line1.set_data(data1[..., :num])
    line2.set_data(data2[..., :num])
    line3.set_data(data3[..., :num])

    return line1, line2, line3

#Data de EC en fonction de T
x = T
y = EC
data1 = np.array([x, y])

#Data de EU en fonction de T
x2 = T
y2 = EU
data2 = np.array([x2, y2])

# generating data of 100 elements
# each for line 2
x3 = T
y3 = E
data3 = np.array([x3, y3])

fig = plt.figure()
ax = fig.add_subplot(111)
l, = ax.plot([], [], 'r-', label="Energie cinétique")
ax2 = ax.twinx()
k = ax2.plot([], [], 'g-', label="Energie potentielle")[0]
ax3= ax.twinx()
w, = ax.plot([], [], 'b-', label="Energie mécanique")

ax.legend([l, k], [l.get_label(), k.get_label()], loc=0)
ax.legend([l, k, w], [l.get_label(), k.get_label(), w.get_label()], loc=0)

ax.set_xlabel("t [s]")
ax.set_ylabel("E [J]")

# Limites de l'axe 1
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)

# Limites de l'axe 2
ax2.set_ylim(-1, 1)
ax2.set_xlim(0, 5)

# Limites de l'axe 2
ax3.set_ylim(-1, 1)
ax3.set_xlim(0, 5)

plt.title('Energie cinétique et potentielle')
time_text = ax.text(0.1, 0.95, "", transform=ax.transAxes,fontsize=15, color='red')

# set line_animation variable to call the function recursively
line_animation = animation.FuncAnimation( fig, updateline, frames=1000, fargs=(data1, l, data2, k, data3, w ))

plt.show()

Any help will be appreciated!

I tried to increase the frames (line 87) but the graph is still running slow. I expected to have a fatser animation


问:
Oauth 2.0 WebClient C#
I'm trying to get a token using Oauth2, Webclient and C#, but so far no success.

I am doing it in a console application, once it worked I must take it to an SSIS script

```<code>In this attempt I did it in another way, so it doesn't work for me. I must get the token using WebClient,

I tried the following:

 private static string Token()
        {
            string wClientId = "...";
            string wClientSecretKey = "...";
            string wAccessToken;

            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

            HttpResponseMessage responseMessage;
            using (HttpClient client = new HttpClient())
            {
                HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://xxxxxxxxxxxxx/oauth2/token");
                HttpContent httpContent = new FormUrlEncodedContent(
                        new[]
                        {
                                        new KeyValuePair<string, string>("grant_type", "client_credentials"),
                        });
                tokenRequest.Content = httpContent;
                tokenRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(wClientId + ":" + wClientSecretKey)));
                responseMessage = client.SendAsync(tokenRequest).Result;
            }
            string ResponseJSON = responseMessage.Content.ReadAsStringAsync().Result;
</code>```

Title: Oauth 2.0 WebClient C#

Body:
I'm trying to get a token using Oauth2, Webclient and C#, but so far no success.

I am doing it in a console application, once it worked I must take it to an SSIS script

In this attempt I did it in another way, so it doesn't work for me. I must get the token using WebClient,

I tried the following:

 private static string Token()
        {
            string wClientId = "...";
            string wClientSecretKey = "...";
            string wAccessToken;

            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

            HttpResponseMessage responseMessage;
            using (HttpClient client = new HttpClient())
            {
                HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://xxxxxxxxxxxxx/oauth2/token");
                HttpContent httpContent = new FormUrlEncodedContent(
                        new[]
                        {
                                        new KeyValuePair<string, string>("grant_type", "client_credentials"),
                        });
                tokenRequest.Content = httpContent;
                tokenRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(wClientId + ":" + wClientSecretKey)));
                responseMessage = client.SendAsync(tokenRequest).Result;
            }
            string ResponseJSON = responseMessage.Content.ReadAsStringAsync().Result;


问:
Why is .Match() not throwing an error? My code should catch when an error is thrown, but instead the function is returning the previously held value
I need to catch an error to break out of a loop iteration whenever a value is not found in a range.

WorksheetFunction.Match is just returning the previous value held by the last iteration instead of throwing an error when its not found.

I have similar logic above this doing the same thing and it is catching the error when no value is found in a range.

Any idea why .Match() is not throwing an error?

```<code>        For k = 1 To 53
            If Not IsError(Application.WorksheetFunction.Match(Cells(2, k).Value, CLrng, 0)) Then
                CLcolIndex = Application.WorksheetFunction.Match(Cells(2, k).Value, CLrng, 0)
                Worksheets("Change Log").Cells(currCLRow, CLcolIndex).Value = Cells(i, k).Value
            Else
                GoTo Nextk
            End If
Nextk:
        Next k
</code>```

I expected this to fall into one of the cases when an error is thrown from the compiler.

Body:
I need to catch an error to break out of a loop iteration whenever a value is not found in a range.

WorksheetFunction.Match is just returning the previous value held by the last iteration instead of throwing an error when its not found.

I have similar logic above this doing the same thing and it is catching the error when no value is found in a range.

Any idea why .Match() is not throwing an error?

        For k = 1 To 53
            If Not IsError(Application.WorksheetFunction.Match(Cells(2, k).Value, CLrng, 0)) Then
                CLcolIndex = Application.WorksheetFunction.Match(Cells(2, k).Value, CLrng, 0)
                Worksheets("Change Log").Cells(currCLRow, CLcolIndex).Value = Cells(i, k).Value
            Else
                GoTo Nextk
            End If
Nextk:
        Next k

I expected this to fall into one of the cases when an error is thrown from the compiler.


问:
Undefined reference after added QNetworkAccessManager?
I created a new class and added a function to it which is supposed to retrieve data on the current euro exchange rate. I used QNetworkAccessManager. When I try to build project I got errors. After I comment QNetworkAccessManager logic errors disapeard.

Currencies.h

```<code>#ifndef CURRENCIES_H
#define CURRENCIES_H

#include <QObject>
#include <QFile>
#include <QTextStream>
#include <QtDebug>
#include <QList>
#include <QProcess>

#include <QRegularExpression>
#include <QSettings>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtXml/QtXml>
#include <QDebug>
#include <string.h>

#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QObject>
#include <algorithm>

#include "Connections.h"

    class Euro : public QObject
    {
        Q_OBJECT

    private:
        //Ui::MainWindow *ui;
        float euroRate=0;
        float finalPriceEuro = 0;
        float finalPrice = 0;
        QString const urlEuroString = "http://api.nbp.pl/api/exchangerates/rates/a/eur/?format=json";
        Connection::Status connectStatus;
        QSettings settings;

    public:
        Euro();
        ~Euro();
        float GetEuroRate() const;
        void SetEuroRate(double);

        void SetFinalPriceEuro(float);
        float GetFinalPriceEuro() const;

        void SetFinalPrice(float);
        float GetFinalPrice() const;

        QString GetEuroUrl() const;

        void SaveEuroRate();

        void LoadEuroRate();

    };

#endif // CURRENCIES_H

</code>```

Currencies.cpp

```<code>#include "Currencies.h"

Euro::Euro()
{
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);

    connect(manager,&QNetworkAccessManager::finished,this,[&](QNetworkReply* reply)
            {

                if(reply->bytesAvailable())
                {
                    connectStatus.SetConnectionStatus(true);
                }
                else
                {
                    connectStatus.SetConnectionStatus(false);
                }
            });

    qDebug()<<connectStatus.GetConnectionStatus();
}

Euro::~Euro()
{

}

float Euro::GetEuroRate() const{
    return euroRate;
}

void Euro::SetEuroRate(double rateValue){
    euroRate = rateValue;
}

QString Euro::GetEuroUrl() const{
    return urlEuroString;
}

void Euro::SetFinalPriceEuro(float price)
{
    finalPriceEuro = price;
}

float Euro::GetFinalPriceEuro() const
{
    return finalPriceEuro;
}

void Euro::SetFinalPrice(float price)
{
    finalPrice = price;
}

float Euro::GetFinalPrice() const
{
    return finalPrice;
}

void Euro::SaveEuroRate(){
    //settings.setValue("euroRate",currencyRate.GetEuroRate());
    qDebug()<<"Zapisano!";
}

void Euro::LoadEuroRate()
{

}
</code>```

Errors

```<code>:-1: error: CMakeFiles/ATLAS.dir/Currencies.cpp.obj:Currencies.cpp:(.text+0x2b0): undefined reference to `__imp__ZN21QNetworkAccessManagerC1EP7QObject'
:-1: error: CMakeFiles/ATLAS.dir/Currencies.cpp.obj:Currencies.cpp:(.text+0x2b7): undefined reference to `__imp__ZN21QNetworkAccessManager8finishedEP13QNetworkReply'
:-1: error: CMakeFiles/ATLAS.dir/Currencies.cpp.obj:Currencies.cpp:(.text+0x2d6): undefined reference to `__imp__ZN21QNetworkAccessManager16staticMetaObjectE'
:-1: error: collect2.exe: error: ld returned 1 exit status

</code>```

Any idea how to solve this? Thanks a lot !

Body:
I created a new class and added a function to it which is supposed to retrieve data on the current euro exchange rate. I used QNetworkAccessManager. When I try to build project I got errors. After I comment QNetworkAccessManager logic errors disapeard.

Currencies.h

#ifndef CURRENCIES_H
#define CURRENCIES_H

#include <QObject>
#include <QFile>
#include <QTextStream>
#include <QtDebug>
#include <QList>
#include <QProcess>

#include <QRegularExpression>
#include <QSettings>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtXml/QtXml>
#include <QDebug>
#include <string.h>

#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QObject>
#include <algorithm>

#include "Connections.h"

    class Euro : public QObject
    {
        Q_OBJECT

    private:
        //Ui::MainWindow *ui;
        float euroRate=0;
        float finalPriceEuro = 0;
        float finalPrice = 0;
        QString const urlEuroString = "http://api.nbp.pl/api/exchangerates/rates/a/eur/?format=json";
        Connection::Status connectStatus;
        QSettings settings;

    public:
        Euro();
        ~Euro();
        float GetEuroRate() const;
        void SetEuroRate(double);

        void SetFinalPriceEuro(float);
        float GetFinalPriceEuro() const;

        void SetFinalPrice(float);
        float GetFinalPrice() const;

        QString GetEuroUrl() const;

        void SaveEuroRate();

        void LoadEuroRate();

    };

#endif // CURRENCIES_H

Currencies.cpp

#include "Currencies.h"

Euro::Euro()
{
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);

    connect(manager,&QNetworkAccessManager::finished,this,[&](QNetworkReply* reply)
            {

                if(reply->bytesAvailable())
                {
                    connectStatus.SetConnectionStatus(true);
                }
                else
                {
                    connectStatus.SetConnectionStatus(false);
                }
            });

    qDebug()<<connectStatus.GetConnectionStatus();
}

Euro::~Euro()
{

}

float Euro::GetEuroRate() const{
    return euroRate;
}

void Euro::SetEuroRate(double rateValue){
    euroRate = rateValue;
}

QString Euro::GetEuroUrl() const{
    return urlEuroString;
}

void Euro::SetFinalPriceEuro(float price)
{
    finalPriceEuro = price;
}

float Euro::GetFinalPriceEuro() const
{
    return finalPriceEuro;
}

void Euro::SetFinalPrice(float price)
{
    finalPrice = price;
}

float Euro::GetFinalPrice() const
{
    return finalPrice;
}

void Euro::SaveEuroRate(){
    //settings.setValue("euroRate",currencyRate.GetEuroRate());
    qDebug()<<"Zapisano!";
}

void Euro::LoadEuroRate()
{

}

Errors

:-1: error: CMakeFiles/ATLAS.dir/Currencies.cpp.obj:Currencies.cpp:(.text+0x2b0): undefined reference to `__imp__ZN21QNetworkAccessManagerC1EP7QObject'
:-1: error: CMakeFiles/ATLAS.dir/Currencies.cpp.obj:Currencies.cpp:(.text+0x2b7): undefined reference to `__imp__ZN21QNetworkAccessManager8finishedEP13QNetworkReply'
:-1: error: CMakeFiles/ATLAS.dir/Currencies.cpp.obj:Currencies.cpp:(.text+0x2d6): undefined reference to `__imp__ZN21QNetworkAccessManager16staticMetaObjectE'
:-1: error: collect2.exe: error: ld returned 1 exit status

Any idea how to solve this? Thanks a lot !


问:
Value of RatingBar getting changed dynamically on scroll
I'm displaying a list of food orders using a RecyclerView. Each view item has a RatingBar, so client can submit rating for the order.

Problem: When client scrolls down and goes back up, the value of the RatingBar shown on an order item changes (no other data changes).

Example:

Initial State:

After I scroll all the way down, and come back up:

Value of the rating bar of the second item gets updated automatically.

No where in the code are we updating the value of RatingBar programatically. Based on our expected behaviour, it should only change when user clicks on it.

Project code:

https://github.com/uOttawaSEGA2022/project-group-4/tree/lastissue

Link to code where RecyclerView and the adapters are defined:

Activity Class
|  Adapter
| Order Item View
|  Orders List Screen

Solutions tried:

Used ListView, RecyclerView, RecyclerView with ListAdapter - same issue in all

Tried setting a change listener on rating bar, and could see that it's getting changed dynamically on scroll even without any user interaction.

```<code>holder.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        if (fromUser) {
            Log.d("ratingBarUpdate", "User updated Rating bar: " + ratingBar.getId());
        } else {
            Log.e("ratingBarUpdate", "Rating bar updated programmatically: " + ratingBar.getId());
        }
    }
});
</code>```

I'm aware, RecyclerView (and ListView etc.) dynamically update existing view items to display data on scroll. The problem is on scrolling back up, the data is incorrect (or not updated correctly).

Is there any way to fix this? Or any other way to display such information which help avoid this problem?

Body:
I'm displaying a list of food orders using a RecyclerView. Each view item has a RatingBar, so client can submit rating for the order.

Problem: When client scrolls down and goes back up, the value of the RatingBar shown on an order item changes (no other data changes).

Example:

Initial State:

After I scroll all the way down, and come back up:

Value of the rating bar of the second item gets updated automatically.

No where in the code are we updating the value of RatingBar programatically. Based on our expected behaviour, it should only change when user clicks on it.

Project code:

https://github.com/uOttawaSEGA2022/project-group-4/tree/lastissue

Link to code where RecyclerView and the adapters are defined:

Activity Class
|  Adapter
| Order Item View
|  Orders List Screen

Solutions tried:

Used ListView, RecyclerView, RecyclerView with ListAdapter - same issue in all

Tried setting a change listener on rating bar, and could see that it's getting changed dynamically on scroll even without any user interaction.

holder.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        if (fromUser) {
            Log.d("ratingBarUpdate", "User updated Rating bar: " + ratingBar.getId());
        } else {
            Log.e("ratingBarUpdate", "Rating bar updated programmatically: " + ratingBar.getId());
        }
    }
});

I'm aware, RecyclerView (and ListView etc.) dynamically update existing view items to display data on scroll. The problem is on scrolling back up, the data is incorrect (or not updated correctly).

Is there any way to fix this? Or any other way to display such information which help avoid this problem?


问:
How to Access Locally Hosted Website using DNS
I have a Synology NAS hosting my PHP website that uses a GoDaddy DNS.

Currently, if I want to access my website using the DNS over the internet I have to change the $_GLOBAL variable URLROOT I set to the DNS and if I want to access the site locally, I have to change the URLROOT to my Synology’s local IP.

Is there a way I can access the site both locally and over the internet while using the DNS?

A thought that crossed my mind is potentially changing the URLROOT depending on the user’s IP, but I’m not sure that’s possible.


问:
JUnitException: TestEngine with ID 'spock' failed to discover tests
We are attempting to make some updates to our testing suite.  We would like to convert our contract tests that use PACT to use jUnit5.

When we update our packages such as our PACT consumer/provider and attempt to run the code we get this exception :

```<code>org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 8.
...
Caused by: org.junit.platform.commons.JUnitException: TestEngine with ID 'spock' failed to discover tests
</code>```

The current build.gradle file contains

```<code>plugins {
    id 'java'
    id 'groovy'
    id "au.com.dius.pact" version '4.2.13'
}

dependencies {
    testImplementation 'org.codehaus.groovy:groovy:3.0.12'
    testImplementation group: 'au.com.dius.pact.consumer', name: 'junit5', version: '4.3.4'
    testImplementation group: 'au.com.dius.pact.provider', name: 'junit5', version: '4.3.4'
    testImplementation 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
    testImplementation 'com.motorolasolutions.pnf:utils:1.0.+:test-lib'
    testImplementation "org.spockframework:spock-core:2.1-M2-groovy-3.0"
    testImplementation "org.spockframework:spock-spring:2.1-M2-groovy-3.0"
    testImplementation "org.spockframework:spock-core:2.1-M2-groovy-3.0"
    testImplementation('com.athaydes:spock-reports:2.1.1-groovy-3.0') {
        transitive = false
    }

    testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter', version: '5.9.1'
    testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.9.1'
}

</code>```

We have tried messing with the plugin Id for 'groovy' and 'java' without luck.  Does anyone have any recommendations on this issue?

Thanks

Body:
We are attempting to make some updates to our testing suite.  We would like to convert our contract tests that use PACT to use jUnit5.

When we update our packages such as our PACT consumer/provider and attempt to run the code we get this exception :

org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 8.
...
Caused by: org.junit.platform.commons.JUnitException: TestEngine with ID 'spock' failed to discover tests

The current build.gradle file contains

plugins {
    id 'java'
    id 'groovy'
    id "au.com.dius.pact" version '4.2.13'
}

dependencies {
    testImplementation 'org.codehaus.groovy:groovy:3.0.12'
    testImplementation group: 'au.com.dius.pact.consumer', name: 'junit5', version: '4.3.4'
    testImplementation group: 'au.com.dius.pact.provider', name: 'junit5', version: '4.3.4'
    testImplementation 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
    testImplementation 'com.motorolasolutions.pnf:utils:1.0.+:test-lib'
    testImplementation "org.spockframework:spock-core:2.1-M2-groovy-3.0"
    testImplementation "org.spockframework:spock-spring:2.1-M2-groovy-3.0"
    testImplementation "org.spockframework:spock-core:2.1-M2-groovy-3.0"
    testImplementation('com.athaydes:spock-reports:2.1.1-groovy-3.0') {
        transitive = false
    }

    testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter', version: '5.9.1'
    testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.9.1'
}

We have tried messing with the plugin Id for 'groovy' and 'java' without luck.  Does anyone have any recommendations on this issue?

Thanks


问:
How to declare variables in a packer built AMI image
I want to create a pre-install ami with packer to use in my ASG and came across a problem.
After creating an EFS, i want t be able to mount it in my AMI.
i am running below in provisioner:

```<code>sudo mount -t nfs -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport ${efs_dns_name}:/  /var/www/html
# Making Mount Permanent
sudo echo '${efs_dns_name}:/ /var/www/html nfs4 defaults,vers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport 0 0' >> /etc/fstab
</code>```
```<code>efs_dns_name = data.aws_efs_file_system.efs.dns_name
</code>```

how can i declare my efs_dns_name variable in packer provisioner so it will populate in mount script?

Body:
I want to create a pre-install ami with packer to use in my ASG and came across a problem.
After creating an EFS, i want t be able to mount it in my AMI.
i am running below in provisioner:

sudo mount -t nfs -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport ${efs_dns_name}:/  /var/www/html
# Making Mount Permanent
sudo echo '${efs_dns_name}:/ /var/www/html nfs4 defaults,vers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport 0 0' >> /etc/fstab

efs_dns_name = data.aws_efs_file_system.efs.dns_name

how can i declare my efs_dns_name variable in packer provisioner so it will populate in mount script?


问:
ASP.Net IHttpModule - how to read variable set in page from custom handler?
I have a web page (asp.net 4, c#) that when a particular action occurs, I need to set a variable and in my custom handler, check the variable value.

My custom module class implements IHttpModule and IRequiredSessionState (note: session variables are not used).

More specifically, I am implementing the method Context_PostAuthenticatioRequest.

The sequence of events is:-
Client page posts back (__doPostBack)
PostAuthenticateRequest is called
Page_Load is called.

I can access both the Request and Response objects in the handler, what I don't know is how to set the variable/flag in JQuery so that it can be picked up.


问:
JavaScript Bokeh problem with hbars and hovertool
I am trying to create a hbar graphic with a working hover tool using the JavaScript Bokeh library but I am running into a few problems. I usually use Bokeh in Python but for my current workflow it makes more sense to write it in JavaScrip.

To have the hover tool working correctly for my graphic I need to properly use the ColumnDataSource object correctly in the hbar but for whatever reason I am only able to get it working by populating it directly into it's parameters with arrays.

Any help would be greatly appreciated and thank you in advance to anyone who helps/takes the time to read this.

<!doctype html>

<meta charset="utf-8">
<title>Example Code</title>

```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Complete Example</title>

<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.4.3.min.js"></script>

<script>
//The order of CSS and JS imports above is important.
</script>
<script type="module">

    // create some data and a ColumnDataSource
    const plt = Bokeh.Plotting;

    var x_data = [1,6,-1];
    var y_data = ["a","b","c"];
    var z_data = [45,62,12];

    const
    arrays = [x_data, y_data,z_data],
    sorted = arrays.map(
        (indices => a => indices.map(i => a[i]))
        ([...arrays[0].keys()].sort((a, b) => arrays[0][a] - arrays[0][b]))
    );

    // console.log();
    x_data = sorted[0];
    y_data = sorted[1];
    z_data = sorted[2];

    const source = new Bokeh.ColumnDataSource({data: { x: x_data,y:y_data,z: z_data }});

     // create some ranges for the plot
     const xdr = new Bokeh.Range1d({ start: -3, end: 3 });
    // const ydr = new Bokeh.Range1d({ start: -7.5, end: 20.5 });

    // make the plot
    const plot = Bokeh.Plotting.figure({

        title: "Hbar test Graph",
        x_range: xdr,
        y_range: y_data,
        toolbar_location: null,
        width: 550,
        height: 550,
        background_fill_color: "#F2F2F7",
        source: source,
    });

    console.log(source);

    // add a line with data from the source
    const hbar = plot.hbar({
        left:0,
        name:"Hbar",
        right:x_data,
        y:y_data,
        height:0.7,
        source: source,
    });

    const hover_tool= new Bokeh.HoverTool({renderers:[hbar],
                             tooltips:[("val", "@z")]});

    plot.add_tools(hover_tool);

    Bokeh.Plotting.show(plot);

</script>
</head>

<body>
</body>

</html></code>```

Body:
I am trying to create a hbar graphic with a working hover tool using the JavaScript Bokeh library but I am running into a few problems. I usually use Bokeh in Python but for my current workflow it makes more sense to write it in JavaScrip.

To have the hover tool working correctly for my graphic I need to properly use the ColumnDataSource object correctly in the hbar but for whatever reason I am only able to get it working by populating it directly into it's parameters with arrays.

Any help would be greatly appreciated and thank you in advance to anyone who helps/takes the time to read this.

<!doctype html>

<meta charset="utf-8">
<title>Example Code</title>

<!doctype html>

<meta charset="utf-8">
<title>Complete Example</title>


问:
Read string from html code and save to file
I need to save this name to file "Lørenskog" and read again later

```<code>- original title on web page "Lørenskog"
titles_urls = self.driver.find_elements(By.XPATH, './/a')
- in the webpage html code -> "\u00f8renskog"
for t in titles_urls:
    if t.get_attribute('href'):
        print(t.get_attribute('href')) # it prints -> "%C3%B8renskog"
</code>```

How do I save it to file and read like "Lørenskog" again ?I think it's in utf-8 code

EDIT :

```<code>import urllib.parse
sample = 'L%C3%B8renskog'
a = urllib.parse.unquote(sample)
print(a)
</code>```

output :
Lørenskog

it's url encoded

Body:
I need to save this name to file "Lørenskog" and read again later

- original title on web page "Lørenskog"
titles_urls = self.driver.find_elements(By.XPATH, './/a')
- in the webpage html code -> "\u00f8renskog"
for t in titles_urls:
    if t.get_attribute('href'):
        print(t.get_attribute('href')) # it prints -> "%C3%B8renskog"

How do I save it to file and read like "Lørenskog" again ?I think it's in utf-8 code

EDIT :

import urllib.parse
sample = 'L%C3%B8renskog'
a = urllib.parse.unquote(sample)
print(a)

output :
Lørenskog

it's url encoded


问:
How to not wait for .animate() to finish to play next animation on click jQuery?
I want my animation to just go (like translateX) rather than waiting for .animate() to finish on button clicks

I want my animation to just go (like translateX) rather than waiting for .animate() to finish on button clicks.. can you help me? So i want it to activate every time i click rather than waiting for every animation to execute.. it is very slow like that because it blocks user clicks until the animation is done.

HTML

```<code>  <button class="nextBtn">Next</button>
  <button class="prevBtn">Prev</button>
  <div class="carousel" style="font-size: 0;">
    <img src="assets/img1.jpg">
    <img src="assets/img2.jpg">
    <img src="assets/img3.jpg">
  </div>
</code>```

CSS

```<code>img {
    width: 500px;
    position: relative;
}

.carousel {
    border: 1px solid red;
    width: 500px;
    display: flex;
    overflow: hidden;
}
</code>```

jQuery

```<code>  let count = 1;
  $(".nextBtn").click(function() {
    if(count < $("img").length) {
      $("img").animate({left: "-=500px"})
      count++;
    }
  });

  $(".prevBtn").click(function() {
    if(count > 1) {
      $("img").animate({left: "+=500px"});
      count--;
    }
  });
</code>```

Body:
I want my animation to just go (like translateX) rather than waiting for .animate() to finish on button clicks

I want my animation to just go (like translateX) rather than waiting for .animate() to finish on button clicks.. can you help me? So i want it to activate every time i click rather than waiting for every animation to execute.. it is very slow like that because it blocks user clicks until the animation is done.

HTML

  <button class="nextBtn">Next</button>
  <button class="prevBtn">Prev</button>

CSS

img {
    width: 500px;
    position: relative;
}

.carousel {
    border: 1px solid red;
    width: 500px;
    display: flex;
    overflow: hidden;
}

jQuery

  let count = 1;
  $(".nextBtn").click(function() {
    if(count < $("img").length) {
      $("img").animate({left: "-=500px"})
      count++;
    }
  });

  $(".prevBtn").click(function() {
    if(count > 1) {
      $("img").animate({left: "+=500px"});
      count--;
    }
  });


问:
Salesforce Trigger not Saving (Data Integration Specialist Superbadge)
I am working on the Data Integration Specialist Superbadge. I can't get the call out trigger to save.

Challenge Not yet complete... here's what's wrong:

The ProjectTrigger does not appear to be calling 'BillingCalloutService.callBillingService()' and passing in the collection of old and new records.

The Trigger doesn't seem to be saving either on the Developer Console or the Apex Trigger in Setup. I have deleted the old workspace in workspace manager in the console as it could be corrupt.

Any ideas or recommendations?

Any recommendations to fix the trigger not saving?


问:
Getting the same prediction when using the PyMC3 data container to generate Bayesian regression prediction using new data
I built the Bayesian regression using PyMC3 package. I'm trying to generate prediction using new data. I used the data container pm.Data() to train the model with the training data, then passed the new data to pm.set_data() before calling pm.sample_posterior_predictive(). The prediction was what I would expect from the training data, not the new data.

Here's my model:

```<code>df_train = df.drop(['Unnamed: 0', 'DATE_AT'], axis=1)

with Model() as model:
    response_mean = []
    x_ = pm.Data('features', df_train) # a data container, can be changed
    t = np.transpose(x_.get_value())

    # intercept
    y = Normal('y', mu=0, sigma=6000)
    response_mean.append(y)

    # channels that can have DECAY and SATURATION effects
    for channel_name in delay_channels:
        i = df_train.columns.get_loc(channel_name)
        xx = t[i].astype(float)

        print(f'Adding Delayed Channels: {channel_name}')
        c = coef.loc[coef['features']==channel_name, 'coef'].values[0]
        s = abs(c*0.015)
        if c <= 0:
            channel_b = HalfNormal(f'beta_{channel_name}', sd=s)
        else:
            channel_b = Normal(f'beta_{channel_name}', mu=c, sigma=s)

        alpha = Beta(f'alpha_{channel_name}', alpha=3, beta=3)
        channel_mu = Gamma(f'mu_{channel_name}', alpha=3, beta=1)
        response_mean.append(logistic_function(
            geometric_adstock_tt(xx, alpha), channel_mu) * channel_b)

    # channels that have SATURATION effects only
    for channel_name in non_lin_channels:
        i = df_train.columns.get_loc(channel_name)
        xx = t[i].astype(float)

        print(f'Adding Non-Linear Logistic Channel: {channel_name}')
        c = coef.loc[coef['features']==channel_name, 'coef'].values[0]
        s = abs(c*0.015)
        if c <= 0:
            channel_b = HalfNormal(f'beta_{channel_name}', sd=s)
        else:
            channel_b = Normal(f'beta_{channel_name}', mu=c, sigma=s)

        # logistic reach curve
        channel_mu = Gamma(f'mu_{channel_name}', alpha=3, beta=1)
        response_mean.append(logistic_function(xx, channel_mu) * channel_b)

    # continuous external features
    for channel_name in control_vars:
        i = df_train.columns.get_loc(channel_name)
        xx = t[i].astype(float)

        print(f'Adding control: {channel_name}')
        c = coef.loc[coef['features']==channel_name, 'coef'].values[0]
        s = abs(c*0.015)
        if c <= 0:
            control_beta = HalfNormal(f'beta_{channel_name}', sd=s)
        else:
            control_beta = Normal(f'beta_{channel_name}', mu=c, sigma=s)

        channel_contrib = control_beta * xx
        response_mean.append(channel_contrib)

    # categorical control variables
    for var_name in index_vars:
        i = df_train.columns.get_loc(var_name)
        shape = len(np.unique(t[i]))
        x = t[i].astype('int')

        print(f'Adding Index Variable: {var_name}')

        ind_beta = Normal(f'beta_{var_name}', sd=6000, shape=shape)
        channel_contrib = ind_beta[x]
        response_mean.append(channel_contrib)

    # noise
    sigma = Exponential('sigma', 10)

    # define likelihood
    likelihood = Normal(outcome, mu=sum(response_mean), sd=sigma, observed=df[outcome].values)

    trace = pm.sample(tune=3000, cores=4, init='advi')
</code>```

Here's the beta's from the model. Notice that ADWORD_SEARCH is one of the most important features:

Betas

When I zeroed out ADWORD_SEARCH feature, I got practically identical prediction, which can not be the case:

```<code>with model:
    y_pred = sample_posterior_predictive(trace)

mod_channel = 'ADWORDS_SEARCH'
df_mod = df_train.copy(deep=True)
df_mod.iloc[12:-12, df_mod.columns.get_loc(mod_channel)] = 0

with model:
    pm.set_data({'features':df_mod})
    y_pred_mod = pm.sample_posterior_predictive(trace)
</code>```

Predictions Plot

By zeroeing out ADWORD_SEARCH, I would expect that the prediction would be significantly lower than the original prediction since ADWORD_SEARCH is one of the most important features according to the betas.

I started questioning the model, but it seems to perform well:

```<code>MAPE = 6.3%
r2 = 0.7
</code>```

I also tried passing in the original training data set to pm.setdata() and I got very similar results as well.

This is difference between prediction from training data and new data:
y1-y2

This is the difference between prediction from training data and the same training data using pm.setdata():
y1-y3

Anyone know what I'm doing wrong?

Body:
I built the Bayesian regression using PyMC3 package. I'm trying to generate prediction using new data. I used the data container pm.Data() to train the model with the training data, then passed the new data to pm.set_data() before calling pm.sample_posterior_predictive(). The prediction was what I would expect from the training data, not the new data.

Here's my model:

df_train = df.drop(['Unnamed: 0', 'DATE_AT'], axis=1)

with Model() as model:
    response_mean = []
    x_ = pm.Data('features', df_train) # a data container, can be changed
    t = np.transpose(x_.get_value())

    # intercept
    y = Normal('y', mu=0, sigma=6000)
    response_mean.append(y)

    # channels that can have DECAY and SATURATION effects
    for channel_name in delay_channels:
        i = df_train.columns.get_loc(channel_name)
        xx = t[i].astype(float)

        print(f'Adding Delayed Channels: {channel_name}')
        c = coef.loc[coef['features']==channel_name, 'coef'].values[0]
        s = abs(c*0.015)
        if c <= 0:
            channel_b = HalfNormal(f'beta_{channel_name}', sd=s)
        else:
            channel_b = Normal(f'beta_{channel_name}', mu=c, sigma=s)

        alpha = Beta(f'alpha_{channel_name}', alpha=3, beta=3)
        channel_mu = Gamma(f'mu_{channel_name}', alpha=3, beta=1)
        response_mean.append(logistic_function(
            geometric_adstock_tt(xx, alpha), channel_mu) * channel_b)

    # channels that have SATURATION effects only
    for channel_name in non_lin_channels:
        i = df_train.columns.get_loc(channel_name)
        xx = t[i].astype(float)

        print(f'Adding Non-Linear Logistic Channel: {channel_name}')
        c = coef.loc[coef['features']==channel_name, 'coef'].values[0]
        s = abs(c*0.015)
        if c <= 0:
            channel_b = HalfNormal(f'beta_{channel_name}', sd=s)
        else:
            channel_b = Normal(f'beta_{channel_name}', mu=c, sigma=s)

        # logistic reach curve
        channel_mu = Gamma(f'mu_{channel_name}', alpha=3, beta=1)
        response_mean.append(logistic_function(xx, channel_mu) * channel_b)

    # continuous external features
    for channel_name in control_vars:
        i = df_train.columns.get_loc(channel_name)
        xx = t[i].astype(float)

        print(f'Adding control: {channel_name}')
        c = coef.loc[coef['features']==channel_name, 'coef'].values[0]
        s = abs(c*0.015)
        if c <= 0:
            control_beta = HalfNormal(f'beta_{channel_name}', sd=s)
        else:
            control_beta = Normal(f'beta_{channel_name}', mu=c, sigma=s)

        channel_contrib = control_beta * xx
        response_mean.append(channel_contrib)

    # categorical control variables
    for var_name in index_vars:
        i = df_train.columns.get_loc(var_name)
        shape = len(np.unique(t[i]))
        x = t[i].astype('int')

        print(f'Adding Index Variable: {var_name}')

        ind_beta = Normal(f'beta_{var_name}', sd=6000, shape=shape)
        channel_contrib = ind_beta[x]
        response_mean.append(channel_contrib)

    # noise
    sigma = Exponential('sigma', 10)

    # define likelihood
    likelihood = Normal(outcome, mu=sum(response_mean), sd=sigma, observed=df[outcome].values)

    trace = pm.sample(tune=3000, cores=4, init='advi')

Here's the beta's from the model. Notice that ADWORD_SEARCH is one of the most important features:

Betas

When I zeroed out ADWORD_SEARCH feature, I got practically identical prediction, which can not be the case:

with model:
    y_pred = sample_posterior_predictive(trace)

mod_channel = 'ADWORDS_SEARCH'
df_mod = df_train.copy(deep=True)
df_mod.iloc[12:-12, df_mod.columns.get_loc(mod_channel)] = 0

with model:
    pm.set_data({'features':df_mod})
    y_pred_mod = pm.sample_posterior_predictive(trace)

Predictions Plot

By zeroeing out ADWORD_SEARCH, I would expect that the prediction would be significantly lower than the original prediction since ADWORD_SEARCH is one of the most important features according to the betas.

I started questioning the model, but it seems to perform well:

MAPE = 6.3%
r2 = 0.7

I also tried passing in the original training data set to pm.setdata() and I got very similar results as well.

This is difference between prediction from training data and new data:
y1-y2

This is the difference between prediction from training data and the same training data using pm.setdata():
y1-y3

Anyone know what I'm doing wrong?


问:
spark-streaming read from specific event hub partition
The azure event hub "my_event_hub" has a total of 5 partitions ("0", "1", "2", "3", "4")

The readstream should only read events from partitions "0" and "4"

event hub configuration as streaming source:-

```<code>val name = "my_event_hub"
val connectionString = "my_event_hub_connection_string"
val max_events = 50

val positions = Map(
  new NameAndPartition(name, 0) -> EventPosition.fromEndOfStream,
  new NameAndPartition(name, 4) -> EventPosition.fromEndOfStream
)

val eventHubsConf = EventHubsConf(connectionString)
                    .setStartingPositions(start)
                    .setMaxEventsPerTrigger(max_Events)
</code>```

official doc for structured-streaming-eventhubs-integation: https://github.com/Azure/azure-event-hubs-spark/blob/master/docs/structured-streaming-eventhubs-integration.md

Using the above configuration the streaming application reads from all 5 partitions of the event hub.
Can we read from specific partitions only?

For example read events only from 2 partitions "0" and "4" with the checkpoint and offsets pointed to the specific partitions.

Body:
The azure event hub "my_event_hub" has a total of 5 partitions ("0", "1", "2", "3", "4")

The readstream should only read events from partitions "0" and "4"

event hub configuration as streaming source:-

val name = "my_event_hub"
val connectionString = "my_event_hub_connection_string"
val max_events = 50

val positions = Map(
  new NameAndPartition(name, 0) -> EventPosition.fromEndOfStream,
  new NameAndPartition(name, 4) -> EventPosition.fromEndOfStream
)

val eventHubsConf = EventHubsConf(connectionString)
                    .setStartingPositions(start)
                    .setMaxEventsPerTrigger(max_Events)

official doc for structured-streaming-eventhubs-integation: https://github.com/Azure/azure-event-hubs-spark/blob/master/docs/structured-streaming-eventhubs-integration.md

Using the above configuration the streaming application reads from all 5 partitions of the event hub.
Can we read from specific partitions only?

For example read events only from 2 partitions "0" and "4" with the checkpoint and offsets pointed to the specific partitions.


问:
Game ending conditions need to be set, clear visual feedback and reset button
Invalid input is not handled as once the user has answered all the provided questions, no ending condition is present and the buttons no longer work.
Once all questions are answered, the game breaks and errors are shown in the console. At this point, a game ending condition should be set, once all questions have been answered the answer buttons should be disabled, and an option to restart/reset the quiz should be presented to the user.
Limited interactivity for the userApp is not fully responsive and could be enhanced using more custom code for JavaScript. There is no quiz ending condition, no option to reset the quiz
Game ending conditions need to be set, and functionality put in place to handle this. Clear visual feedback should be provided to the User, and the option to restart/reset the quiz provided to the User, once all questions have been answered.</p>
```<code>// Game questions

let locationKnow = [
  {
    name: "Dublin Airport",
    image: "assets/images/dub.jpg",
    location: [" Dublin Southside", "Dublin Centre", "Dublin Airport", "Dublin West"],
  },
  {
    name: "Glasnevin Cemetery",
    image: "assets/images/glasnevin.jpg",
    location: ["Kilmainham Gaol", "Glasnevin Cemetery", "Dublin Castle", "St. Patrick`s Cathedral"],
  },
  {
      name: "Kilmainham Gaol",
      image: "assets/images/gaol.jpg",
      location: ["Kilmainham Gaol", "Temple Bar", "Dublin Castle", "St. Patrick`s Cathedral"],
    },
  {
    name: "Guinness Storehouse",
    image: "assets/images/guinness.jpg",
    location: ["Dublin Castle", "Guinness Storehouse","Trinity College", "Temple Bar"],
  },
  {
      name: "Dublin Castle",
      image: "assets/images/castle.jpg",
      location: ["St. Patrick`s Cathedral", "Dublin Castle", "Temple Bar", "Kilmainham Gaol"],
  },
  {
      name: "Botanic Gardens",
      image: "assets/images/botanic.jpg",
      location: ["Kilmainham Gaol", "Temple Bar", "Botanic Gardens", "St. Patrick`s Cathedral"],
    },
  {
      name: "St. Patrick`s Cathedral",
      image: "assets/images/stpatrick.jpg",
      location: ["Guinness Storehouse", "Dublin Castle", "St. Patrick`s Cathedral" ,"Trinity College"],
  },
  {
      name: "Trinity College",
      image: "assets/images/trinity.jpg",
      location: ["Trinity College", "Temple Bar", "Guinness Storehouse", "Kilmainham Gaol"],
  },
  {
      name: "Jameson Distillery",
      image: "assets/images/jameson.jpg",
      location: ["Kilmainham Gaol", "Jameson Distillery", "Dublin Castle", "St. Patrick`s Cathedral"],
    },
  {
      name: "Temple Bar",
      image: "assets/images/tbar.jpg",
      location: ["Temple Bar", "Trinity College", "Kilmainham Gaol", "Guinness Storehouse"],
  },
];

// Function to give name to each button using names from locationKnow

function bookDublin(name) {
  let div = document.getElementById("div-location");
  div.innerHTML += `
    <button class="guess-option" onclick="clickIt('${name}')">
        ${name}
    </button>`;
}

let indice = Math.floor(Math.random()* locationKnow.length);
let road = 0;

  function whichImg() {
    let city = locationKnow[indice];
    let image = document.getElementById("dublin-image-center");
    image.setAttribute('src', city.image);

    // adding console.log to print all the source code from the console for images
    console.log(image.getAttribute("src"));

    let divLocation = document.getElementById("div-location");
    divLocation.innerHTML = "";
  //buttons name
    city.location.forEach((option) => {
        bookDublin(option);
    });

  }

  whichImg();

    // Function for change the color after good/wrong answers

    let gameArea = document.getElementById("check-dublin");

    function correct(){
        gameArea.style.backgroundColor = "rgba(96, 255, 199, 1)";
        alert("That's RIGHT!");
      }

    function wrong(){
        gameArea.style.backgroundColor = "rgba(255, 166, 164, 1)";
        alert("That's WRONG!");
      }

      // Function for increment good/wrong answer after you click it

      function addGood() {

        let yourScor = parseInt(document.getElementById("marked").innerText);
        document.getElementById("marked").innerText = ++yourScor;

    }

    function addWrong() {

        let yourScor = parseInt(document.getElementById("un-marked").innerText);
        document.getElementById("un-marked").innerText = ++yourScor;

    }

    // Function to call each function and validate each option from buttons

    function clickIt(option) {
      let city = locationKnow[indice];
      let goodAnswer = city.name === option;
      if (goodAnswer) {
          indice++;
          road++;
          correct();
          addGood();
          whichImg();
      } else {
          wrong();
          addWrong();
      }
    }
</code>```

Body:
Invalid input is not handled as once the user has answered all the provided questions, no ending condition is present and the buttons no longer work.
Once all questions are answered, the game breaks and errors are shown in the console. At this point, a game ending condition should be set, once all questions have been answered the answer buttons should be disabled, and an option to restart/reset the quiz should be presented to the user.
Limited interactivity for the userApp is not fully responsive and could be enhanced using more custom code for JavaScript. There is no quiz ending condition, no option to reset the quiz
Game ending conditions need to be set, and functionality put in place to handle this. Clear visual feedback should be provided to the User, and the option to restart/reset the quiz provided to the User, once all questions have been answered.

// Game questions

let locationKnow = [
  {
    name: "Dublin Airport",
    image: "assets/images/dub.jpg",
    location: [" Dublin Southside", "Dublin Centre", "Dublin Airport", "Dublin West"],
  },
  {
    name: "Glasnevin Cemetery",
    image: "assets/images/glasnevin.jpg",
    location: ["Kilmainham Gaol", "Glasnevin Cemetery", "Dublin Castle", "St. Patrick`s Cathedral"],
  },
  {
      name: "Kilmainham Gaol",
      image: "assets/images/gaol.jpg",
      location: ["Kilmainham Gaol", "Temple Bar", "Dublin Castle", "St. Patrick`s Cathedral"],
    },
  {
    name: "Guinness Storehouse",
    image: "assets/images/guinness.jpg",
    location: ["Dublin Castle", "Guinness Storehouse","Trinity College", "Temple Bar"],
  },
  {
      name: "Dublin Castle",
      image: "assets/images/castle.jpg",
      location: ["St. Patrick`s Cathedral", "Dublin Castle", "Temple Bar", "Kilmainham Gaol"],
  },
  {
      name: "Botanic Gardens",
      image: "assets/images/botanic.jpg",
      location: ["Kilmainham Gaol", "Temple Bar", "Botanic Gardens", "St. Patrick`s Cathedral"],
    },
  {
      name: "St. Patrick`s Cathedral",
      image: "assets/images/stpatrick.jpg",
      location: ["Guinness Storehouse", "Dublin Castle", "St. Patrick`s Cathedral" ,"Trinity College"],
  },
  {
      name: "Trinity College",
      image: "assets/images/trinity.jpg",
      location: ["Trinity College", "Temple Bar", "Guinness Storehouse", "Kilmainham Gaol"],
  },
  {
      name: "Jameson Distillery",
      image: "assets/images/jameson.jpg",
      location: ["Kilmainham Gaol", "Jameson Distillery", "Dublin Castle", "St. Patrick`s Cathedral"],
    },
  {
      name: "Temple Bar",
      image: "assets/images/tbar.jpg",
      location: ["Temple Bar", "Trinity College", "Kilmainham Gaol", "Guinness Storehouse"],
  },
];

// Function to give name to each button using names from locationKnow

function bookDublin(name) {
  let div = document.getElementById("div-location");
  div.innerHTML += `
    <button class="guess-option" onclick="clickIt('${name}')">
        ${name}
    </button>`;
}

let indice = Math.floor(Math.random()* locationKnow.length);
let road = 0;

  function whichImg() {
    let city = locationKnow[indice];
    let image = document.getElementById("dublin-image-center");
    image.setAttribute('src', city.image);

    // adding console.log to print all the source code from the console for images
    console.log(image.getAttribute("src"));

    let divLocation = document.getElementById("div-location");
    divLocation.innerHTML = "";
  //buttons name
    city.location.forEach((option) => {
        bookDublin(option);
    });

  }

  whichImg();

    // Function for change the color after good/wrong answers

    let gameArea = document.getElementById("check-dublin");

    function correct(){
        gameArea.style.backgroundColor = "rgba(96, 255, 199, 1)";
        alert("That's RIGHT!");
      }

    function wrong(){
        gameArea.style.backgroundColor = "rgba(255, 166, 164, 1)";
        alert("That's WRONG!");
      }

      // Function for increment good/wrong answer after you click it

      function addGood() {

        let yourScor = parseInt(document.getElementById("marked").innerText);
        document.getElementById("marked").innerText = ++yourScor;

    }

    function addWrong() {

        let yourScor = parseInt(document.getElementById("un-marked").innerText);
        document.getElementById("un-marked").innerText = ++yourScor;

    }

    // Function to call each function and validate each option from buttons

    function clickIt(option) {
      let city = locationKnow[indice];
      let goodAnswer = city.name === option;
      if (goodAnswer) {
          indice++;
          road++;
          correct();
          addGood();
          whichImg();
      } else {
          wrong();
          addWrong();
      }
    }


问:
Make div with react components as children disappear if I click outside of it
I want to make a form that disappears if I click outside of it.

Form Component:

```<code>const CreateTaskPopup = (props) => {

  const ref = query(collection(db, "tasks"));
  const mutation = useFirestoreCollectionMutation(ref);

  useEffect(() => {
    const closeTaskPopup = (event) => {
      if (event.target.id != "addForm") {
        props.setTrigger(false)
      }
    }
    document.addEventListener('click', closeTaskPopup);

    return () => document.removeEventListener('click', closeTaskPopup)
  }, [])

  return (props.trigger) ? (
      <>
        <div className="bg-darkishGrey my-4 p-1 mx-3 ml-16 cursor-pointer block"
        id="addForm">
          <div className="flex justify-between">
            <div className="flex break-all items-center ">
              <Image src={fileIcon} className="w-6 mx-2"/>
              <div>
              <Formik
                initialValues={{
                  taskName: "",
                  taskIsDone: false,
                  parentId: props.parentId ? props.parentId : "",
                  hasChildren: false,
                }}
                onSubmit={(values) => {
                  mutation.mutate(values);
                  props.setTrigger(false);
                }}
              >
                <Form>
                  <div className="">
                    <TextInput
                      placeholder="Type a name"
                      name="taskName"
                      type="text"
                    />
                  </div>
                </Form>
                </Formik>
              </div>
            </div>
            <div className="flex items-center">
            </div>
          </div>
        </div>
      </>
  ) : null
}

export default CreateTaskPopup
</code>```

Text Input Component:

```<code>import { useField } from "formik";

const TextInput = ({ label, ...props}) => {
  const [field, meta] = useField(props);
  return (
    <div>
      <label id="addForm" className="text-lightestGrey text-xl block"
      htmlFor={props.id || props.name}>
        {label}
      </label>
      <input id="addForm" className="bg-darkishGrey text-xl text-almostWhite my-2
      outline-none w-10/12 rounded-sm p-1 mx-3" {...field} {...props} />
      {meta.touched && meta.error ? <div>{meta.error}</div>: null}
    </div>
  );
};

export default TextInput;

</code>```

I tried giving an id to the elements inside it but it's not the best solution as it has components from the Formik library to which I can't assign an id. I don't know what would be the best solution for this problem.

Body:
I want to make a form that disappears if I click outside of it.

Form Component:

const CreateTaskPopup = (props) => {

  const ref = query(collection(db, "tasks"));
  const mutation = useFirestoreCollectionMutation(ref);

  useEffect(() => {
    const closeTaskPopup = (event) => {
      if (event.target.id != "addForm") {
        props.setTrigger(false)
      }
    }
    document.addEventListener('click', closeTaskPopup);

    return () => document.removeEventListener('click', closeTaskPopup)
  }, [])

  return (props.trigger) ? (
      <>

              <Image src={fileIcon} className="w-6 mx-2"/>

              <Formik
                initialValues={{
                  taskName: "",
                  taskIsDone: false,
                  parentId: props.parentId ? props.parentId : "",
                  hasChildren: false,
                }}
                onSubmit={(values) => {
                  mutation.mutate(values);
                  props.setTrigger(false);
                }}
              >
                <Form>

                    <TextInput
                      placeholder="Type a name"
                      name="taskName"
                      type="text"
                    />

                </Form>
                </Formik>

      </>
  ) : null
}

export default CreateTaskPopup

Text Input Component:

import { useField } from "formik";

const TextInput = ({ label, ...props}) => {
  const [field, meta] = useField(props);
  return (

        {label}

      <input id="addForm" className="bg-darkishGrey text-xl text-almostWhite my-2
      outline-none w-10/12 rounded-sm p-1 mx-3" {...field} {...props} />
      {meta.touched && meta.error ?
{meta.error}
: null}

  );
};

export default TextInput;

I tried giving an id to the elements inside it but it's not the best solution as it has components from the Formik library to which I can't assign an id. I don't know what would be the best solution for this problem.


问:
How do I get my javascript file to pull from a folder in project?
Here is the code that was copied from a repository and all I did was change the path to point to a folder in my project to play that specific .mp3 file rather than one from freemusicarchive.org.

the one i copied plays in the web browser fine but mine shows the image and title change but no audio plays?

let track_list = [
  {
    name: "Jingle Bell Rock",
    artist: "Bobby Helms",
    image: "https://upload.wikimedia.org/wikipedia/en/0/0e/Single_Bobby_Helms-Jingle_Bell_Rock_cover.jpg",
    path: Assets/music/tomp-3.cc-ill-be-home-for-christmas"
  },
```
<p>the original code that i copied was this...</p>
<pre class="lang-js prettyprint-override"><code>let track_list = [
{
    name: "Enthusiast",
    artist: "Tours",
    image: "https://images.pexels.com/photos/3100835/pexels-photo-3100835.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=250&w=250",
    path: "https://files.freemusicarchive.org/storage-freemusicarchive-org/music/no_curator/Tours/Enthusiast/Tours_-_01_-_Enthusiast.mp3"
  },

</code>```

the one i copied plays in the web browser fine but mine shows the image and title change but no audio plays?

Body:
Here is the code that was copied from a repository and all I did was change the path to point to a folder in my project to play that specific .mp3 file rather than one from freemusicarchive.org.

the one i copied plays in the web browser fine but mine shows the image and title change but no audio plays?

let track_list = [
  {
    name: "Jingle Bell Rock",
    artist: "Bobby Helms",
    image: "https://upload.wikimedia.org/wikipedia/en/0/0e/Single_Bobby_Helms-Jingle_Bell_Rock_cover.jpg",
    path: Assets/music/tomp-3.cc-ill-be-home-for-christmas"
  },

the original code that i copied was this...

let track_list = [
{
    name: "Enthusiast",
    artist: "Tours",
    image: "https://images.pexels.com/photos/3100835/pexels-photo-3100835.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=250&w=250",
    path: "https://files.freemusicarchive.org/storage-freemusicarchive-org/music/no_curator/Tours/Enthusiast/Tours_-_01_-_Enthusiast.mp3"
  },

the one i copied plays in the web browser fine but mine shows the image and title change but no audio plays?


问:
Google Console Cloud Create credentials OAuth Cliend ID has error

There was an error while loading /apis/credentials/oauthclient?previousPage=%2Fapis%2Fcredentials%3Fproject%3Dmidbooks-8800&project=midbooks-8800. Please try again.

Tracking Number: c7520181810687758

show error when create credentials OAuth cliend id

add some libraries like google+ api and add some scopes but didn't solve


问:
use a big number in a function
i would like to have some kind of pseudo-code or show me the right way to work with a big number in C. i got for homework to decompose numbers to prime numbers so i already have a function for it, but at the last test it fails because i cant store this number in the biggest data type that i know of (unsigned long long). and i can use just standard libraries like <stdio,math,stdlib,string>

a example of the lenght of the number that i have to work with:

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

i have come up with an idea to allocate a memory section and initialize each number of the big number to a heap memory. the problem then is that i dont know how to continue or even if its the right way of doing so.

Title: use a big number in a function

Body:
i would like to have some kind of pseudo-code or show me the right way to work with a big number in C. i got for homework to decompose numbers to prime numbers so i already have a function for it, but at the last test it fails because i cant store this number in the biggest data type that i know of (unsigned long long). and i can use just standard libraries like <stdio,math,stdlib,string>

a example of the lenght of the number that i have to work with:

932865073719992059629773513614789388266580305083920591925740371392254317064584855785088915745763

i have come up with an idea to allocate a memory section and initialize each number of the big number to a heap memory. the problem then is that i dont know how to continue or even if its the right way of doing so.


问:
ASP.NET MVC FilePathResult not using utf-8
I am working on an old ASP.NET MVC project and I am trying to use FilePathResult in an ActionResult to load an HTML file within a .cshtml page using HTML.Action.

The issue is that utf-8 characters including em dashes and quotation marks (— “ ”) are garbled on the resulting page (showing up as ANSI encoded characters â€” â€œ â€). I am using the answer detailed here to try to force utf-8 encoding, and I have utf-8 set in my site metadata. Unfortunately the messed-up characters persist. I can however use utf-8 characters directly within my .cshtml file and they render correctly on the site, just not when returned by my controller.

Here is the controller code:

```<code>    [ChildActionOnly]
    public ActionResult GetHtmlPage(string path)
    {
        //return new FilePathResult(path, "text/html");
        string contentType = "text/html";
        Response.Charset = "utf-8"; // or other encoding
        Response.ContentEncoding = Encoding.UTF8;
        var fileResult = new FilePathResult(path, contentType);

        return fileResult;
    }
</code>```

Body:
I am working on an old ASP.NET MVC project and I am trying to use FilePathResult in an ActionResult to load an HTML file within a .cshtml page using HTML.Action.

The issue is that utf-8 characters including em dashes and quotation marks (— “ ”) are garbled on the resulting page (showing up as ANSI encoded characters â€” â€œ â€). I am using the answer detailed here to try to force utf-8 encoding, and I have utf-8 set in my site metadata. Unfortunately the messed-up characters persist. I can however use utf-8 characters directly within my .cshtml file and they render correctly on the site, just not when returned by my controller.

Here is the controller code:

    [ChildActionOnly]
    public ActionResult GetHtmlPage(string path)
    {
        //return new FilePathResult(path, "text/html");
        string contentType = "text/html";
        Response.Charset = "utf-8"; // or other encoding
        Response.ContentEncoding = Encoding.UTF8;
        var fileResult = new FilePathResult(path, contentType);

        return fileResult;
    }


问:
JS accordion area-expanded One section at a time
I'm using this example for the accordion and trying to play with it to have just One Section Open at a time
I know how to create this using iQuery, but here I'm puzzled. Should I also do something like forEach or !this or to specify current?</p>
```<code>class Accordion {
  constructor(domNode) {
    this.rootEl = domNode;
    this.buttonEl = this.rootEl.querySelector('button[aria-expanded]');

    const controlsId = this.buttonEl.getAttribute('aria-controls');
    this.contentEl = document.getElementById(controlsId);

    this.open = this.buttonEl.getAttribute('aria-expanded') === 'true';

    // add event listeners
    this.buttonEl.addEventListener('click', this.onButtonClick.bind(this));
  }

  onButtonClick() {
    this.toggle(!this.open);
  }

  toggle(open) {
    // don't do anything if the open state doesn't change
    if (open === this.open) {
      return;
    }

    // update the internal state
    this.open = open;

    // handle DOM updates
    this.buttonEl.setAttribute('aria-expanded', `${open}`);

    if (open) {
      this.contentEl.removeAttribute('hidden');
    } else {
      this.contentEl.setAttribute('hidden', '');
    }
  }

  // Add public open and close methods for convenience
  open() {
    this.toggle(true);
  }

  close() {
    this.toggle(false);
  }
}

// init accordions
const accordions = document.querySelectorAll('.accordion h3');
accordions.forEach((accordionEl) => {
  new Accordion(accordionEl);
});
</code>```

Body:
I'm using this example for the accordion and trying to play with it to have just One Section Open at a time
I know how to create this using iQuery, but here I'm puzzled. Should I also do something like forEach or !this or to specify current?

class Accordion {
  constructor(domNode) {
    this.rootEl = domNode;
    this.buttonEl = this.rootEl.querySelector('button[aria-expanded]');

    const controlsId = this.buttonEl.getAttribute('aria-controls');
    this.contentEl = document.getElementById(controlsId);

    this.open = this.buttonEl.getAttribute('aria-expanded') === 'true';

    // add event listeners
    this.buttonEl.addEventListener('click', this.onButtonClick.bind(this));
  }

  onButtonClick() {
    this.toggle(!this.open);
  }

  toggle(open) {
    // don't do anything if the open state doesn't change
    if (open === this.open) {
      return;
    }

    // update the internal state
    this.open = open;

    // handle DOM updates
    this.buttonEl.setAttribute('aria-expanded', `${open}`);

    if (open) {
      this.contentEl.removeAttribute('hidden');
    } else {
      this.contentEl.setAttribute('hidden', '');
    }
  }

  // Add public open and close methods for convenience
  open() {
    this.toggle(true);
  }

  close() {
    this.toggle(false);
  }
}

// init accordions
const accordions = document.querySelectorAll('.accordion h3');
accordions.forEach((accordionEl) => {
  new Accordion(accordionEl);
});


问:
Swiper.JS combined with PhotoSwipe in React JS
There are people who made it, but not in react...

```<code>var swiper = new Swiper(".mySwiper", {
  slidesPerView: 1,
  spaceBetween: 10,
  centeredSlides: true,
  grabCursor: true,
  effect: "creative",
  creativeEffect: {
    prev: {
      shadow: true,
      translate: ["-30%", 0, -1],
    }, TO BE CONTINUED...

  >> The actual code is huge, but this is only for the codepen link
</code>```

CodePen

The confusing part is how do I combine the elements of these react libraries if they come with just ready-to-use components. There is not that much flexibility as there is in pure HTML.

Please show me the way to the right direction

Body:
There are people who made it, but not in react...

var swiper = new Swiper(".mySwiper", {
  slidesPerView: 1,
  spaceBetween: 10,
  centeredSlides: true,
  grabCursor: true,
  effect: "creative",
  creativeEffect: {
    prev: {
      shadow: true,
      translate: ["-30%", 0, -1],
    }, TO BE CONTINUED...

  >> The actual code is huge, but this is only for the codepen link

CodePen

The confusing part is how do I combine the elements of these react libraries if they come with just ready-to-use components. There is not that much flexibility as there is in pure HTML.

Please show me the way to the right direction


问:
Transpose table on the basis of category
I am working on angular app. I am using material table. I am doing transpose of table.  My code is as follows.

HTML:

```<code><table mat-table [dataSource]="displayData" class="mat-elevation-z8" *ngIf="showTable">

  <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

  <!-- Position Column -->
  <ng-container [matColumnDef]="column" *ngFor="let column of displayColumns">
    <th mat-header-cell *matHeaderCellDef> {{ column }} </th>
    <td mat-cell *matCellDef="let element"> {{ element[column] }} </td>
  </ng-container>

  <tr mat-row *matRowDef="let row; columns: displayColumns;"></tr>
</table>
</code>```

Data which will be populated in table is as follows:

```<code>const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Hydrogen', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Hydrogen', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Hydrogen', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Boron', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Boron', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Boron', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];
</code>```

Stackblitz:

https://stackblitz.com/edit/angular-h6dvzc-w4z9za?file=app%2Ftable-basic-example.ts,app%2Ftable-basic-example.html

In this code, in my data for few elements name is common which is 'Hydrogen', for some 'Boron' and some different names as well etc. I want to categorize this transpose table on the basis of "name" property as show below

For example -  as shown in attached image for hydrogen, I want to show all elements in transposed form and similarly for other elements. How can I do that?

Body:
I am working on angular app. I am using material table. I am doing transpose of table.  My code is as follows.

HTML:

  <ng-container [matColumnDef]="column" *ngFor="let column of displayColumns">
     {{ column }}
     {{ element[column] }}
  </ng-container>

Data which will be populated in table is as follows:

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Hydrogen', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Hydrogen', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Hydrogen', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Boron', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Boron', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Boron', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

Stackblitz:

https://stackblitz.com/edit/angular-h6dvzc-w4z9za?file=app%2Ftable-basic-example.ts,app%2Ftable-basic-example.html

In this code, in my data for few elements name is common which is 'Hydrogen', for some 'Boron' and some different names as well etc. I want to categorize this transpose table on the basis of "name" property as show below

For example -  as shown in attached image for hydrogen, I want to show all elements in transposed form and similarly for other elements. How can I do that?


问:
Javascript Neural Network Weight List Undefined
I have written a tiny Neural Network in JavaScript and moving from C# irritates me a ton since JavaScript is in my opinion way buggier. I fixed the original error which was happening but now I can't even back propagate since the weights and biases go to NaN after the process!

Why does my BackPropagation Function cause weights to go NaN

```<code>class NeuralNet {
// const for learningRate
static LEARNING_RATE = 0.33;
// define float[][] for biases
biases;
// define float[][] for values
values;
// define float[][] for errors
errors;
// define float[][][] for weights
weights;

// constructor
constructor(inputSize, hiddenSize, outputSize) {
    // set biases
    this.biases = [
        // hidden layer
        new Array(hiddenSize).fill(0).map(NeuralNet.random),
        // output layer
        new Array(outputSize).fill(0).map(NeuralNet.random)
    ];
    // set values
    this.values = [
        // input layer
        new Array(inputSize).fill(0),
        // hidden layer
        new Array(hiddenSize).fill(0),
        // output layer
        new Array(outputSize).fill(0)
    ];
    // set errors
    this.errors = [
        // hidden layer
        new Array(hiddenSize).fill(0).map(() => new Array(inputSize).fill(0)),
        // output layer
        new Array(outputSize).fill(0).map(() => new Array(hiddenSize).fill(0))
    ];
    // set weights
    this.weights = [
        // hidden layer
        new Array(hiddenSize).fill(0).map(() => new Array(inputSize).fill(0).map(NeuralNet.random)),
        // output layer
        new Array(outputSize).fill(0).map(() => new Array(hiddenSize).fill(0).map(NeuralNet.random))
    ];
}

// define a random
static random() {
    // return random number between -1 and 1
    return Math.random() * 2 - 1;
}

// tanh function
static tanh(x) {
    // return tanh of x
    return Math.tanh(x);
}

// tanh activation function
feedForward() {
    // for each layer
    for (var i = 1; i < this.values.length; i++) {
        // for each neuron
        for (var j = 0; j < this.values[i].length; j++) {
            // set value to bias
            this.values[i][j] = this.biases[i - 1][j];
            // for each weight
            for (var k = 0; k < this.weights[i - 1].length; k++) {
                // add weight * value
                this.values[i][j] += this.weights[i - 1][k][j] * this.values[i][k];
            }
            // apply tanh
            this.values[i][j] = NeuralNet.tanh(this.values[i][j]);
        }
    }
}

// get output of neural net
getOutput(inpts) {
    // set input
    this.setInput(inpts);
    // feed forward
    this.feedForward();
    // return the output
    return this.values[this.values.length - 1];
}

// backpropagation that doesn't make all values NaN
backpropagation(expected) {
    // for each layer
    for (var i = this.values.length - 1; i > 0; i--) {
        // for each neuron
        for (var j = 0; j < this.values[i].length; j++) {
            // if output layer
            if (i == this.values.length - 1) {
                // set error
                this.errors[i - 1][j] = (expected[j] - this.values[i][j]) * (1 - this.values[i][j] * this.values[i][j]);
            } else {
                // set error
                this.errors[i - 1][j] = 0;
                // for each weight
                for (var k = 0; k < this.weights[i].length; k++) {
                    // add weight * error
                    this.errors[i - 1][j] += this.weights[i][k][j] * this.errors[i][k];
                }
                // multiply error with tanh
                this.errors[i - 1][j] *= (1 - this.values[i][j] * this.values[i][j]);
            }
            // for each weight
            for (var k = 0; k < this.weights[i - 1].length; k++) {
                // add error * value * learning rate
                this.weights[i - 1][k][j] += this.errors[i - 1][j] * this.values[i - 1][k] * NeuralNet.LEARNING_RATE;
            }
            // add error * learning rate
            this.biases[i - 1][j] += this.errors[i - 1][j] * NeuralNet.LEARNING_RATE;
        }
    }
}
</code>```

Init --> var neuralNet = new NeuralNet(10, 10, 1);

Body:
I have written a tiny Neural Network in JavaScript and moving from C# irritates me a ton since JavaScript is in my opinion way buggier. I fixed the original error which was happening but now I can't even back propagate since the weights and biases go to NaN after the process!

Why does my BackPropagation Function cause weights to go NaN

class NeuralNet {
// const for learningRate
static LEARNING_RATE = 0.33;
// define float[][] for biases
biases;
// define float[][] for values
values;
// define float[][] for errors
errors;
// define float[][][] for weights
weights;

// constructor
constructor(inputSize, hiddenSize, outputSize) {
    // set biases
    this.biases = [
        // hidden layer
        new Array(hiddenSize).fill(0).map(NeuralNet.random),
        // output layer
        new Array(outputSize).fill(0).map(NeuralNet.random)
    ];
    // set values
    this.values = [
        // input layer
        new Array(inputSize).fill(0),
        // hidden layer
        new Array(hiddenSize).fill(0),
        // output layer
        new Array(outputSize).fill(0)
    ];
    // set errors
    this.errors = [
        // hidden layer
        new Array(hiddenSize).fill(0).map(() => new Array(inputSize).fill(0)),
        // output layer
        new Array(outputSize).fill(0).map(() => new Array(hiddenSize).fill(0))
    ];
    // set weights
    this.weights = [
        // hidden layer
        new Array(hiddenSize).fill(0).map(() => new Array(inputSize).fill(0).map(NeuralNet.random)),
        // output layer
        new Array(outputSize).fill(0).map(() => new Array(hiddenSize).fill(0).map(NeuralNet.random))
    ];
}

// define a random
static random() {
    // return random number between -1 and 1
    return Math.random() * 2 - 1;
}

// tanh function
static tanh(x) {
    // return tanh of x
    return Math.tanh(x);
}

// tanh activation function
feedForward() {
    // for each layer
    for (var i = 1; i < this.values.length; i++) {
        // for each neuron
        for (var j = 0; j < this.values[i].length; j++) {
            // set value to bias
            this.values[i][j] = this.biases[i - 1][j];
            // for each weight
            for (var k = 0; k < this.weights[i - 1].length; k++) {
                // add weight * value
                this.values[i][j] += this.weights[i - 1][k][j] * this.values[i][k];
            }
            // apply tanh
            this.values[i][j] = NeuralNet.tanh(this.values[i][j]);
        }
    }
}

// get output of neural net
getOutput(inpts) {
    // set input
    this.setInput(inpts);
    // feed forward
    this.feedForward();
    // return the output
    return this.values[this.values.length - 1];
}

// backpropagation that doesn't make all values NaN
backpropagation(expected) {
    // for each layer
    for (var i = this.values.length - 1; i > 0; i--) {
        // for each neuron
        for (var j = 0; j < this.values[i].length; j++) {
            // if output layer
            if (i == this.values.length - 1) {
                // set error
                this.errors[i - 1][j] = (expected[j] - this.values[i][j]) * (1 - this.values[i][j] * this.values[i][j]);
            } else {
                // set error
                this.errors[i - 1][j] = 0;
                // for each weight
                for (var k = 0; k < this.weights[i].length; k++) {
                    // add weight * error
                    this.errors[i - 1][j] += this.weights[i][k][j] * this.errors[i][k];
                }
                // multiply error with tanh
                this.errors[i - 1][j] *= (1 - this.values[i][j] * this.values[i][j]);
            }
            // for each weight
            for (var k = 0; k < this.weights[i - 1].length; k++) {
                // add error * value * learning rate
                this.weights[i - 1][k][j] += this.errors[i - 1][j] * this.values[i - 1][k] * NeuralNet.LEARNING_RATE;
            }
            // add error * learning rate
            this.biases[i - 1][j] += this.errors[i - 1][j] * NeuralNet.LEARNING_RATE;
        }
    }
}

Init --> var neuralNet = new NeuralNet(10, 10, 1);


问:
How to ignore RAISERROR in Sybase ASE-15 T-SQL?
I have a loop which executes a proc.
That proc can throw RAISERROR which, of course, stops the loop and the whole program.
Is there any way to ignore that error and continue the loop?
In normal languages I can CATCH the error, but what is possible in Sybase T-SQL?

I found EXCEPTION section (similar to Oracle) and CONTINUE_AFTER_RAISERROR, but they are in Sybase IQ, not in ASE.

Any idea?


问:
eclipse how to set run configuration default for a specific project
have several java servlet projects. Each one uses a different configuration file. The servlet use and environment variable to find the config file. I have several different run time configurations. One for each project.

Is there a way to set the default run time configuration for each project. I loose a lot of time because I try to debug and accidentally select the wrong profile

Kind regards

Andy


问:
Access mysql using colab
IMAGE OF MY ERROR
I am trying to link mysql with google colab, but I am not able to find the right host name. Can I get the proper host name and even right user and password.It would even helpful if you say how to link mysql with colab.

I tried changing the host to url link, but I wasn't able to do it and I learnt that it becomes less secure. I am expecting this error to be resolved to complete my project. This program worked in PYTHON IDLE but in colab I can't find the right way to run the code.

ERROR DISPLAYED-> MySQLInterfaceError: Can't connect to MySQL server on 'localhost:3306' (99)

Title: Access mysql using colab


问:
DynamoDBAutoGeneratedTimestamp CREATE strategy is always updating?
I am trying to use the DynamoDBAutoGeneratedTimestamp annotation for generating timestamps for when my records are last updated and when they are created. The annotation currently has 2 strategies, ALWAYS and CREATE.

My initial understanding was that the ALWAYS strategy should update the timestamp every time the record is changed, and the CREATE strategy should set the timestamp only when the record is created. The ALWAYS strategy appears to be working just fine in updating the timestamp each time the record changes; however, the CREATE strategy appears to be behaving exactly the same as the ALWAYS strategy (meaning the timestamp updates each time the record changes).

It is now my understanding that the CREATE strategy doesn't do that, and instead tells the record to generate a timestamp if you're going to write it to the database and the value of the field in the record to be written is null.

This causes the field with the CREATE strategy to always be updated if the record itself is ever updated.

So, are there any easy solutions to this? I could set it myself, of course, but I was wondering if there is some sort of option or config that is not known to me that would address this issue?

Example code:

```<code>@DynamoDBTable(tableName = "Foo")
public class Foo {
    @DynamoDBAutoGeneratedTimestamp(strategy = DynamoDBAutoGenerateStrategy.CREATE)
    private Date createdAt;

    @DynamoDBAutoGeneratedTimestamp(strategy = DynamoDBAutoGenerateStrategy.ALWAYS)
    private Date updatedAt;
}
</code>```

Body:
I am trying to use the DynamoDBAutoGeneratedTimestamp annotation for generating timestamps for when my records are last updated and when they are created. The annotation currently has 2 strategies, ALWAYS and CREATE.

My initial understanding was that the ALWAYS strategy should update the timestamp every time the record is changed, and the CREATE strategy should set the timestamp only when the record is created. The ALWAYS strategy appears to be working just fine in updating the timestamp each time the record changes; however, the CREATE strategy appears to be behaving exactly the same as the ALWAYS strategy (meaning the timestamp updates each time the record changes).

It is now my understanding that the CREATE strategy doesn't do that, and instead tells the record to generate a timestamp if you're going to write it to the database and the value of the field in the record to be written is null.

This causes the field with the CREATE strategy to always be updated if the record itself is ever updated.

So, are there any easy solutions to this? I could set it myself, of course, but I was wondering if there is some sort of option or config that is not known to me that would address this issue?

Example code:

@DynamoDBTable(tableName = "Foo")
public class Foo {
    @DynamoDBAutoGeneratedTimestamp(strategy = DynamoDBAutoGenerateStrategy.CREATE)
    private Date createdAt;

    @DynamoDBAutoGeneratedTimestamp(strategy = DynamoDBAutoGenerateStrategy.ALWAYS)
    private Date updatedAt;
}


问:
OSC Send from NodeJS App deployed in Heroku
My NodeJS app is running in Heroku and uses OSC and WebSockets to communicate OSC messages from app clients to OSC clients in a local network successfully, either internally with 127.0.0.1 or 192.168.xx.xx on another endpoint in the same network. Now, I have deployed it in Heroku but I am not receiving anything, but I can see Sockets working just fine every time a new client is connected. I probably have to tweak my server in order to be able to receive and send OSC from the Heroku clients to my machine running, for example, SuperCollider, that is, one osc client.

Here is my express server.js file configuration running on NodeJS.

```<code>{
    "clientAddress": "0.0.0.0", //Apps address
    "clientPort": 57121, //Apps port
    "appAddress": "127.0.0.1", //OSC client's address on same machine.
    "appPort": 57120 // OSC client listening port
}

</code>```

My apps index.js OSC configuration below:

```<code>osc_config = {
  address: '127.0.0.1',
  port: 8081 //binds on the WS port
};

var oscPort = new osc.WebSocketPort({
  url: ("ws://" + osc_config.address + ":" + osc_config.port)
});
</code>```

Body:
My NodeJS app is running in Heroku and uses OSC and WebSockets to communicate OSC messages from app clients to OSC clients in a local network successfully, either internally with 127.0.0.1 or 192.168.xx.xx on another endpoint in the same network. Now, I have deployed it in Heroku but I am not receiving anything, but I can see Sockets working just fine every time a new client is connected. I probably have to tweak my server in order to be able to receive and send OSC from the Heroku clients to my machine running, for example, SuperCollider, that is, one osc client.

Here is my express server.js file configuration running on NodeJS.

{
    "clientAddress": "0.0.0.0", //Apps address
    "clientPort": 57121, //Apps port
    "appAddress": "127.0.0.1", //OSC client's address on same machine.
    "appPort": 57120 // OSC client listening port
}

My apps index.js OSC configuration below:

osc_config = {
  address: '127.0.0.1',
  port: 8081 //binds on the WS port
};

var oscPort = new osc.WebSocketPort({
  url: ("ws://" + osc_config.address + ":" + osc_config.port)
});


问:
error uploading API REST + BD (express - sequelize - postgress) in railway
I use express and sequelize ORM to connect to a Postgres database on my laptop.
In the deploy logs figures this. I was using Heroku, I'm new to railway</p>
```<code>ConnectionError [SequelizeConnectionError]: connect ETIMEDOUT 35.197.113.116:5432
at Client._connectionCallback (/app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:143:24)
at Client._handleErrorWhileConnecting (/app/node_modules/pg/lib/client.js:305:19)
at Client._handleErrorEvent (/app/node_modules/pg/lib/client.js:315:19)
at Connection.emit (node:events:513:28)
at Socket.reportStreamError (/app/node_modules/pg/lib/connection.js:52:12)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
parent: Error: connect ETIMEDOUT 35.197.113.116:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -110,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.197.113.116',
port: 5432
},
original: Error: connect ETIMEDOUT 35.197.113.116:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -110,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.197.113.116',
port: 5432
}
}
</code>```

Body:
I use express and sequelize ORM to connect to a Postgres database on my laptop.
In the deploy logs figures this. I was using Heroku, I'm new to railway

ConnectionError [SequelizeConnectionError]: connect ETIMEDOUT 35.197.113.116:5432
at Client._connectionCallback (/app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:143:24)
at Client._handleErrorWhileConnecting (/app/node_modules/pg/lib/client.js:305:19)
at Client._handleErrorEvent (/app/node_modules/pg/lib/client.js:315:19)
at Connection.emit (node:events:513:28)
at Socket.reportStreamError (/app/node_modules/pg/lib/connection.js:52:12)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
parent: Error: connect ETIMEDOUT 35.197.113.116:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -110,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.197.113.116',
port: 5432
},
original: Error: connect ETIMEDOUT 35.197.113.116:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -110,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.197.113.116',
port: 5432
}
}


问:
Angular How to make a multi filter Pipe and also maintain original indexing
I have the following:

```<code><ion-item-sliding *ngFor="let vehicle of vehicleData | customFilterPipe:'VW'; let i = index"></ion-item-sliding>
</code>```
```<code>import {Pipe, PipeTransform} from "@angular/core";

@Pipe({
  name: 'customFilterPipe',
  pure: false
})
export class CustomFilterPipe implements PipeTransform {
  transform(items: any[], filter: any): any {
    if (!items || !filter) {
      return items;
    }

    return items.filter(item => item.manufacturer.indexOf(filter) !== -1);
  }
}
</code>```

and the following vehicle data:

```<code>      "id": 1,
      "maufacturer": "vw",
      "modal": "test1",
      "color": "black"
    },
    {
      "id": 2,
      "maufacturer": "honda",
      "modal": "test9",
      "color": "black"
    },
    {
      "id": 3,
      "maufacturer": "jaguar",
      "modal": "test2",
      "color": "red"
    }]

</code>```

Currently the filter only filters by manufacturer. How can I make it multifilter eg manufacture "jaguar" and color us "red"

Additionally how can I maintain the original indexing from the original data object?

Thanks for any help here :)

I have added a singular filer as provided in the example above which works for the single filter but am now stuck for the multi filter + indexing

Body:
I have the following:

<ion-item-sliding *ngFor="let vehicle of vehicleData | customFilterPipe:'VW'; let i = index"></ion-item-sliding>

import {Pipe, PipeTransform} from "@angular/core";

@Pipe({
  name: 'customFilterPipe',
  pure: false
})
export class CustomFilterPipe implements PipeTransform {
  transform(items: any[], filter: any): any {
    if (!items || !filter) {
      return items;
    }

    return items.filter(item => item.manufacturer.indexOf(filter) !== -1);
  }
}

and the following vehicle data:

      "id": 1,
      "maufacturer": "vw",
      "modal": "test1",
      "color": "black"
    },
    {
      "id": 2,
      "maufacturer": "honda",
      "modal": "test9",
      "color": "black"
    },
    {
      "id": 3,
      "maufacturer": "jaguar",
      "modal": "test2",
      "color": "red"
    }]

Currently the filter only filters by manufacturer. How can I make it multifilter eg manufacture "jaguar" and color us "red"

Additionally how can I maintain the original indexing from the original data object?

Thanks for any help here :)

I have added a singular filer as provided in the example above which works for the single filter but am now stuck for the multi filter + indexing


问:
Refer to a date in another worksheet
So I am trying to refer to a date in another worksheet, but when the date is blank I end up with a bunch of 1900 dates.

So I tried using this formula : =IF('Titulaires'!D3="","",'Titulaires'!D3). but it doesn,t work and I don't see why
Since the IF statement work like : condition, true action, false action. i thought it would of worked

Title: Refer to a date in another worksheet


问:
react-native-share wouldn't open anything in real ios device but app doesn't freeze
I'm trying to implement sharing a pdf feature using react-native-share. When I click 'share' button, there should be a pop-up with different sharing options but nothing pops up when I connect to my real ios device and test it. The app doesn't freeze or anything. Weird thing is everything works as expected when I test it on ios simulator.
Here's my code snippet</p>
```<code>const sharePdf = async () => {

    const shareOptions = {
      url: `file://${reportUri}`,
      type: 'application/pdf',
      failOnCancel: true,
    };

    await Share.open(shareOptions);
  };

</code>```

Body:
I'm trying to implement sharing a pdf feature using react-native-share. When I click 'share' button, there should be a pop-up with different sharing options but nothing pops up when I connect to my real ios device and test it. The app doesn't freeze or anything. Weird thing is everything works as expected when I test it on ios simulator.
Here's my code snippet

const sharePdf = async () => {

    const shareOptions = {
      url: `file://${reportUri}`,
      type: 'application/pdf',
      failOnCancel: true,
    };

    await Share.open(shareOptions);
  };


问:
I'm working with the Austin Night theme; I'm trying to customize the images within the CTA section using JSON file
I'm trying to customize the CTA section with new images and the support documentation for Austin Night says you're supposed to customize images within the JSON files. I uploaded some images to the image manager but now I'm unsure of where to copy over the new image file within the coding - So I need help knowing where exactly I do this and what part of the image URL is supposed to copy over the default image text. Thanks!

I've uploaded images to the Image Manager and I've copied various parts of the image URL to replace the theme's default images, but nothing seems to work. I've been working within the en.JSON homepage file and I even tried to change the image within the OB Custom images file all in Stencil File Editor, since the theme documentation doesn't give much description on what to do exactly besides to customize in the JSON file.