问:
Laravel Sanctum XHR request returns me a 401 - "Unauthenticated."
I am trying out Laravel Sanctum and unfortunately I have a problem and hope you can help me.

I have several blade pages that I call up via the web route. For example '/', 'about-us' and /dashboard. The dashboard is only visible to users who are logged in.

web.php

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');
```
<p>In the dashboard, I have a tab where the logged-in user can view all other users. Here I send a get fetch call to the api route with Vanilla JS.</p>
<p><strong>api.php</strong></p>
<pre class="lang-php prettyprint-override"><code>Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
</code>```

My JS in the blade file looks like this:

async function send(method, url = "/api/users") {

    const rawResponse = await fetch(url, {
            method: method,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }
        }, 2000);
    const content = await rawResponse.json();
    return content;
}
```
<p><strong>Problem:</strong> But I get a 401 here <code>Object { message: "Unauthenticated." }</code>.  Why and what do I have to do to make it work?</p>
<p><strong>My thinking so far</strong>.
As I understand it, Laravel sets a <code>laravel_session</code> and an <code>XSRF-token</code> cookie when it is called. If I fire the request against the webroute, laravel recognises me as the user. But if i fire the same request against the laravel api route i am not logged in for laravel. So I have to provide something in my request. I had tried to include the XSRF token in the request header. Like that:</p>
<pre class="lang-js prettyprint-override"><code>const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
// ...
headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': token
},

</code>```

But that didn't work either.

Note: I have not configured anything else in Laravel to sanctum. I only ran the migration (personal_access_token). But the table is always empty.

My Kernel.php file:

  'api' => [
    // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
```

Body:
I am trying out Laravel Sanctum and unfortunately I have a problem and hope you can help me.

I have several blade pages that I call up via the web route. For example '/', 'about-us' and /dashboard. The dashboard is only visible to users who are logged in.

web.php

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');

In the dashboard, I have a tab where the logged-in user can view all other users. Here I send a get fetch call to the api route with Vanilla JS.

api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

My JS in the blade file looks like this:

async function send(method, url = "/api/users") {

    const rawResponse = await fetch(url, {
            method: method,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }
        }, 2000);
    const content = await rawResponse.json();
    return content;
}

Problem: But I get a 401 here Object { message: "Unauthenticated." }.  Why and what do I have to do to make it work?

My thinking so far.
As I understand it, Laravel sets a laravel_session and an XSRF-token cookie when it is called. If I fire the request against the webroute, laravel recognises me as the user. But if i fire the same request against the laravel api route i am not logged in for laravel. So I have to provide something in my request. I had tried to include the XSRF token in the request header. Like that:

const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
// ...
headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': token
},

But that didn't work either.

Note: I have not configured anything else in Laravel to sanctum. I only ran the migration (personal_access_token). But the table is always empty.

My Kernel.php file:

  'api' => [
    // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],


来源: stackexchange

问:
Comparing rows in spark dataframe to obtain a new column
I'm a beginner in spark and I'm dealing with a large dataset (over 1.5 Million rows and 2 columns). I have to evaluate the Cosine Similarity of the field "features" beetween each row. The main problem is this iteration beetween the rows and finding an efficient and rapid method. I will have to use this method with another dataset of 42.5 Million rows and it would be a big computational problem if I won't find the most efficient way of doing it.

```<code>
| post_id   |     features       |
| --------  |     --------       |
| Bkeur23   |[cat,dog,person]    |
| Ksur312kd |[wine,snow,police]  |
| BkGrtTeu3 |[]                  |
| Fwd2kd    |[person,snow,cat]   |

</code>```

I've created an algorithm that evaluates this cosine similarity beetween each element of the i-th and j-th row but i've tried using lists or creating a spark DF / RDD for each result and merging them using the" union" function.
The function I've used to evaluate the cosineSimilarity is the following. It takes 2 lists in input ( the lists of the i-th and j-th rows) and returns the maximum value of the cosine similarity between each couple of elements in the lists. But this is not the problem.

def cosineSim(lista1,lista2,embed):
#embed = hub.KerasLayer(os.getcwd())
    eps=sys.float_info.epsilon
    if((lista1 is not None) and (lista2 is not None)):
        if((len(lista1)>0) and (len(lista2)>0)):
            risultati={}
            for a in lista1:
                tem = a
                x = tf.constant([tem])
                embeddings = embed(x)
                x = np.asarray(embeddings)
                x1 = x[0].tolist()
                for b in lista2:
                    tem = b
                    x = tf.constant([tem])
                    embeddings = embed(x)
                    x = np.asarray(embeddings)
                    x2 = x[0].tolist()

                    sum = 0
                    suma1 = 0
                    sumb1 = 0
                    for i,j in zip(x1, x2):
                        suma1 += i * i
                        sumb1 += j*j
                        sum += i*j
                    cosine_sim = sum / ((sqrt(suma1))*(sqrt(sumb1))+eps)
                    risultati[a+'-'+b]=cosine_sim
                    cosine_sim=0
            risultati=max(risultati.values())
    return risultati
```
<p>The function I'm using to iterate over the rows is the following one:</p>
```def iterazione(df,numero,embed):
    a=1
    k=1

    emp_RDD = spark.sparkContext.emptyRDD()
    columns1= StructType([StructField('Source', StringType(), False),
                       StructField('Destination', StringType(), False),
                     StructField('CosinSim',FloatType(),False)])
    first_df = spark.createDataFrame(data=emp_RDD,
                                         schema=columns1)

    for i in df:

        for j in islice(df, a, None):
            r=cosineSim(i[1],j[1],embed)

            if(r>0.45):
                z=spark.createDataFrame(data=[(i[0],j[0],r)],schema=columns1)
                first_df=first_df.union(z)

            k=k+1
            if(k==numero):
                k=a+1
        a=a+1
    return first_df
```
<p>The output I desire is something like this:</p>
```

| Source    |  Dest     | CosinSim |
| --------  |  ----     |  ------  |
| Bkeur23   | Ksur312kd | 0.93     |
| Bkeur23   | Fwd2kd    | 0.673    |
| Ksur312kd | Fwd2kd    | 0.76     |

```

But there is a problem in my "iterazione" function.
I ask you to help me finding the best way to iterate all over this rows. I was thinking also about copying the column "features" as "features2" and applying my function using WithColumn but I don't know how to do it and if it will work. I want to know if there's some method to do it directly in a spark dataframe, avoiding the creation of other datasets and merging them later, or if you know some method more rapid and efficient. Thank you!

ContentLicense: CC BY-SA 4.0

Body:
I'm a beginner in spark and I'm dealing with a large dataset (over 1.5 Million rows and 2 columns). I have to evaluate the Cosine Similarity of the field "features" beetween each row. The main problem is this iteration beetween the rows and finding an efficient and rapid method. I will have to use this method with another dataset of 42.5 Million rows and it would be a big computational problem if I won't find the most efficient way of doing it.

| post_id   |     features       |
| --------  |     --------       |
| Bkeur23   |[cat,dog,person]    |
| Ksur312kd |[wine,snow,police]  |
| BkGrtTeu3 |[]                  |
| Fwd2kd    |[person,snow,cat]   |

I've created an algorithm that evaluates this cosine similarity beetween each element of the i-th and j-th row but i've tried using lists or creating a spark DF / RDD for each result and merging them using the" union" function.
The function I've used to evaluate the cosineSimilarity is the following. It takes 2 lists in input ( the lists of the i-th and j-th rows) and returns the maximum value of the cosine similarity between each couple of elements in the lists. But this is not the problem.

def cosineSim(lista1,lista2,embed):
#embed = hub.KerasLayer(os.getcwd())
    eps=sys.float_info.epsilon
    if((lista1 is not None) and (lista2 is not None)):
        if((len(lista1)>0) and (len(lista2)>0)):
            risultati={}
            for a in lista1:
                tem = a
                x = tf.constant([tem])
                embeddings = embed(x)
                x = np.asarray(embeddings)
                x1 = x[0].tolist()
                for b in lista2:
                    tem = b
                    x = tf.constant([tem])
                    embeddings = embed(x)
                    x = np.asarray(embeddings)
                    x2 = x[0].tolist()

                    sum = 0
                    suma1 = 0
                    sumb1 = 0
                    for i,j in zip(x1, x2):
                        suma1 += i * i
                        sumb1 += j*j
                        sum += i*j
                    cosine_sim = sum / ((sqrt(suma1))*(sqrt(sumb1))+eps)
                    risultati[a+'-'+b]=cosine_sim
                    cosine_sim=0
            risultati=max(risultati.values())
    return risultati

The function I'm using to iterate over the rows is the following one:

def iterazione(df,numero,embed):
    a=1
    k=1

    emp_RDD = spark.sparkContext.emptyRDD()
    columns1= StructType([StructField('Source', StringType(), False),
                       StructField('Destination', StringType(), False),
                     StructField('CosinSim',FloatType(),False)])
    first_df = spark.createDataFrame(data=emp_RDD,
                                         schema=columns1)

    for i in df:

        for j in islice(df, a, None):
            r=cosineSim(i[1],j[1],embed)

            if(r>0.45):
                z=spark.createDataFrame(data=[(i[0],j[0],r)],schema=columns1)
                first_df=first_df.union(z)

            k=k+1
            if(k==numero):
                k=a+1
        a=a+1
    return first_df

The output I desire is something like this:

| Source    |  Dest     | CosinSim |
| --------  |  ----     |  ------  |
| Bkeur23   | Ksur312kd | 0.93     |
| Bkeur23   | Fwd2kd    | 0.673    |
| Ksur312kd | Fwd2kd    | 0.76     |

But there is a problem in my "iterazione" function.
I ask you to help me finding the best way to iterate all over this rows. I was thinking also about copying the column "features" as "features2" and applying my function using WithColumn but I don't know how to do it and if it will work. I want to know if there's some method to do it directly in a spark dataframe, avoiding the creation of other datasets and merging them later, or if you know some method more rapid and efficient. Thank you!


问:
How to run gcc in pfsense terminal?
I need to run a javascript script in pfsense terminal but I don't know how to download the gcc nor node library to run it. And if I do don't know how to export the correct command to use the "gcc [command]" and "node [command]" without using the full path.
Is there anyone who can give me steps to download them, and make them usable without full path, cause I'm trying for months now and noone has helped me.

I've tried the normal way of "pkg install X" and drag&drop the library folder directly to the VM I use for the pfsense. I cant even download side package manager cause pfsense doesn't let me.

Title: How to run gcc in pfsense terminal?


问:
Why swagger truncates long string query parameters? And how can I fix that?
I have an api-part (written in .net) of an application where there is a post-method in the controller that accepts a  string value.I am trying to send a request in Swagger with a long string (544743 characters), but in my method I only received a string with 524288 characters . Then I discovered that the maximum input field in ui can hold 524288 characters.

Question: How can I increase input field length in Swagger?
P.S. I tried to find a variable in swagger configurations that is responsible for this parameter, but I couldn't.


问:
How can I activate these poses from the Outliner?
I just bought this model and it has various poses available in the outliner. How can I use them? I imagine they are some kind of controllers. Any help is appreciated.

Visibility: On/Off, activate them and deactivate the old one


问:
Nonetype object has no attribute find (cannot find tr class)
im not sure what is wrong and why beautifulsoup cannot find the tr class. What am I doing wrong or where should I look?

```<code> import requests
 from bs4 import BeautifulSoup

 URL = "https://www.dailyfx.com/economic-calendar#yesterday"
 page = requests.get(URL)
 soup = BeautifulSoup(page.content, 'html.parser')

 tbody = soup.find("tbody", class_ = "dfx-font-size-4")

 column = tbody.find("tr", class_= "dfx-expandableTable__row dfx-
 economicCalendarRow__pastEvent")

 td = column.find("td", class_="dfx-economicCalendarRow__countryCol jsdfx-
 economicCalendarRow__countryCol align-top")

 div = td.find("div", class_="dfx-economicCalendarRow__countryContent dfx-
 expandableTable__fadeableContent  dfx-border--y-0 dfx-border--l-0 text-nowrap pe-lg-6
 w-100")

 country = div.find("span", class_="dfx-economicCalendarRow__country jsdfx-
 economicCalendarRow__country align-middle text-black font-weight-bold d-none d-lg-
 inline").text

 print(country)
</code>```

here is the error:

Traceback (most recent call last): File "c:\Users\Economic Event Scraper\test.py", line 12, in  td = column.find("td", class_="dfx-economicCalendarRow__countryCol jsdfx-economicCalendarRow__countryCol align-top") AttributeError: 'NoneType' object has no attribute 'find'

Body:
im not sure what is wrong and why beautifulsoup cannot find the tr class. What am I doing wrong or where should I look?

 import requests
 from bs4 import BeautifulSoup

 URL = "https://www.dailyfx.com/economic-calendar#yesterday"
 page = requests.get(URL)
 soup = BeautifulSoup(page.content, 'html.parser')

 tbody = soup.find("tbody", class_ = "dfx-font-size-4")

 column = tbody.find("tr", class_= "dfx-expandableTable__row dfx-
 economicCalendarRow__pastEvent")

 td = column.find("td", class_="dfx-economicCalendarRow__countryCol jsdfx-
 economicCalendarRow__countryCol align-top")

 div = td.find("div", class_="dfx-economicCalendarRow__countryContent dfx-
 expandableTable__fadeableContent  dfx-border--y-0 dfx-border--l-0 text-nowrap pe-lg-6
 w-100")

 country = div.find("span", class_="dfx-economicCalendarRow__country jsdfx-
 economicCalendarRow__country align-middle text-black font-weight-bold d-none d-lg-
 inline").text

 print(country)

here is the error:

Traceback (most recent call last): File "c:\Users\Economic Event Scraper\test.py", line 12, in  td = column.find("td", class_="dfx-economicCalendarRow__countryCol jsdfx-economicCalendarRow__countryCol align-top") AttributeError: 'NoneType' object has no attribute 'find'


问:
python spacy: Create custom pipeline configurable with a variable
I have a series of regular expressions in a dictionary:

```<code>regex_dict = {
    "EN1": r"\bquick\b|\bbrown\b|\bfox\b",
    "EN2": r"\bjumps\b|\bover\b|\blazy\b|\bdog\b",
    "FR1": r"\brapide\b|\bmarrons\b|\brequin\b",
    "FR2": r"\bsaute\b|\bsur\b|\bparesseux\b|\bchien\b",
}
</code>```

Starting from a text that is in one of 5 languages I would like to match a regular expression on the text and pass the matches as spans to the spacy doc object setting an extension.

THis is done as follows:

```<code>import re
import spacy
from spacy.tokens import Span

# Load the spaCy model
nlp = spacy.load("en_core_web_sm")

# Create the custom pipeline function
def custom_pipeline(doc):
    # Define the regular expression to match
    pattern = r"quick|brown|fox|jumps|over|lazy|dog" # this is just a random regex

    # Apply the regular expression to the text of the doc object
    matches = re.finditer(pattern, doc.text)

    # Create a list of spans based on the matches
    spans = []
    for match in matches:
        start, end = match.span()
        span = Span(doc, start, end, label="NUMERAL")
        spans.append(span)

    # Set the extension attribute "numeral" on the doc object to the list of spans
    doc._.set("numeral", spans)
    return doc

# Add the custom pipeline function to the spaCy pipeline
nlp.add_pipe(custom_pipeline, name="custom_pipeline", last=True)

# Process a text with the custom pipeline
doc = nlp("The quick brown fox jumps over the lazy dog.")

# Get the spans with the "numeral" extension attribute
spans = doc._.numeral

# Print the spans
for span in spans:
    print(span.text)
</code>```

Now I would like to get a cutomizable custom pipeline where I can pass a variable in order to chose one of a series of particular regular expressions:

PSEUDOCODE:

```<code>custompipeline = f(var1, var2) ‘ where var 1 and var 2 will decide which regular expreson(s) shokuld be matched in the customized pipeline.
</code>```

And then I would like to transform that into a spacy factory.

how should I proceed?

Body:
I have a series of regular expressions in a dictionary:

regex_dict = {
    "EN1": r"\bquick\b|\bbrown\b|\bfox\b",
    "EN2": r"\bjumps\b|\bover\b|\blazy\b|\bdog\b",
    "FR1": r"\brapide\b|\bmarrons\b|\brequin\b",
    "FR2": r"\bsaute\b|\bsur\b|\bparesseux\b|\bchien\b",
}

Starting from a text that is in one of 5 languages I would like to match a regular expression on the text and pass the matches as spans to the spacy doc object setting an extension.

THis is done as follows:

import re
import spacy
from spacy.tokens import Span

# Load the spaCy model
nlp = spacy.load("en_core_web_sm")

# Create the custom pipeline function
def custom_pipeline(doc):
    # Define the regular expression to match
    pattern = r"quick|brown|fox|jumps|over|lazy|dog" # this is just a random regex

    # Apply the regular expression to the text of the doc object
    matches = re.finditer(pattern, doc.text)

    # Create a list of spans based on the matches
    spans = []
    for match in matches:
        start, end = match.span()
        span = Span(doc, start, end, label="NUMERAL")
        spans.append(span)

    # Set the extension attribute "numeral" on the doc object to the list of spans
    doc._.set("numeral", spans)
    return doc

# Add the custom pipeline function to the spaCy pipeline
nlp.add_pipe(custom_pipeline, name="custom_pipeline", last=True)

# Process a text with the custom pipeline
doc = nlp("The quick brown fox jumps over the lazy dog.")

# Get the spans with the "numeral" extension attribute
spans = doc._.numeral

# Print the spans
for span in spans:
    print(span.text)

Now I would like to get a cutomizable custom pipeline where I can pass a variable in order to chose one of a series of particular regular expressions:

PSEUDOCODE:

custompipeline = f(var1, var2) ‘ where var 1 and var 2 will decide which regular expreson(s) shokuld be matched in the customized pipeline.

And then I would like to transform that into a spacy factory.

how should I proceed?


问:
Django models - how to properly calculate multiple values with various conditions
I want to calculate multiple values in a single query on my model. Each metric should have a different filter (or no filters at all). I'm using Django==2.2.3 and a Djongo model.

MyModel columns:

```<code>user_id  = models.IntegerField(blank=True, null=True)
group_id = models.IntegerField(blank=True, null=True)
</code>```

What I try to run, suggested in another topic, does not work for me.

Query:

```<code>MyModel.objects.aggregate
    (
        total=Count('user_id'),
        test=Count('user_id', filter=Q(user_id='just_a_fake_id')),
        group_1_value=Count('user_id', filter=Q(group_id=1)),
        group_2_value=Count('user_id', filter=Q(group_id=2)),
 )
</code>```

The results: {'total': 0, 'test': 47479, 'group_1_value': 47479, 'group_2_value': 47479}, does not make sense - all results (except total) returns the same number which is the count of all the records.

What I want to run is query similar to

```<code>SELECT COUNT(user_id) as total,
       COUNT(CASE WHEN group_id=1 THEN user_id END) as group_1_value,
       COUNT(CASE WHEN group_id=2 THEN user_id END) as group_2_value
FROM MyModel
</code>```

How do I modify the query in order to get the correct values?

Body:
I want to calculate multiple values in a single query on my model. Each metric should have a different filter (or no filters at all). I'm using Django==2.2.3 and a Djongo model.

MyModel columns:

user_id  = models.IntegerField(blank=True, null=True)
group_id = models.IntegerField(blank=True, null=True)

What I try to run, suggested in another topic, does not work for me.

Query:

MyModel.objects.aggregate
    (
        total=Count('user_id'),
        test=Count('user_id', filter=Q(user_id='just_a_fake_id')),
        group_1_value=Count('user_id', filter=Q(group_id=1)),
        group_2_value=Count('user_id', filter=Q(group_id=2)),
 )

The results: {'total': 0, 'test': 47479, 'group_1_value': 47479, 'group_2_value': 47479}, does not make sense - all results (except total) returns the same number which is the count of all the records.

What I want to run is query similar to

SELECT COUNT(user_id) as total,
       COUNT(CASE WHEN group_id=1 THEN user_id END) as group_1_value,
       COUNT(CASE WHEN group_id=2 THEN user_id END) as group_2_value
FROM MyModel

How do I modify the query in order to get the correct values?


问:
Placeholder for time input in Safari
I am using <input type="time" />. Chrome, Firefox, and Edge renders it properly i.e. the placeholder used is : --:-- -- where as Safari uses 12:30 PM as a placeholder. What is the workaround for this problem?

I tried CSS solution but same issue occurs.

Title: Placeholder for time input in Safari


问:
socket.emit Not sending to client, but logs fine
So I have a very basic socket application. My Frontend is html, and i want to make it so were whenever i click a button, it alerts on another address. So it goes from admin.html -> index.js -> index.html and the admin.html -> index.js goes very smoothly, but index.html never recieves it.

heres index.js:

```<code>const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.use(express.static(__dirname+"/public"))

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('disconnect', () => {
    console.log('a user disconnected')
  });

  socket.on('epic', () => {
    console.log('test');
  });

  socket.on('alert', (text) => {
    console.log(text);
    socket.emit('bans', text)
  })
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
</code>```

admin.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin Page</title>
</head>
<body>
  <input type='text'>
  <button onClick='test()'>Alert whatever</button>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.4/socket.io.js" integrity="sha512-YeeA/Qxn5hYdkukScTCNNOhTrv1C2RubAGButJ1rmgQwZf/HdRaCGl+JAVkqsqaNRaYNHdheiuKKuPf9mDcqKg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script>
    const socket = io();

    function test() {
      let text = document.querySelector('input').value;
      socket.emit('alert', text);
    }
  </script>
</body>
</html>
</code>```

index.html:

```<code><html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Socket.io</title>
</head>
<body>
  <button onClick='test()'>Test</button>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.4/socket.io.js" integrity="sha512-YeeA/Qxn5hYdkukScTCNNOhTrv1C2RubAGButJ1rmgQwZf/HdRaCGl+JAVkqsqaNRaYNHdheiuKKuPf9mDcqKg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script>
    const socket = io();

    function test() {
      socket.emit('epic');
    }

    socket.on('bans', (text) => {
      document.title = text;
    })
  </script>
</body>
</html>
</code>```

How can I make it to where index.html receives and changes the document title? (I have tried console.log to make sure it was just my fault and the file was receiving it, but it never logged anything in the console)

Body:
So I have a very basic socket application. My Frontend is html, and i want to make it so were whenever i click a button, it alerts on another address. So it goes from admin.html -> index.js -> index.html and the admin.html -> index.js goes very smoothly, but index.html never recieves it.

heres index.js:

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.use(express.static(__dirname+"/public"))

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('disconnect', () => {
    console.log('a user disconnected')
  });

  socket.on('epic', () => {
    console.log('test');
  });

  socket.on('alert', (text) => {
    console.log(text);
    socket.emit('bans', text)
  })
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

admin.html:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin Page</title>

  <input type='text'>
  <button onClick='test()'>Alert whatever</button>

index.html:

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Socket.io</title>

  <button onClick='test()'>Test</button>

How can I make it to where index.html receives and changes the document title? (I have tried console.log to make sure it was just my fault and the file was receiving it, but it never logged anything in the console)


问:
GCN steller graph: train_gen = generator.flow(train_subjects.index, train_targets)
I am using GCN from Steller Graph with Cora dataset from CSV files (not default dataset). It gives me an error:         raise KeyError(missing_values) at train_gen = generator.flow(train_subjects.index, train_targets).

The error is given below. Also, the link to the code is here.
Any idea how to resolve the issue?

```<code>    KeyError                                  Traceback (most recent call last)
<ipython-input-42-c481c4cb28d0> in <module>
----> 1 train_gen = generator.flow(train_subjects.index, train_subjects)

4 frames
/usr/local/lib/python3.8/dist-packages/stellargraph/core/element_data.py in require_valid(self, query_ids, ilocs)
     77                 raise KeyError(missing_values[0])
     78
---> 79             raise KeyError(missing_values)
     80
     81     def to_iloc(self, ids, smaller_type=True, strict=False) -> np.ndarray:

KeyError: array([2065, 1877,  638,  255,  628, 2585, 2606, 2340,  338,  983,  429, ....])
</code>```

Body:
I am using GCN from Steller Graph with Cora dataset from CSV files (not default dataset). It gives me an error:         raise KeyError(missing_values) at train_gen = generator.flow(train_subjects.index, train_targets).

The error is given below. Also, the link to the code is here.
Any idea how to resolve the issue?

    KeyError                                  Traceback (most recent call last)
<ipython-input-42-c481c4cb28d0> in <module>
----> 1 train_gen = generator.flow(train_subjects.index, train_subjects)

4 frames
/usr/local/lib/python3.8/dist-packages/stellargraph/core/element_data.py in require_valid(self, query_ids, ilocs)
     77                 raise KeyError(missing_values[0])
     78
---> 79             raise KeyError(missing_values)
     80
     81     def to_iloc(self, ids, smaller_type=True, strict=False) -> np.ndarray:

KeyError: array([2065, 1877,  638,  255,  628, 2585, 2606, 2340,  338,  983,  429, ....])


问:
Unable to establish connection While execute transaction in TDengine
It reported an error when I wanted to create an new database in TDengine.

```<code>create database pows;
</code>```

The error was:

DB error: Unable to establish connection While execute transaction

Then I executed 'show transactions\G;` to show the transaction information.

The result are as below:

result screenshot

But I don't know how to analysis it next step.

Body:
It reported an error when I wanted to create an new database in TDengine.

create database pows;

The error was:

DB error: Unable to establish connection While execute transaction

Then I executed 'show transactions\G;` to show the transaction information.

The result are as below:

result screenshot

But I don't know how to analysis it next step.


问:
How to solve this kind of unknown error of get storage
I'd faced this unknown error where the getStorage have problem to write the data. Is anybody ever met this type of error. Hope somebody can help me.

    String? nullCheck(String? state, String? data, String device, String key) {
    var checkData;

    if (state != null) {
      checkData = data;
      getStorage.write(device + key, data);

      return checkData;
    }
    if (state == null) {
      checkData = getStorage.read(device + key);
    }
    return checkData;
  }
```

the error as in this picture:
unknown error of get storage

Body:
I'd faced this unknown error where the getStorage have problem to write the data. Is anybody ever met this type of error. Hope somebody can help me.

    String? nullCheck(String? state, String? data, String device, String key) {
    var checkData;

    if (state != null) {
      checkData = data;
      getStorage.write(device + key, data);

      return checkData;
    }
    if (state == null) {
      checkData = getStorage.read(device + key);
    }
    return checkData;
  }

the error as in this picture:
unknown error of get storage


问:
Block request that is not coming through the load balancer (Fixed)
I have a two servers that serve the same static content behind an Nginx load balancer
`

```<code>    upstream backend {
        server xxx.xxx.xxx.xx;
        server xxx.xxx.xxx.xx;
    }

    server {
        server_name example.com www.example.com;
        location / {
            proxy_pass http://backend;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

    server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host !~* ^(www\.)?example.com$) {
        return 444;
    }

        listen 80;
        server_name example.com www.example.com;
    return 404; # managed by Certbot

}
</code>```

`
So far I have blocked access to the load balancer from the IP and I want to do the same for the servers I want only the requests that goes through the load balancer to be accpted by both backend servers.

servers have same configuration here is how it looks:

`

```<code>server {
        listen 80 default_server;
        listen [::]:80 default_server;
        root /var/www/html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        access_log /var/log/nginx/access.log;
}
</code>```

`

FIXED:
I created a special header that the load balancer adds to the request and if it is not included the server will close the connection.

Body:
I have a two servers that serve the same static content behind an Nginx load balancer
`

    upstream backend {
        server xxx.xxx.xxx.xx;
        server xxx.xxx.xxx.xx;
    }

    server {
        server_name example.com www.example.com;
        location / {
            proxy_pass http://backend;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

    server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host !~* ^(www\.)?example.com$) {
        return 444;
    }

        listen 80;
        server_name example.com www.example.com;
    return 404; # managed by Certbot

}

`
So far I have blocked access to the load balancer from the IP and I want to do the same for the servers I want only the requests that goes through the load balancer to be accpted by both backend servers.

servers have same configuration here is how it looks:

`

server {
        listen 80 default_server;
        listen [::]:80 default_server;
        root /var/www/html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        access_log /var/log/nginx/access.log;
}

`

FIXED:
I created a special header that the load balancer adds to the request and if it is not included the server will close the connection.


问:
Delete element from a nested list while keeping the original nested structure CLISP
Is there a way to delete an element from a nested list while also keeping the nested structure intact?

For instance, for the list ((1 (2 (3 (3 4 5 (3 (3)))) 3 4) 3 3) 3 (3 3)) if we delete the element 3 then the result should be ((1 (2 ((4 5 (()))) 4)) ()), essentially the function should keep the previous list structure

I tried checking 3 cases:

a) if the current element is an atom and equal to the given number, then nothing should happen

b) if the current element is an atom and different than the given number, then it should be appended to the result

c) if the current element is a list, then the delete function should be applied to it (using mapcar and a lambda)

If I run my delete function on the list ((1 (2 (3 (3 4 5 (3 (3)))) 3 4) 3 3) 3 (3 3)) where the given number is 3, it outputs (1 2 4 5 4) instead of the expected outcome ((1 (2 ((4 5 (()))) 4)) ())

I believe it's because I turn the current element into a list (if it's equal to the given number) and then use append which removes the parentheses

(defun delete (no l)
    (cond
        ;; current element == given number
        ;; it shouldn't be added to the result -> nil
        ((and (atom l) (equal no l)) nil)
        ;; current element != given number
        ;; it is made into a list and added to the result
        ((and (atom l) (not (equal no l)))  (list l))
        ;; current element is a list
        ;; the delete function is applied to each element of the list using mapcar
        (t (apply 'append (mapcar #'(lambda (x) (delete n x)) l)))))
```


问:
How to go about forwarding inputs through a randomly connected neural network
I saw a youtube video on genetic algorithms by davidrandallmiller and wanted to see if I could code it myself but I'm not sure how to go about doing it

if I generate a bunch of random binary encoded genes, every gene describes a single connection between two neuron, if I understood from the video correctly, every neuron calculates it's own output by getting the weighted sum of all of it's inputs, and then runs them through thanh function and passes that output to the next neuron

but I don't understand how a neuron can connect to itself.

and how do I find the order of which to calculate neuron outputs, because I feel like I should make it so a neuron can't be activated (calculate it's outputs and pass them) unless all of it's incoming connections have also been activated

I'm not sure if that makes sense, maybe there is some other technique I can use to achieve a genetic algorithm with neural network?

any help is appreciated


问:
Boostrap Datatables with Admin LTE breaking page & not staying responsive with more then 1 table on the page
I am having some extreme difficulties in keeping my data tables responsive on smaller screens. I have the issue page coming up on my reports page where I have navbar tabs to show 3 different tables (Only 2 are shown in the code and until I fix this error I am not continuing with said page.) which are Clicks/Leads/Reversals (Clicks/Leads for now). It is breaking out of my page as shown in the pictures below on the Leads tab table:

Clicks page preview

Leads page preview - Problematic table lies here

My code for displaying that page is like so:

reports.blade.php

@extends('admin.layouts.app')

@section('content')

Offer Reports

Home

Offer Reports

                            Clicks

                            Leads

                            Reversals

                            Revenue

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                                @foreach($clicks as $click)
                                    @php
                                    $banner = \App\Models\OfferBanner::find($click->bid);
                                    $offer = \App\Models\Offer::find($banner->oid);
                                    $advertiser = \App\Models\Advertiser::find($offer->aid);
                                    $publisher = \App\Models\Publisher::find($click->pid);
                                    $geo_location = \Location::get($click->ip_address);
                                    $timestamp = \Carbon\Carbon::parse($click->created_at)->toDateTimeString();
                                    @endphp

                                        {{ $click->id }}
                                        id) }}">{{ $offer->name }}
                                        id) }}">{{ $advertiser->company }}
                                        id) }}">{{ $publisher->first_name }} {{ $publisher->last_name }}
                                        {{ $click->token }}
                                        @if($click->s1) {{ $click->s1 }} @endif @if($click->s2)/ {{$click->s2}} @endif @if($click->s3)/ {{ $click->s3 }} @endif @if($click->s4)/ {{$click->s4}} @endif @if($click->s5)/ {{ $click->s5 }} @endif
                                        {{ $click->referred_url }}

regionName }}, {{ $geo_location->countryName }}">{{ $click->ip_address }}

                                        {{ $timestamp }}

                                            <form action="" method="post">
                                                @csrf
                                                <input type="text" name="action" value="credit" hidden>
                                                <button class="btn btn-app" type="submit">
                                                     Credit
                                                </button>
                                            </form>

                                @endforeach

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                                @foreach($leads as $lead)
                                    @php
                                        $banner = \App\Models\OfferBanner::find($lead->bid);
                                        $offer = \App\Models\Offer::find($banner->oid);
                                        $advertiser = \App\Models\Advertiser::find($offer->aid);
                                        $publisher = \App\Models\Publisher::find($lead->pid);
                                        $geo_location = \Location::get($lead->ip_address);
                                        $timestamp = \Carbon\Carbon::parse($lead->created_at)->toDateTimeString();
                                    @endphp

                                        {{ $lead->id }}
                                        {{ $offer->name }}
                                        {{ $advertiser->company }}
                                        {{ $publisher->first_name }} {{ $publisher->last_name }}
                                        {{ $lead->token }}
                                        @if($lead->s1) {{ $lead->s1 }} @endif @if($lead->s2)/ {{$lead->s2}} @endif @if($lead->s3)/ {{ $lead->s3 }} @endif @if($lead->s4)/ {{$lead->s4}} @endif @if($lead->s5)/ {{ $lead->s5 }} @endif
                                        {{ $lead->referred_url }}

regionName }}, {{ $geo_location->countryName }}">{{ $lead->ip_address }}

                                        {{ $timestamp }}

                                            <form action="" method="post">
                                                @csrf
                                                <input type="text" name="action" value="reverse" hidden>
                                                <button class="btn btn-app" type="submit">
                                                     Reverse
                                                </button>
                                            </form>

                                @endforeach

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                            Morbi turpis dolor, vulputate vitae felis non, tincidunt congue mauris. Phasellus volutpat augue id mi placerat mollis. Vivamus faucibus eu massa eget condimentum. Fusce nec hendrerit sem, ac tristique nulla. Integer vestibulum orci odio. Cras nec augue ipsum. Suspendisse ut velit condimentum, mattis urna a, malesuada nunc. Curabitur eleifend facilisis velit finibus tristique. Nam vulputate, eros non luctus efficitur, ipsum odio volutpat massa, sit amet sollicitudin est libero sed ipsum. Nulla lacinia, ex vitae gravida fermentum, lectus ipsum gravida arcu, id fermentum metus arcu vel metus. Curabitur eget sem eu risus tincidunt eleifend ac ornare magna.

                            Pellentesque vestibulum commodo nibh nec blandit. Maecenas neque magna, iaculis tempus turpis ac, ornare sodales tellus. Mauris eget blandit dolor. Quisque tincidunt venenatis vulputate. Morbi euismod molestie tristique. Vestibulum consectetur dolor a vestibulum pharetra. Donec interdum placerat urna nec pharetra. Etiam eget dapibus orci, eget aliquet urna. Nunc at consequat diam. Nunc et felis ut nisl commodo dignissim. In hac habitasse platea dictumst. Praesent imperdiet accumsan ex sit amet facilisis.

    @endsection
@section('footerComponent')

@endsection```

Inside app.blade i have called all the required css styles & javascript files that adminlte requires, as seen in the screenshots the pages load the datatable. It wouldn't let me include the app.blade.php for character reasons. The inital  call is in app.blade.php the same way table2 is called above in the reports.blade.php and is placed at bottom of the app.blade.php after all other javascripts.

I was having the issue of the Leads table being smaller and not stretching the whole length so i added some more paramenters to the datatable load. Now i just have this second table bugging me and wondering how the 3rd table will come to show on this single page.

Body:
I am having some extreme difficulties in keeping my data tables responsive on smaller screens. I have the issue page coming up on my reports page where I have navbar tabs to show 3 different tables (Only 2 are shown in the code and until I fix this error I am not continuing with said page.) which are Clicks/Leads/Reversals (Clicks/Leads for now). It is breaking out of my page as shown in the pictures below on the Leads tab table:

Clicks page preview

Leads page preview - Problematic table lies here

My code for displaying that page is like so:

reports.blade.php

@extends('admin.layouts.app')

@section('content')

Offer Reports

Home

Offer Reports

                            Clicks

                            Leads

                            Reversals

                            Revenue

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                                @foreach($clicks as $click)
                                    @php
                                    $banner = \App\Models\OfferBanner::find($click->bid);
                                    $offer = \App\Models\Offer::find($banner->oid);
                                    $advertiser = \App\Models\Advertiser::find($offer->aid);
                                    $publisher = \App\Models\Publisher::find($click->pid);
                                    $geo_location = \Location::get($click->ip_address);
                                    $timestamp = \Carbon\Carbon::parse($click->created_at)->toDateTimeString();
                                    @endphp

                                        {{ $click->id }}
                                        id) }}">{{ $offer->name }}
                                        id) }}">{{ $advertiser->company }}
                                        id) }}">{{ $publisher->first_name }} {{ $publisher->last_name }}
                                        {{ $click->token }}
                                        @if($click->s1) {{ $click->s1 }} @endif @if($click->s2)/ {{$click->s2}} @endif @if($click->s3)/ {{ $click->s3 }} @endif @if($click->s4)/ {{$click->s4}} @endif @if($click->s5)/ {{ $click->s5 }} @endif
                                        {{ $click->referred_url }}

regionName }}, {{ $geo_location->countryName }}">{{ $click->ip_address }}

                                        {{ $timestamp }}

                                            <form action="" method="post">
                                                @csrf
                                                <input type="text" name="action" value="credit" hidden>
                                                <button class="btn btn-app" type="submit">
                                                     Credit
                                                </button>
                                            </form>

                                @endforeach

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                                @foreach($leads as $lead)
                                    @php
                                        $banner = \App\Models\OfferBanner::find($lead->bid);
                                        $offer = \App\Models\Offer::find($banner->oid);
                                        $advertiser = \App\Models\Advertiser::find($offer->aid);
                                        $publisher = \App\Models\Publisher::find($lead->pid);
                                        $geo_location = \Location::get($lead->ip_address);
                                        $timestamp = \Carbon\Carbon::parse($lead->created_at)->toDateTimeString();
                                    @endphp

                                        {{ $lead->id }}
                                        {{ $offer->name }}
                                        {{ $advertiser->company }}
                                        {{ $publisher->first_name }} {{ $publisher->last_name }}
                                        {{ $lead->token }}
                                        @if($lead->s1) {{ $lead->s1 }} @endif @if($lead->s2)/ {{$lead->s2}} @endif @if($lead->s3)/ {{ $lead->s3 }} @endif @if($lead->s4)/ {{$lead->s4}} @endif @if($lead->s5)/ {{ $lead->s5 }} @endif
                                        {{ $lead->referred_url }}

regionName }}, {{ $geo_location->countryName }}">{{ $lead->ip_address }}

                                        {{ $timestamp }}

                                            <form action="" method="post">
                                                @csrf
                                                <input type="text" name="action" value="reverse" hidden>
                                                <button class="btn btn-app" type="submit">
                                                     Reverse
                                                </button>
                                            </form>

                                @endforeach

                                    #
                                    Offer
                                    Advertiser
                                    Publisher
                                    Click ID
                                    Sub IDs
                                    Referer
                                    I.P. Address
                                    Timestamp
                                    Action

                            Morbi turpis dolor, vulputate vitae felis non, tincidunt congue mauris. Phasellus volutpat augue id mi placerat mollis. Vivamus faucibus eu massa eget condimentum. Fusce nec hendrerit sem, ac tristique nulla. Integer vestibulum orci odio. Cras nec augue ipsum. Suspendisse ut velit condimentum, mattis urna a, malesuada nunc. Curabitur eleifend facilisis velit finibus tristique. Nam vulputate, eros non luctus efficitur, ipsum odio volutpat massa, sit amet sollicitudin est libero sed ipsum. Nulla lacinia, ex vitae gravida fermentum, lectus ipsum gravida arcu, id fermentum metus arcu vel metus. Curabitur eget sem eu risus tincidunt eleifend ac ornare magna.

                            Pellentesque vestibulum commodo nibh nec blandit. Maecenas neque magna, iaculis tempus turpis ac, ornare sodales tellus. Mauris eget blandit dolor. Quisque tincidunt venenatis vulputate. Morbi euismod molestie tristique. Vestibulum consectetur dolor a vestibulum pharetra. Donec interdum placerat urna nec pharetra. Etiam eget dapibus orci, eget aliquet urna. Nunc at consequat diam. Nunc et felis ut nisl commodo dignissim. In hac habitasse platea dictumst. Praesent imperdiet accumsan ex sit amet facilisis.

    @endsection
@section('footerComponent')

@endsection

Inside app.blade i have called all the required css styles & javascript files that adminlte requires, as seen in the screenshots the pages load the datatable. It wouldn't let me include the app.blade.php for character reasons. The inital  call is in app.blade.php the same way table2 is called above in the reports.blade.php and is placed at bottom of the app.blade.php after all other javascripts.

I was having the issue of the Leads table being smaller and not stretching the whole length so i added some more paramenters to the datatable load. Now i just have this second table bugging me and wondering how the 3rd table will come to show on this single page.


问:
webassembly doesn't display {{.}}
There is a go project on the gin-gonic framework and webassembly uses when inserting code, there is no element display

main.go

```<code>
...

r.GET("/outh", func(c \*gin.Context) {
r.LoadHTMLFiles("./templates/outh/outh.html", "./templates/footer.html", "./templates/navbar.html", "./templates/static.html")
c.HTML(http.StatusOK, "outh.html", gin.H{
"Title": "test"
})

    })

...
</code>```

wasm code

```<code>

var document = js.Global().Get("document")

func register(_ js.Value, _ []js.Value) interface{} {

message := `{{.Title}} `

    reg := document.Call("getElementById", "logindiv")

    reg.Set("innerHTML", message)

return nil
}

func main() {

reg := document.Call("getElementById", "registerss")
    reg.Set("value", "0")
    reg.Call("addEventListener", "click", js.FuncOf(register))

}
</code>```

How to make an image appear when inserting html code?

Everything works but I do not understand why it is not displayed.

result:
enter image description here

Title: webassembly doesn't display {{.}}

Body:
There is a go project on the gin-gonic framework and webassembly uses when inserting code, there is no element display

main.go

...

r.GET("/outh", func(c \*gin.Context) {
r.LoadHTMLFiles("./templates/outh/outh.html", "./templates/footer.html", "./templates/navbar.html", "./templates/static.html")
c.HTML(http.StatusOK, "outh.html", gin.H{
"Title": "test"
})

    })

...

wasm code

var document = js.Global().Get("document")

func register(_ js.Value, _ []js.Value) interface{} {

message := `{{.Title}} `

    reg := document.Call("getElementById", "logindiv")

    reg.Set("innerHTML", message)

return nil
}

func main() {

reg := document.Call("getElementById", "registerss")
    reg.Set("value", "0")
    reg.Call("addEventListener", "click", js.FuncOf(register))

}

How to make an image appear when inserting html code?

Everything works but I do not understand why it is not displayed.

result:
enter image description here


问:
Count the rising edges in a 128 wide bitfield
Number of rising edges = The number of "01" bit patterns.
I do not know how to copy only 1 or two bits from a long pattern in a register, after that I thought about doing shift and compare it to "01" and increase R5 (which is the output, contains the number of rising edges)
My input is R7 (Base address of the 128-bit bitfield in the internal memory)</p>
```<code>COUNT_01_NOMOD:

; [TODO: Place your code here]
    MOV R6, @R7
    back: SHL $1, R6
        CJNE R6, 1, cero_first
        cero_first: CJNE, 0, back
    INC R5

    RET
</code>```

Body:
Number of rising edges = The number of "01" bit patterns.
I do not know how to copy only 1 or two bits from a long pattern in a register, after that I thought about doing shift and compare it to "01" and increase R5 (which is the output, contains the number of rising edges)
My input is R7 (Base address of the 128-bit bitfield in the internal memory)

COUNT_01_NOMOD:

; [TODO: Place your code here]
    MOV R6, @R7
    back: SHL $1, R6
        CJNE R6, 1, cero_first
        cero_first: CJNE, 0, back
    INC R5

    RET


问:
Compilation error, Delphi project within Jenkins
I migrated a project from Delphi 10.1 to Delphi 11 and when compiling the project, I get the error:

```<code>[DCC Error] E2597 /Users/jenkins/Jenkins/tools/android-ndk-r18b/sources/cxx-stl/llvm-libc++/include/ios:529: error: undefined reference to 'std::__ndk1::ios_base::clear(unsigned int)''
</code>```

What could i be doing wrong?

I already created a new project, and imported the units, but even so the error continues...

Body:
I migrated a project from Delphi 10.1 to Delphi 11 and when compiling the project, I get the error:

[DCC Error] E2597 /Users/jenkins/Jenkins/tools/android-ndk-r18b/sources/cxx-stl/llvm-libc++/include/ios:529: error: undefined reference to 'std::__ndk1::ios_base::clear(unsigned int)''

What could i be doing wrong?

I already created a new project, and imported the units, but even so the error continues...


问:
External onLoad function does not trigger in script tag
I am struggling to make the following component to work as expected :

```<code>const Example=()=>{
    const ref = useRef(null);

    useEffect(() => {
        let refValue;

        if (ref.current) {
            const script = document.createElement("script");
            script.src = "https://externalsource.com/hey.js";

            script.async = true;
            script.type = "text/javascript";

            const onScriptLoad=()=>{
                 externalFunction();
               };

            script.onload = onScriptLoad;
            ref.current.appendChild(script);
            refValue = ref.current;
        };

        return () => {
            if (refValue) {
                while (refValue.firstChild) {
                    refValue.removeChild(refValue.firstChild);
                };
            };
        };
    }, [ref,]);

    return (
        <div className="..." >
            <div ref={ref} className="..."  />
        </div>
    );

};
</code>```

In React , I always get "externalFunction is not defined" , whereas in NextJS the component does work as expected. Could you please let me know why , and how would you address it ?

Thanks !

Body:
I am struggling to make the following component to work as expected :

const Example=()=>{
    const ref = useRef(null);

    useEffect(() => {
        let refValue;

        if (ref.current) {
            const script = document.createElement("script");
            script.src = "https://externalsource.com/hey.js";

            script.async = true;
            script.type = "text/javascript";

            const onScriptLoad=()=>{
                 externalFunction();
               };

            script.onload = onScriptLoad;
            ref.current.appendChild(script);
            refValue = ref.current;
        };

        return () => {
            if (refValue) {
                while (refValue.firstChild) {
                    refValue.removeChild(refValue.firstChild);
                };
            };
        };
    }, [ref,]);

    return (

    );

};

In React , I always get "externalFunction is not defined" , whereas in NextJS the component does work as expected. Could you please let me know why , and how would you address it ?

Thanks !


问:
flutter_modular: ^5.0.3. return GuardedRouteException or RouteNotFoundException
I try to navigate from  recruiter to recruiter/task inside the Children of recruiter ModuleRoute.

Here I want to Open TaskPage on RouterOutlet.

Package Used

```<code>flutter_modular: ^5.0.3
</code>```

Routes list ---

```<code>@override
List<ModularRoute> get routes => [
  ChildRoute('/', child: (context, args) => RecruiterLandingPage(),
      children: [
        ChildRoute('/tasks',
          child: (context, args) =>TasksPage(),
          transition: TransitionType.noTransition,

        ),
    ];
</code>```

RecruiterLandingPage

I use :

```<code>Modular.to.navigate('/tasks');
</code>```

It returns Exception

```<code>Error: RouteNotFoundException: Route (/tasks) not found
           dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49                    throw_
           packages/flutter_modular/src/presenter/navigation/modular_route_information_parser.dart 111:9   <fn>
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 84:54                              runBody
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 123:5                              _async
           packages/flutter_modular/src/presenter/navigation/modular_route_information_parser.dart 109:56  <fn>
           packages/flutter_modular/src/shared/either.dart 46:18                                           fold
           packages/flutter_modular/src/presenter/navigation/modular_route_information_parser.dart 109:24  selectRoute
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50                              <fn>
           dart-sdk/lib/async/zone.dart 1653:54                                                            runUnary
           dart-sdk/lib/async/future_impl.dart 147:18                                                      handleValue
           dart-sdk/lib/async/future_impl.dart 766:44                                                      handleValueCallback
           dart-sdk/lib/async/future_impl.dart 795:13                                                      _propagateToListeners
           dart-sdk/lib/async/future_impl.dart 566:5                                                       [_completeWithValue]
           dart-sdk/lib/async/future_impl.dart 639:7                                                       callback
           dart-sdk/lib/async/schedule_microtask.dart 40:11                                                _microtaskLoop
           dart-sdk/lib/async/schedule_microtask.dart 49:5                                                 _startMicrotaskLoop
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15                             <fn>
</code>```

and When I Use :

```<code>Modular.to.navigate('/recruiter/tasks');
</code>```

It returns Exception

```<code>Error: GuardedRouteException: /recruiter/
           dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49  throw_
           packages/flutter_modular/src/presenter/guards/route_guard.dart 31:5           pos
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50            <fn>
           dart-sdk/lib/async/zone.dart 1653:54                                          runUnary
           dart-sdk/lib/async/future_impl.dart 147:18                                    handleValue
           dart-sdk/lib/async/future_impl.dart 766:44                                    handleValueCallback
           dart-sdk/lib/async/future_impl.dart 795:13                                    _propagateToListeners
           dart-sdk/lib/async/future_impl.dart 566:5                                     [_completeWithValue]
           dart-sdk/lib/async/future_impl.dart 639:7                                     callback
           dart-sdk/lib/async/schedule_microtask.dart 40:11                              _microtaskLoop
           dart-sdk/lib/async/schedule_microtask.dart 49:5                               _startMicrotaskLoop
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15           <fn>
</code>```

recruiter Route Open by using :

```<code>ModuleRoute("/recruiter", module: RecruiterModule(),
    guards: [AuthGuard(), Modular.get<RoleGuardVerify>().getGuard(RoleGuardVerify.RECRUITER)]
),
</code>```

Authguard

```<code>import 'package:/authentication/ui/bloc/user_status/user_status_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';

class AuthGuard extends RouteGuard {
  AuthGuard() : super();

  @override
  Future<bool> canActivate(String path, ModularRoute router) async {
    var bloc = Modular.get<UserStatusBloc>();
    bloc.add(UserStatusLoadStarted());

    return bloc.state is UserStatusLogin;
  }
}
</code>```

RoleGuardVerify

```<code>import 'package:---/app/role_guard.dart';
import 'package:----/authentication/ui/bloc/user_status/user_status_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';

class RoleGuardVerify {
  static final int RECRUITER = 1;
  static final int CONSULTANT = 2;
  static final int MANAGER = 3;

  Map<int, String> redirectByRole = {
    RECRUITER: "/recruiter",
    CONSULTANT: "/consultant",
    MANAGER: "/manager"
  };

  RouteGuard getGuard(int guardRoleType) {
    try {
      var bloc = Modular.get<UserStatusBloc>();
      if (!(bloc.state is UserStatusLogin)) {
        return RoleGuard(guardRoleType, "/login");
      }
      var user = (bloc.state as UserStatusLogin).user;
      var redirect = redirectByRole[user.role];
      if(redirect != null) {

        return RoleGuard(guardRoleType, redirect);
      }else{
        return RoleGuard(guardRoleType, '/recruiter');
      }
    } catch (e) {

      return RoleGuard(guardRoleType, "/login");
    }
  }
}
</code>```

In my opinion, The Guards I created are not returning GuardedRouteException. I want the right way to do navigation.

I used the link(https://modular.flutterando.com.br/docs/flutter_modular/navegation) for this navigation.

Body:
I try to navigate from  recruiter to recruiter/task inside the Children of recruiter ModuleRoute.

Here I want to Open TaskPage on RouterOutlet.

Package Used

flutter_modular: ^5.0.3

Routes list ---

@override
List<ModularRoute> get routes => [
  ChildRoute('/', child: (context, args) => RecruiterLandingPage(),
      children: [
        ChildRoute('/tasks',
          child: (context, args) =>TasksPage(),
          transition: TransitionType.noTransition,

        ),
    ];

RecruiterLandingPage

I use :

Modular.to.navigate('/tasks');

It returns Exception

Error: RouteNotFoundException: Route (/tasks) not found
           dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49                    throw_
           packages/flutter_modular/src/presenter/navigation/modular_route_information_parser.dart 111:9   <fn>
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 84:54                              runBody
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 123:5                              _async
           packages/flutter_modular/src/presenter/navigation/modular_route_information_parser.dart 109:56  <fn>
           packages/flutter_modular/src/shared/either.dart 46:18                                           fold
           packages/flutter_modular/src/presenter/navigation/modular_route_information_parser.dart 109:24  selectRoute
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50                              <fn>
           dart-sdk/lib/async/zone.dart 1653:54                                                            runUnary
           dart-sdk/lib/async/future_impl.dart 147:18                                                      handleValue
           dart-sdk/lib/async/future_impl.dart 766:44                                                      handleValueCallback
           dart-sdk/lib/async/future_impl.dart 795:13                                                      _propagateToListeners
           dart-sdk/lib/async/future_impl.dart 566:5                                                       [_completeWithValue]
           dart-sdk/lib/async/future_impl.dart 639:7                                                       callback
           dart-sdk/lib/async/schedule_microtask.dart 40:11                                                _microtaskLoop
           dart-sdk/lib/async/schedule_microtask.dart 49:5                                                 _startMicrotaskLoop
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15                             <fn>

and When I Use :

Modular.to.navigate('/recruiter/tasks');

It returns Exception

Error: GuardedRouteException: /recruiter/
           dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49  throw_
           packages/flutter_modular/src/presenter/guards/route_guard.dart 31:5           pos
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50            <fn>
           dart-sdk/lib/async/zone.dart 1653:54                                          runUnary
           dart-sdk/lib/async/future_impl.dart 147:18                                    handleValue
           dart-sdk/lib/async/future_impl.dart 766:44                                    handleValueCallback
           dart-sdk/lib/async/future_impl.dart 795:13                                    _propagateToListeners
           dart-sdk/lib/async/future_impl.dart 566:5                                     [_completeWithValue]
           dart-sdk/lib/async/future_impl.dart 639:7                                     callback
           dart-sdk/lib/async/schedule_microtask.dart 40:11                              _microtaskLoop
           dart-sdk/lib/async/schedule_microtask.dart 49:5                               _startMicrotaskLoop
           dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15           <fn>

recruiter Route Open by using :

ModuleRoute("/recruiter", module: RecruiterModule(),
    guards: [AuthGuard(), Modular.get<RoleGuardVerify>().getGuard(RoleGuardVerify.RECRUITER)]
),

Authguard

import 'package:/authentication/ui/bloc/user_status/user_status_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';

class AuthGuard extends RouteGuard {
  AuthGuard() : super();

  @override
  Future<bool> canActivate(String path, ModularRoute router) async {
    var bloc = Modular.get<UserStatusBloc>();
    bloc.add(UserStatusLoadStarted());

    return bloc.state is UserStatusLogin;
  }
}

RoleGuardVerify

import 'package:---/app/role_guard.dart';
import 'package:----/authentication/ui/bloc/user_status/user_status_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';

class RoleGuardVerify {
  static final int RECRUITER = 1;
  static final int CONSULTANT = 2;
  static final int MANAGER = 3;

  Map<int, String> redirectByRole = {
    RECRUITER: "/recruiter",
    CONSULTANT: "/consultant",
    MANAGER: "/manager"
  };

  RouteGuard getGuard(int guardRoleType) {
    try {
      var bloc = Modular.get<UserStatusBloc>();
      if (!(bloc.state is UserStatusLogin)) {
        return RoleGuard(guardRoleType, "/login");
      }
      var user = (bloc.state as UserStatusLogin).user;
      var redirect = redirectByRole[user.role];
      if(redirect != null) {

        return RoleGuard(guardRoleType, redirect);
      }else{
        return RoleGuard(guardRoleType, '/recruiter');
      }
    } catch (e) {

      return RoleGuard(guardRoleType, "/login");
    }
  }
}

In my opinion, The Guards I created are not returning GuardedRouteException. I want the right way to do navigation.

I used the link(https://modular.flutterando.com.br/docs/flutter_modular/navegation) for this navigation.


问:
python socket trying to set a specific time the recv() function would work for
i am building a network system with connects a raspberry pi 4 and my computer
my computer should send some things to the raspberry pi and every 10 iterations a request for the value of a distance sensor

i tried sending the request but the request is being sent only 6 times and then the program in my computer gets stuck on the recv part(waiting to get the information but doesnt getting anything)

i tried doing a timeout to the recv method but it doesnt work, does anyone know how to do that the recv() function will only try to get the information for a specific time?
like doing that the socket will try getting information each time for a specific time and then more to the next iteration


问:
How to add filter inside the tabular-inline model of django admin
I am trying to add filter with inline model

I tried adding list_filter within inline class but it is a method not given in inline class