问:
how to set the number of cards in a row in bootstrap carousel
inside a container, when I gave col-md-3 on each carousel-item 4 cards are shown at a time.
but what I want is to display two card on a row on medium screens (col-md-6) and 3 cards on larger and extra large screens (col-lg-4). also one card on mobile screens (xs).

I have tried col-lg-4 on each item but it doesn't work as expected. how can I solve this?

html

```<code>
<!------ Include the above in your HEAD tag ---------->

<!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>Document</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <link rel="stylesheet" href="./ashik.css">
</head>
<body>
    <div class="container-fluid">
        <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000">
            <div class="carousel-inner row w-100 mx-auto" role="listbox">
                <div class="carousel-item col-md-3  active">
                   <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 1" class="thumb">
                          <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=1" alt="slide 1">
                        </a>
                      </div>
                    </div>
                </div>
                <div class="carousel-item col-md-3 ">
                   <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 3" class="thumb">
                         <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=2" alt="slide 2">
                        </a>
                      </div>
                    </div>
                </div>
                <div class="carousel-item col-md-3 ">
                   <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 4" class="thumb">
                         <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=3" alt="slide 3">
                        </a>
                      </div>
                    </div>
                </div>
                <div class="carousel-item col-md-3 ">
                    <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 5" class="thumb">
                         <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=4" alt="slide 4">
                        </a>
                      </div>
                    </div>
                </div>
                <div class="carousel-item col-md-3 ">
                  <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 6" class="thumb">
                          <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=5" alt="slide 5">
                        </a>
                      </div>
                    </div>
                </div>
                <div class="carousel-item col-md-3 ">
                   <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 7" class="thumb">
                          <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=6" alt="slide 6">
                        </a>
                      </div>
                    </div>
                </div>
                <div class="carousel-item col-md-3 ">
                   <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 8" class="thumb">
                          <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=7" alt="slide 7">
                        </a>
                      </div>
                    </div>
                </div>
                 <div class="carousel-item col-md-3">
                    <div class="panel panel-default">
                      <div class="panel-thumbnail">
                        <a href="#" title="image 2" class="thumb">
                         <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=8" alt="slide 8">
                        </a>
                      </div>

                    </div>
                </div>

            </div>
            <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="sr-only">Previous</span>
            </a>
            <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="sr-only">Next</span>
            </a>
        </div>
    </div>

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> -->

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
<script src="./ashik.js"></script>

</body>
</html>
</code>```

js

```<code>
$('#carouselExample').on('slide.bs.carousel', function (e) {

    var $e = $(e.relatedTarget);
    var idx = $e.index();
    var itemsPerSlide = 4;
    var totalItems = $('.carousel-item').length;

    if (idx >= totalItems-(itemsPerSlide-1)) {
        var it = itemsPerSlide - (totalItems - idx);
        console.log({it});
        for (var i=0; i<it; i++) {
            // append slides to end
            if (e.direction=="left") {
                $('.carousel-item').eq(i).appendTo('.carousel-inner');
            }
            else {
                $('.carousel-item').eq(0).appendTo('.carousel-inner');
            }
        }
    }
});

  $('#carouselExample').carousel({
                interval: false,
        });

  $(document).ready(function() {
/* show lightbox when clicking a thumbnail */
    $('a.thumb').click(function(event){
      event.preventDefault();
      var content = $('.modal-body');
      content.empty();
        var title = $(this).attr("title");
        $('.modal-title').html(title);
        content.html($(this).html());
        $(".modal-profile").modal({show:true});
    });

  });
</code>```

Body:
inside a container, when I gave col-md-3 on each carousel-item 4 cards are shown at a time.
but what I want is to display two card on a row on medium screens (col-md-6) and 3 cards on larger and extra large screens (col-lg-4). also one card on mobile screens (xs).

I have tried col-lg-4 on each item but it doesn't work as expected. how can I solve this?

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>Document</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <link rel="stylesheet" href="./ashik.css">

                Previous

                Next

js

$('#carouselExample').on('slide.bs.carousel', function (e) {

    var $e = $(e.relatedTarget);
    var idx = $e.index();
    var itemsPerSlide = 4;
    var totalItems = $('.carousel-item').length;

    if (idx >= totalItems-(itemsPerSlide-1)) {
        var it = itemsPerSlide - (totalItems - idx);
        console.log({it});
        for (var i=0; i<it; i++) {
            // append slides to end
            if (e.direction=="left") {
                $('.carousel-item').eq(i).appendTo('.carousel-inner');
            }
            else {
                $('.carousel-item').eq(0).appendTo('.carousel-inner');
            }
        }
    }
});

  $('#carouselExample').carousel({
                interval: false,
        });

  $(document).ready(function() {
/* show lightbox when clicking a thumbnail */
    $('a.thumb').click(function(event){
      event.preventDefault();
      var content = $('.modal-body');
      content.empty();
        var title = $(this).attr("title");
        $('.modal-title').html(title);
        content.html($(this).html());
        $(".modal-profile").modal({show:true});
    });

  });


来源: stackexchange

问:
MySQL Workbench - Cant select FK column. Dropdown not populating
Here are my tables CREATE Statements:

CREATE TABLE `User` (
  `UserId` int NOT NULL AUTO_INCREMENT,
  `CompanyId` int NOT NULL,
  `FirstName` varchar(50) NOT NULL,
  `LastName` varchar(50) NOT NULL,
  `UserName` varchar(100) NOT NULL,
  PRIMARY KEY (`UserId`),
  KEY `FK_Company_User_idx` (`CompanyId`),
  CONSTRAINT `FK_Company_User` FOREIGN KEY (`CompanyId`) REFERENCES `Company` (`CompanyId`)
) ENGINE=InnoDB AUTO_INCREMENT=256 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `Notification` (
  `NotificationId` int NOT NULL AUTO_INCREMENT,
  `Email` varchar(100) DEFAULT NULL,
  `Message` text,
  `Subject` varchar(100) DEFAULT NULL,
  `UserId` int NOT NULL,
  PRIMARY KEY (`NotificationId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

I am trying to create a FK between UserId in Notification and UserId in User but the dropdown for selecting the field is not populating.

Any help is appreciated.

ContentLicense: CC BY-SA 4.0


问:
How do I resolve a backup restoration error
I am trying to reconstruct a website from backups. When I try to import the database content via PHPMyAdmin, I get the following error:

Fatal error: Uncaught TypeError: mb_strcut() expects parameter 1 to be string, bool given in /home/customer/public_html/phpmyadmin/libraries/classes/File.php:772 Stack trace: #0 /home/customer/public_html/phpmyadmin/libraries/classes/File.php(772): mb_strcut(false, 0, 32768) #1 /home/customer/public_html/phpmyadmin/libraries/classes/Import.php(432): PhpMyAdmin\File->read(32768) #2 /home/customer/public_html/phpmyadmin/libraries/classes/Plugins/Import/ImportSql.php(135): PhpMyAdmin\Import->getNextChunk(Object(PhpMyAdmin\File)) #3 /home/customer/public_html/phpmyadmin/libraries/classes/Controllers/ImportController.php(635): PhpMyAdmin\Plugins\Import\ImportSql->doImport(Object(PhpMyAdmin\File), Array) #4 /home/customer/public_html/phpmyadmin/libraries/classes/Routing.php(186): PhpMyAdmin\Controllers\ImportController->index(Array) #5 /home/customer/public_html/phpmyadmin/index.php(18): PhpMyAdmin\Routing::callControllerForRoute('/import', Object(FastRoute\Dispatcher\GroupCountBased), Object(Symfony\Component\DependencyInjecti in /home/customer/public_html/phpmyadmin/libraries/classes/File.php on line 772

I have looked everywhere to try and find how to overcome the problem, but so far, no joy.

Any help more than welcome.

We have tried importing on to two different hosting platforms (Plesk and Siteground's own).

Plesk produced an "unknown" Plesk version error.

Also tried importing a dump and importing directly via PHPMyAdmin. Dump did not recognise the file, PHPMyAdmin produced this error. We also tried to restore the back up without any luck. Finally, we tried to open the mySQL zip file directly but it is password protected.

Note we have no control of the file source, which is the only back up.
Note 2. I get the same import error when I try to import to Xampp local server


问:
Bamboo variables passed to function are incorrect
I have an environment object that is built via bamboo variables. When I run this runs against bamboo, environment.product is 'bar', but environment.foos is ['g'], when I would expect it to be ['a','b'], it's as if null or a invalid value is being passed to getFoos, but if that's the case why would product have the correct value?

Also, all the correct values are returned from the other functions (i.e. toBool, toNumber), so it's not like it's choking on the use of a function.

Why is this happening, or is there a way to simulate this, with the use of bamboo? I would have to push my code in a PR to get it to build with bamboo. If I use the local version of this file and hardcode the values instead of using #{bamboo.XXX}#, it works exactly as expected.

```<code>export const environment: Environment = {
    foos: getFoos('#{bamboo.productName}#'),
    product: '#{bamboo.productName}#',
    loggingOverride: LogLevel['#{bamboo.logLevelOverride}#'],
    production: true,
    debugMode: toBool('#{bamboo.debugMode}#'),
    version: '7.8.0-0',
    productURL: '#{bamboo.productUrl}#',
    seconds: toNumber('#{bamboo.seconds}#'),
    disableSplash: false,
    build: '#{bamboo.deploy.release}#',
    hash: '#{bamboo.deploy.release}#',
};

function toBool(tokenValue: string): boolean {
    return tokenValue === 'true';
}

function toNumber(tokenValue: string): number {
    return parseFloat(tokenValue);
}

function getFoos(product: string): string[] {
    switch (product) {
        case 'bar':
            return ['a','b'];
        case 'baz':
             return ['c', 'd'];
        case 'qux':
        case 'quux':
            return ['e', 'f'];
        default:
            return ['g'];
    }
}
</code>```

Body:
I have an environment object that is built via bamboo variables. When I run this runs against bamboo, environment.product is 'bar', but environment.foos is ['g'], when I would expect it to be ['a','b'], it's as if null or a invalid value is being passed to getFoos, but if that's the case why would product have the correct value?

Also, all the correct values are returned from the other functions (i.e. toBool, toNumber), so it's not like it's choking on the use of a function.

Why is this happening, or is there a way to simulate this, with the use of bamboo? I would have to push my code in a PR to get it to build with bamboo. If I use the local version of this file and hardcode the values instead of using #{bamboo.XXX}#, it works exactly as expected.

export const environment: Environment = {
    foos: getFoos('#{bamboo.productName}#'),
    product: '#{bamboo.productName}#',
    loggingOverride: LogLevel['#{bamboo.logLevelOverride}#'],
    production: true,
    debugMode: toBool('#{bamboo.debugMode}#'),
    version: '7.8.0-0',
    productURL: '#{bamboo.productUrl}#',
    seconds: toNumber('#{bamboo.seconds}#'),
    disableSplash: false,
    build: '#{bamboo.deploy.release}#',
    hash: '#{bamboo.deploy.release}#',
};

function toBool(tokenValue: string): boolean {
    return tokenValue === 'true';
}

function toNumber(tokenValue: string): number {
    return parseFloat(tokenValue);
}

function getFoos(product: string): string[] {
    switch (product) {
        case 'bar':
            return ['a','b'];
        case 'baz':
             return ['c', 'd'];
        case 'qux':
        case 'quux':
            return ['e', 'f'];
        default:
            return ['g'];
    }
}


问:
How to rename an array/vector automatically in R?
I wrote a (not pretty, but working) function to make one long vector from a certain column of my dataframe and add in a certain number of NA's every time the ID changes. Now what I am looking for is a possibility to automatically rename the variable array within the function so the output of the function carries an individual name (to make it easy to identify which values are in there and to prevent it from getting overwritten when running the function for a different column). One possibility would be to rename it with x or array_x. Now what I tried is several variations of this:

```<code>c("array_", as.character(x)) <- array
rm(array)
print(c("array_", as.character(x)))
</code>```

But it only throws errors- I assume because the string is not recognized as a variable name. Can anyone help me on solving this?

Here is some example data and the part of the function that is already running:

```<code>
ID <- c(rep ("A", 3), rep("B", 3))
Day <- c(1,2,3,1,2,3)
Score1 <- c(12,4, 16, 9, 12, 13)
Score2 <- c(1, 4, 4, 1, 3, 5)
Score3 <- c(23, 19, 12, 12, 24, 11)

df <- data.frame(ID, Day, Score1, Score2, Score3)
print(df)

foo <- function(x) {

array <- c(df[1,x])

for (i in 2:nrow(df))

{
  if (df[i, 1] == df[i-1, 1 ]) {
    array <- append (array, df[i, x])
  }
  else
  {
      array <- append (array, rep (NA, 5))
      array <- append (array, df[i, x])
  }
}
#rename array
print (array)
}

foo("Score1")

</code>```

Body:
I wrote a (not pretty, but working) function to make one long vector from a certain column of my dataframe and add in a certain number of NA's every time the ID changes. Now what I am looking for is a possibility to automatically rename the variable array within the function so the output of the function carries an individual name (to make it easy to identify which values are in there and to prevent it from getting overwritten when running the function for a different column). One possibility would be to rename it with x or array_x. Now what I tried is several variations of this:

c("array_", as.character(x)) <- array
rm(array)
print(c("array_", as.character(x)))

But it only throws errors- I assume because the string is not recognized as a variable name. Can anyone help me on solving this?

Here is some example data and the part of the function that is already running:

ID <- c(rep ("A", 3), rep("B", 3))
Day <- c(1,2,3,1,2,3)
Score1 <- c(12,4, 16, 9, 12, 13)
Score2 <- c(1, 4, 4, 1, 3, 5)
Score3 <- c(23, 19, 12, 12, 24, 11)

df <- data.frame(ID, Day, Score1, Score2, Score3)
print(df)

foo <- function(x) {

array <- c(df[1,x])

for (i in 2:nrow(df))

{
  if (df[i, 1] == df[i-1, 1 ]) {
    array <- append (array, df[i, x])
  }
  else
  {
      array <- append (array, rep (NA, 5))
      array <- append (array, df[i, x])
  }
}
#rename array
print (array)
}

foo("Score1")


问:
Hardware Acceleration for Headless Chrome on WSL2 Docker
my target is to server-side-render a frame of a WebGL2 application in a performant way.
To do so, I'm using Puppeteer with headless Chrome inside a Docker container running Ubuntu 20.04.4 on WSL2 on Windows 10 22H2.
However, I can't get any hardware acceleration to become active.
It seems that Chrome doesn't detect my Nvidia GTX1080 card, while on the host system with headless: false it's being used and increases render performance drastically.

I have followed the tutorial here to install the CUDA toolkit on WSL2.

A container spun up using sudo docker run --gpus all nvcr.io/nvidia/k8s/cuda-sample:nbody nbody -gpu -benchmark uses the GTX1080.

Running nvidia-smi inside the container shows the following:

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.65       Driver Version: 527.37       CUDA Version: 12.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  On   | 00000000:01:00.0  On |                  N/A |
| N/A   49C    P8    10W /  N/A |    871MiB /  8192MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
</code>```

Using flags like

```<code>--ignore-gpu-blocklist
--enable-gpu-rasterization
--enable-zero-copy
--use-gl=desktop / --use-gl=egl
</code>```

did not solve the problem.

I also tried libosmesa6 with --use-gl=osmesa which had no effect.

I'm starting my container with docker-compose including the following section into the service's block:

```<code>deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
</code>```

Chrome version is HeadlessChrome/108.0.5351.0.
The Chrome WebGL context's WEBGL_debug_renderer_info tells me
vendor: Google Inc. (Google)
renderer: ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)

Visiting chrome://gpu with Puppeteer shows me the following:
enter image description here

Any ideas what might still be missing to have Chrome use the GPU for hardware acceleration?

Body:
my target is to server-side-render a frame of a WebGL2 application in a performant way.
To do so, I'm using Puppeteer with headless Chrome inside a Docker container running Ubuntu 20.04.4 on WSL2 on Windows 10 22H2.
However, I can't get any hardware acceleration to become active.
It seems that Chrome doesn't detect my Nvidia GTX1080 card, while on the host system with headless: false it's being used and increases render performance drastically.

I have followed the tutorial here to install the CUDA toolkit on WSL2.

A container spun up using sudo docker run --gpus all nvcr.io/nvidia/k8s/cuda-sample:nbody nbody -gpu -benchmark uses the GTX1080.

Running nvidia-smi inside the container shows the following:

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.65       Driver Version: 527.37       CUDA Version: 12.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  On   | 00000000:01:00.0  On |                  N/A |
| N/A   49C    P8    10W /  N/A |    871MiB /  8192MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|

Using flags like

--ignore-gpu-blocklist
--enable-gpu-rasterization
--enable-zero-copy
--use-gl=desktop / --use-gl=egl

did not solve the problem.

I also tried libosmesa6 with --use-gl=osmesa which had no effect.

I'm starting my container with docker-compose including the following section into the service's block:

deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]

Chrome version is HeadlessChrome/108.0.5351.0.
The Chrome WebGL context's WEBGL_debug_renderer_info tells me
vendor: Google Inc. (Google)
renderer: ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)

Visiting chrome://gpu with Puppeteer shows me the following:
enter image description here

Any ideas what might still be missing to have Chrome use the GPU for hardware acceleration?


问:
splunk HEC endpoint is execting priv key
when interacting HEC endpoint even priv key is expected ?

dr % curl --cert splunkserverdefaultcert-chain.crt https://-splunkhec.:8088/services/collector
curl: (58) unable to set private key file: 'splunkserverdefaultcert-chain.crt' type PEM

splunkserverdefaultcert-chain.crt -- is downloaded from https://-splunkhec.:8088/services/collector .

Why is the priv key needed to interact with HEC endpoint on splunk

I am expecting to be able interact with only certificate  chain


问:
Sentiment analysis with respect to subject? (Python)
I am looking to do infer sentiment in  simple and short sentences.
They are of the form:

"A is bad. B is good"

(The form is not always like this, but its the general idea)

I need to be able to identify if A is bad.

Thank you!


问:
I don't know what is the problem unfortunately
I'm trying to send a word by clicking the button next to that word to a different html page using socket connection. I'm trying to learn socket, and I haven't learnt anything yet. It doesn't do anything that shows up when I click the button.

This is my 1st html page that has the buttons to send the word next to the button.

```<code><html>

<head>
  <script src="/node_modules/socket.io/client-dist/socket.io.js"></script>
</head>
<table>
  <tr>

    <td id="word1">Word 1</td>
    <td><button id="button1">Word 1</button></td>

    <td id="word2">Word 2</td>
    <td><button id="button2">Word 2</button></td>

    <td id="word3">Word 3</td>
    <td><button id="button3">Word 3</button></td>

    <td id="word4">Word 4</td>
    <td><button id="button4">Word 4</button></td>

    <td id="word5">Word 5</td>
    <td><button id="button5">Word 5</button></td>

    <td id="word6">Word 6</td>
    <td><button id="button6">Word 6</button></td>
  </tr>
</table>
<script>
  // Initialize the socket
  var socket = io();

  // Get a reference to the buttons and words
  var button1 = document.getElementById("button1");
  var button2 = document.getElementById("button2");
  var button3 = document.getElementById("button3");
  var button4 = document.getElementById("button4");
  var button5 = document.getElementById("button5");
  var button6 = document.getElementById("button6");
  var word1 = document.getElementById("word1");
  var word2 = document.getElementById("word2");
  var word3 = document.getElementById("word3");
  var word4 = document.getElementById("word4");
  var word5 = document.getElementById("word5");
  var word6 = document.getElementById("word6");

  // Create a function to handle the click event
  function handleClick(button, word) {
    button.addEventListener("click", function () {
      // Get the text of the word
      var text = word.textContent;

      // Use the socket to send the text to the new page
      socket.emit("send-word", text);
    });
  }

  // Attach an event listener to each button
  handleClick(button1, word1);
  handleClick(button2, word2);
  handleClick(button3, word3);
  handleClick(button4, word4);
  handleClick(button5, word5);
  handleClick(button6, word6);
</script>

</html>
</code>```

This is the page that must be receive the word and display it.

```<code><html>
  <head>
    <title>My New Page</title>
    <script src="/node_modules/socket.io/client-dist/socket.io.js"></script>
  </head>
  <body>
    <div id="word-container">Selam</div>

    <script>
      // Initialize the socket
      var socket = io();

      // Listen for the "send-word" event
      socket.on("send-word", function(text) {
        // Get a reference to the word container
        var container = document.getElementById("word-container");

        // Update the container with the received text
        container.textContent = text;
      });
    </script>
  </body>
</html>

</code>```

It may be so simple to solve this problem, but I'm kinda new into coding and socket.
This is my first post in stack overflow also so if I have done anything wrong, sorry :)

Body:
I'm trying to send a word by clicking the button next to that word to a different html page using socket connection. I'm trying to learn socket, and I haven't learnt anything yet. It doesn't do anything that shows up when I click the button.

This is my 1st html page that has the buttons to send the word next to the button.

    Word 1
    <button id="button1">Word 1</button>

    Word 2
    <button id="button2">Word 2</button>

    Word 3
    <button id="button3">Word 3</button>

    Word 4
    <button id="button4">Word 4</button>

    Word 5
    <button id="button5">Word 5</button>

    Word 6
    <button id="button6">Word 6</button>

This is the page that must be receive the word and display it.

    <title>My New Page</title>

Selam

It may be so simple to solve this problem, but I'm kinda new into coding and socket.
This is my first post in stack overflow also so if I have done anything wrong, sorry :)


问:
OAI-PMH - creation of endpoint
I would like to create an oai-pmh endpoint to publish metadata to. However, I'm having a little trouble seeing how to do it. I see that several solutions are available to me via Dspace or Fedora. But I would like to create it myself in python, do you know any modules that can do this? Because I found the pyoai module but it's more for harvesting than for publishing.</p>

Title: OAI-PMH - creation of endpoint


问:
Azure Logic App Standard - Some of the connections are not authorized yet
I'm creating a logic apps standard workflow hosted in an ase v3. I have the built-in file system connector to collect from an on-prem file share. I was able to create the workflow in the azure portal. However, when I return to it and click save I get the following message:

Some of the connections are not authorized yet. If you just created a
workflow from a template, please add the authorized connections to
your workflow before saving

The code for the workflow is shown below:

{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "Copy_file": {
                "inputs": {
                    "parameters": {
                        "destination": "destination_path_here",
                        "source": "@triggerOutputs()?['body']?['path']"
                    },
                    "serviceProviderConfiguration": {
                        "connectionName": "FileSystem",
                        "operationId": "copyFile",
                        "serviceProviderId": "/serviceProviders/FileSystem"
                    }
                },
                "runAfter": {},
                "type": "ServiceProvider"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "triggers": {
            "When_a_file_is_added": {
                "conditions": [
                    {
                        "expression": "@not(equals(triggerBody().Size,0))"
                    }
                ],
                "inputs": {
                    "parameters": {
                        "folderPath": "source_path_here"
                    },
                    "serviceProviderConfiguration": {
                        "connectionName": "FileSystem",
                        "operationId": "whenFilesAreAdded",
                        "serviceProviderId": "/serviceProviders/FileSystem"
                    }
                },
                "kind": "Polling",
                "recurrence": {
                    "frequency": "Second",
                    "interval": 15
                },
                "splitOn": "@triggerOutputs()?['body']",
                "type": "ServiceProvider"
            }
        }
    },
    "kind": "Stateful"
}
```


问:
Apache Flink REST API
Apache Flink provides a set of Rest API. When my flink job is running, I tried to access the job using /jobs and it gave me the metadata information. When i tried to fetch the results using /job/:jobid/execution-result, I got the result as {status: "RUNNING"}. Upon stopping I get the response as

{
"status": {
"id": "COMPLETED"
},
"job-execution-result": {
"id": jobid,
"application-status": "CANCELED",
"accumulator-results": {},
"net-runtime": 1872358
}
}

Is there a way I can get the results that get printed on flink std out using any other API calls?

Title: Apache Flink REST API


问:
Java fabric8 kubernetes client to get the name of the deployed kubernetes pod's cluster
I want to use fabric8 kubernetes client (java) inside a pod to obtain the cluster it is deployed on.

Currently, I can obtain the context using:

```<code>KubernetesClient client = new DefaultKubernetesClient();
return client.getConfiguration();
</code>```

When running locally, I can see the current kubernetes context. However, when it is run on the deployed pod, I am unable to see the kubernetes context.

Why is it not working on the deployed pod? How can I detect the kubernetes cluster the pod is deployed on?

Body:
I want to use fabric8 kubernetes client (java) inside a pod to obtain the cluster it is deployed on.

Currently, I can obtain the context using:

KubernetesClient client = new DefaultKubernetesClient();
return client.getConfiguration();

When running locally, I can see the current kubernetes context. However, when it is run on the deployed pod, I am unable to see the kubernetes context.

Why is it not working on the deployed pod? How can I detect the kubernetes cluster the pod is deployed on?


问:
_RemoteTraceback,, fit_prophet(weather)
I want to make a model based on weather data using prophet.
Unfortunately, I got this error: Exception: Less than two datapoints before cutoff. Increase initial window.

thank you in advance

my script:
from prophet.diagnostics import cross_validation

m = fit_prophet(weather)
cv = cross_validation(m, initial=f'{365 * 6} days', period='10 days', horizon='10 days', parallel="processes")

and the error:

```<code>_RemoteTraceback                          Traceback (most recent call last)
_RemoteTraceback:
"""
</code>```

...

```<code>Exception: Less than two datapoints before cutoff. Increase initial window.

</code>```

I changed the number of (initial=f'{365 * 4} days', period='100 days', horizon='100 days) again and again, but it didn't solve.
Would anyone help me to fix that?

Title: _RemoteTraceback,, fit_prophet(weather)

Body:
I want to make a model based on weather data using prophet.
Unfortunately, I got this error: Exception: Less than two datapoints before cutoff. Increase initial window.

thank you in advance

my script:
from prophet.diagnostics import cross_validation

m = fit_prophet(weather)
cv = cross_validation(m, initial=f'{365 * 6} days', period='10 days', horizon='10 days', parallel="processes")

and the error:

_RemoteTraceback                          Traceback (most recent call last)
_RemoteTraceback:
"""

...

Exception: Less than two datapoints before cutoff. Increase initial window.

I changed the number of (initial=f'{365 * 4} days', period='100 days', horizon='100 days) again and again, but it didn't solve.
Would anyone help me to fix that?


问:
Phishing alert on github-pages
could anyone help me ?
I have twenty alerts on my github.io using github pages, and I don't know what to do to resolve this, I made a clone of the instagram page, and now I have this alert,
check the url: https://luuan11.github.io/instagram-login-page/
On virusTotal: https://www.virustotal.com/gui/url-analysis/u-e8f3c7032425be44a9a55a75bc2be1e55bc00b77ac4c257ea6371f605c5c86d6-1670341085

Something to remove this alerts

Title: Phishing alert on github-pages


问:
Distance of nearest cell having
Given a binary grid of n*m. Find the distance of the nearest 1 in the grid for each cell.
The distance is calculated as |i1  - i2| + |j1 - j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1.</p>
```<code>Input: grid = {{0,1,1,0},{1,1,0,0},{0,0,1,1}}
Output: {{1,0,0,1},{0,0,1,1},{1,1,0,0}}
Explanation: The grid is-
0 1 1 0
1 1 0 0
0 0 1 1
0's at (0,0), (0,3), (1,2), (1,3), (2,0) and
(2,1) are at a distance of 1 from 1's at (0,1),
(0,2), (0,2), (2,3), (1,0) and (1,1)
respectively.

</code>```

Title: Distance of nearest cell having

Body:
Given a binary grid of n*m. Find the distance of the nearest 1 in the grid for each cell.
The distance is calculated as |i1  - i2| + |j1 - j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1.

Input: grid = {{0,1,1,0},{1,1,0,0},{0,0,1,1}}
Output: {{1,0,0,1},{0,0,1,1},{1,1,0,0}}
Explanation: The grid is-
0 1 1 0
1 1 0 0
0 0 1 1
0's at (0,0), (0,3), (1,2), (1,3), (2,0) and
(2,1) are at a distance of 1 from 1's at (0,1),
(0,2), (0,2), (2,3), (1,0) and (1,1)
respectively.


问:
ValueError at /create_post/
When I click the Create New Post button, I get this error.

The service.views.create_post view did not return an HttpResponse
object. Instead, it returned None.

views.py

```<code>    @login_required
    @permission_required("service.add_post")
    def create_post(req):
    form = PostForm()
    if req.method == "POST":
        form = PostForm(req.POST)
        if form.is_valid():
            form.save()
            title = form.cleaned_data.get("title")
            if title != "POST":
                messages.error(req, f"Something went wrong")
                return redirect('index')
            id = form.cleaned_data.get("pk")
            messages.success(req, f"Post {title} was created successfully")
            return redirect('index')
        return render(req, "create_post.html", {"form":form})
</code>```

Nothing because I don't understand the error

Title: ValueError at /create_post/

Body:
When I click the Create New Post button, I get this error.

The service.views.create_post view did not return an HttpResponse
object. Instead, it returned None.

views.py

    @login_required
    @permission_required("service.add_post")
    def create_post(req):
    form = PostForm()
    if req.method == "POST":
        form = PostForm(req.POST)
        if form.is_valid():
            form.save()
            title = form.cleaned_data.get("title")
            if title != "POST":
                messages.error(req, f"Something went wrong")
                return redirect('index')
            id = form.cleaned_data.get("pk")
            messages.success(req, f"Post {title} was created successfully")
            return redirect('index')
        return render(req, "create_post.html", {"form":form})

Nothing because I don't understand the error


问:
Jest test: how to write a test suite correctly?
I have a function 'getWeather' at App.tsx.

```<code>
const App: React.FC<any> = () => {

  // get and set value from search field
  const [myCity, setMyCity] = useState<string>('');

  const getCity = (e: any): void => {
    e.preventDefault();
    const target = e.target;
    setMyCity(target.city.value.trim());
  };

  const [weatherData, setWeatherData] = useState({
  } as IWeatherDataObj);

  const getWeather = (myCity: string) => {

    const cityUrl = `https://api.openweathermap.org/data/2.5/weather?q=${myCity}&lang=en&appid=${API_KEY}&units=metric`;

    fetch(cityUrl)
      .then((response) => response.json())
      .then((data) => setWeatherData({
        name: data.name,
        country: data.sys.country,
        wind: data.wind.speed,
        clouds: data.weather[0].description,
        temp: Math.round(data.main.temp),
        feels_like: Math.round(data.main.feels_like),
        pressure: data.main.pressure,
        humidity: data.main.humidity,
        icon: data.weather[0].icon,
        error: undefined
      }))
      .catch((error) =>
        error.response === undefined &&
        setWeatherData({
          name: undefined,
          country: undefined,
          wind: undefined,
          clouds: undefined,
          temp: undefined,
          feels_like: undefined,
          pressure: undefined,
          humidity: undefined,
          icon: undefined,
          error: `City "${myCity}" is not found`
        })
      );
  };

  useEffect(() => {
    getWeather('Prague');
  }, [])
</code>```

And I have an App.test.tsx where I try to mock the server response:

```<code>const MOCK_WEATHER = [{ "coord": { "lon": 14.4208, "lat": 50.088 }, "weather": [{ "id": 804, "main": "Clouds", "description": "overcast clouds", "icon": "04d" }], "base": "stations", "main": { "temp": 4.23, "feels_like": -0.55, "temp_min": 2.93, "temp_max": 6.11, "pressure": 1013, "humidity": 92 }, "visibility": 10000, "wind": { "speed": 7.2, "deg": 240 }, "clouds": { "all": 100 }, "dt": 1670327256, "sys": { "type": 2, "id": 2010430, "country": "CZ", "sunrise": 1670309138, "sunset": 1670338875 }, "timezone": 3600, "id": 3067696, "name": "Prague", "cod": 200 }]
</code>```

And I have to test that during the first render the weatherData object will contain the "weatherData.name" field (it means getWeather function works correctly).

But I have no idea how to run getWeather inside of App.test.tsx, get the 'server response' and add the values from the response to weatherData.

Shotrly, help me to write a test :)

Body:
I have a function 'getWeather' at App.tsx.

const App: React.FC<any> = () => {

  // get and set value from search field
  const [myCity, setMyCity] = useState<string>('');

  const getCity = (e: any): void => {
    e.preventDefault();
    const target = e.target;
    setMyCity(target.city.value.trim());
  };

  const [weatherData, setWeatherData] = useState({
  } as IWeatherDataObj);

  const getWeather = (myCity: string) => {

    const cityUrl = `https://api.openweathermap.org/data/2.5/weather?q=${myCity}&lang=en&appid=${API_KEY}&units=metric`;

    fetch(cityUrl)
      .then((response) => response.json())
      .then((data) => setWeatherData({
        name: data.name,
        country: data.sys.country,
        wind: data.wind.speed,
        clouds: data.weather[0].description,
        temp: Math.round(data.main.temp),
        feels_like: Math.round(data.main.feels_like),
        pressure: data.main.pressure,
        humidity: data.main.humidity,
        icon: data.weather[0].icon,
        error: undefined
      }))
      .catch((error) =>
        error.response === undefined &&
        setWeatherData({
          name: undefined,
          country: undefined,
          wind: undefined,
          clouds: undefined,
          temp: undefined,
          feels_like: undefined,
          pressure: undefined,
          humidity: undefined,
          icon: undefined,
          error: `City "${myCity}" is not found`
        })
      );
  };

  useEffect(() => {
    getWeather('Prague');
  }, [])

And I have an App.test.tsx where I try to mock the server response:

const MOCK_WEATHER = [{ "coord": { "lon": 14.4208, "lat": 50.088 }, "weather": [{ "id": 804, "main": "Clouds", "description": "overcast clouds", "icon": "04d" }], "base": "stations", "main": { "temp": 4.23, "feels_like": -0.55, "temp_min": 2.93, "temp_max": 6.11, "pressure": 1013, "humidity": 92 }, "visibility": 10000, "wind": { "speed": 7.2, "deg": 240 }, "clouds": { "all": 100 }, "dt": 1670327256, "sys": { "type": 2, "id": 2010430, "country": "CZ", "sunrise": 1670309138, "sunset": 1670338875 }, "timezone": 3600, "id": 3067696, "name": "Prague", "cod": 200 }]

And I have to test that during the first render the weatherData object will contain the "weatherData.name" field (it means getWeather function works correctly).

But I have no idea how to run getWeather inside of App.test.tsx, get the 'server response' and add the values from the response to weatherData.

Shotrly, help me to write a test :)


问:
how to implement signals handler in pytest
Is it possible to execute following example with pytest tests?

I have 2 devices, and two different tests are running simultaneously on each

FYI. I'm trying to do it due to save time, I already can run Test B after Test A with the desired var, however I need that var in the end phase of test B, so if it's possible Test B could wait for end of Test A and then continue after receiving that var.

Thanks in advance!

Device A

Test A

Do something

send var to test B

Device B

Test B

Do something

Wait for var from test A

Do something


问:
How to fix Tcl_WaitForEvent: unable to start notifier thread error?
Running a Python3 Tkinter application through docker I get a message as soon as I run the docker command:

tkinter_app.py:

```<code>from tkinter import *

ws = Tk()
ws.title('App')

title_lbl = Label(ws, text="TK APP")
title_lbl.pack()

if __name__ == '__main__':
    ws.mainloop()
</code>```

Command:

```<code>[root]$ docker run -it --rm -e DISPLAY=unix$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix -v /home/path:/home/path --name tkinter_application docker_python_image python3 /home/path/tkinter_app.py
Tcl_WaitForEvent: unable to start notifier thread
[root]$
</code>```

docker version 20.10.21

docker os: Ubuntu

python version 3.10.6

os version RHEL 7

I don't get that error when I run with a different docker image that contains python version 3.10.0 in my current development environment.

I have tried using this image (with python 3.10.6) in another environment with a RHEL8 system and it also works.

Between python v3.10.0 and v3.10.6 there is no difference in code that affects the tkinter module. Feels more like a docker issue.

Body:
Running a Python3 Tkinter application through docker I get a message as soon as I run the docker command:

tkinter_app.py:

from tkinter import *

ws = Tk()
ws.title('App')

title_lbl = Label(ws, text="TK APP")
title_lbl.pack()

if __name__ == '__main__':
    ws.mainloop()

Command:

[root]$ docker run -it --rm -e DISPLAY=unix$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix -v /home/path:/home/path --name tkinter_application docker_python_image python3 /home/path/tkinter_app.py
Tcl_WaitForEvent: unable to start notifier thread
[root]$

docker version 20.10.21

docker os: Ubuntu

python version 3.10.6

os version RHEL 7

I don't get that error when I run with a different docker image that contains python version 3.10.0 in my current development environment.

I have tried using this image (with python 3.10.6) in another environment with a RHEL8 system and it also works.

Between python v3.10.0 and v3.10.6 there is no difference in code that affects the tkinter module. Feels more like a docker issue.


问:
Intellij IDEA CE + Spring Boot + Smart Tomcat with hot reload : how to?
I have a Spring Boot app + Intellij IDEA + Smart Tomcat plugin dev environment.

Whenever I change backend or frontend (WebContent folder) related code, I would like to trigger an auto-reload and have the Smart Tomcat deployment refreshed.

How can I achieve that?

Thank you for your help.


问:
React Native Geolocation.watchPosition not working in Android emulator
It's crucial for me to have location updates and emulation of a route in the android emulator. But all I get is a single update on the map and nothing more.

Can't seem to find any good examples of "watchPosition" using functional components.

What am I missing? Here's some of the code I'm using:

...

import Geolocation from "@react-native-community/geolocation";

...

  useEffect(() => {

    const watchId = Geolocation.watchPosition(
      handlePosition,
      handlePositionError,
      geoConfig
    );

    return () => Geolocation.clearWatch(watchId);

  }, []);

  const geoConfig = {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 1000,
  };

  const handlePosition = info => {
    console.log("getting position");
    setMyLocation({
      latitude: info.coords.latitude,
      longitude: info.coords.longitude,
      latitudeDelta: latitudeDelta,
      longitudeDelta: longitudeDelta,
    });
    if (isMine) {
      const position = {
        latitude: info.coords.latitude,
        longitude: info.coords.longitude,
      };
      updateRideDriverPosition(ride.rideId, position, () =>
        console.log("Yay! position updated")
      );
    } else {
      (async () =>
        await getRideById(ride.rideId).then(item => {
          setCarLocation({
            latitude: item.position.latitude,
            longitude: item.position.longitude,
          });
        }))();
    }
  };

  const handlePositionError = error => console.log(new Date(), error);

...
```

I tried to just use "getPosition" inside an interval and that worked fine, also the google maps app works fine and updates the location the whole route I configured.

How can I get continuous responses with new locations?

Body:
It's crucial for me to have location updates and emulation of a route in the android emulator. But all I get is a single update on the map and nothing more.

Can't seem to find any good examples of "watchPosition" using functional components.

What am I missing? Here's some of the code I'm using:

...

import Geolocation from "@react-native-community/geolocation";

...

  useEffect(() => {

    const watchId = Geolocation.watchPosition(
      handlePosition,
      handlePositionError,
      geoConfig
    );

    return () => Geolocation.clearWatch(watchId);

  }, []);

  const geoConfig = {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 1000,
  };

  const handlePosition = info => {
    console.log("getting position");
    setMyLocation({
      latitude: info.coords.latitude,
      longitude: info.coords.longitude,
      latitudeDelta: latitudeDelta,
      longitudeDelta: longitudeDelta,
    });
    if (isMine) {
      const position = {
        latitude: info.coords.latitude,
        longitude: info.coords.longitude,
      };
      updateRideDriverPosition(ride.rideId, position, () =>
        console.log("Yay! position updated")
      );
    } else {
      (async () =>
        await getRideById(ride.rideId).then(item => {
          setCarLocation({
            latitude: item.position.latitude,
            longitude: item.position.longitude,
          });
        }))();
    }
  };

  const handlePositionError = error => console.log(new Date(), error);

...

I tried to just use "getPosition" inside an interval and that worked fine, also the google maps app works fine and updates the location the whole route I configured.

How can I get continuous responses with new locations?


问:
How to implement the creation of Background-tasks or services for a specific user?
In my ASP.Net Core with MVC (Razorpages) I want to be able to let users click on a 'START' button which in the backend should start a (potentially long-running) background task or service.

It should occasionally send updates to the UI for that user. Probably through some JS/AJAX request.
The user, while being on that page, should receive those updates and see them on-screen.
It is important that updates are not shared across all users (hence wanting to create the background-service for a specific user).
Also when the user navigates to a different page and navigates back, it should still keep updating from the same background-service/thread.

My own 2 cents
My first instinct is that I should keep track of the user's ID within the background-task, so I can retrieve the background-service that belongs to a specific user and receive updates when the user is on the correct page.

However, the way I have implemented this seems like a big code smell and I do not fully understand how to actually update the user's UI with it... I seem to be stuck.

My question
I was wondering if others may have ideas on how to successfully implement the creation of Background-tasks or services for a specific user? Or that maybe I am missing something obvious I haven't thought of myself. Anybody any ideas?

Thanks!

What I tried was the following.

I created a background service:

```<code>    public class SomeService : IHostedService
    {
        private Guid _userId;

        public EventHandler UpdateUiEvent;

        public void SetUserId(Guid userId)
        {
            _userId = userId;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                // Do stuff on a loop
                UpdateUI();
                await Task.Delay(1000, cancellationToken);
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }

        private void UpdateUI()
        {
            EventArgs eventArgs = new EventArgs();
            UpdateUiEvent?.Invoke(this, eventArgs);
        }
    }
</code>```

Secondly I have a controller with an action which starts the service when a user calls the method 'StartServiceForUser' from the Razor-page (AJAX):

```<code>public class SomeController : Controller
{
    private readonly ILogger<SomeController> _logger;
    private readonly IServiceProvider _serviceProvider;

    public SomeController(ILogger<SomeController> logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;

    }

    /// <summary>
    /// Called from AJAX-request in Razor-page UI.
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public async Task<IActionResult> StartServiceForUser(Guid userId, CancellationToken cancellationToken)
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var service = scope.ServiceProvider.GetService<SomeService>();
            if (service == null) throw new Exception("Service is null.");

            service.SetUserId(userId);
            service.UpdateUiEvent += OnUiUpdated;

            await service.StartAsync(cancellationToken);
        }

        return Ok("Service has started");
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

    /// <summary>
    /// Called when the UpdateUI event is fired in the 'SomeService' class.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnUiUpdated(object? sender, EventArgs e)
    {
        // How will I push this update to the user?
    }
}
</code>```

As seen in the comment of the OnUiUpdated method, I do not understand how to proceed further...
How will I push this update to the user?
I have the feeling I am doing something completely wrong and do not know how else to get my head around this problem. Any help is appreciated!

Edit 1 somebody suggested in the comments I should take a look at SignalR for client-server communication. This helps, however does not yet solve the problem of having a long-running (or continuous-running) operation and updating the UI regularly.

Body:
In my ASP.Net Core with MVC (Razorpages) I want to be able to let users click on a 'START' button which in the backend should start a (potentially long-running) background task or service.

It should occasionally send updates to the UI for that user. Probably through some JS/AJAX request.
The user, while being on that page, should receive those updates and see them on-screen.
It is important that updates are not shared across all users (hence wanting to create the background-service for a specific user).
Also when the user navigates to a different page and navigates back, it should still keep updating from the same background-service/thread.

My own 2 cents
My first instinct is that I should keep track of the user's ID within the background-task, so I can retrieve the background-service that belongs to a specific user and receive updates when the user is on the correct page.

However, the way I have implemented this seems like a big code smell and I do not fully understand how to actually update the user's UI with it... I seem to be stuck.

My question
I was wondering if others may have ideas on how to successfully implement the creation of Background-tasks or services for a specific user? Or that maybe I am missing something obvious I haven't thought of myself. Anybody any ideas?

Thanks!

What I tried was the following.

I created a background service:

    public class SomeService : IHostedService
    {
        private Guid _userId;

        public EventHandler UpdateUiEvent;

        public void SetUserId(Guid userId)
        {
            _userId = userId;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                // Do stuff on a loop
                UpdateUI();
                await Task.Delay(1000, cancellationToken);
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }

        private void UpdateUI()
        {
            EventArgs eventArgs = new EventArgs();
            UpdateUiEvent?.Invoke(this, eventArgs);
        }
    }

Secondly I have a controller with an action which starts the service when a user calls the method 'StartServiceForUser' from the Razor-page (AJAX):

public class SomeController : Controller
{
    private readonly ILogger<SomeController> _logger;
    private readonly IServiceProvider _serviceProvider;

    public SomeController(ILogger<SomeController> logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;

    }

    ///
    /// Called from AJAX-request in Razor-page UI.
    ///
    /// <returns></returns>
    [HttpPost]
    public async Task<IActionResult> StartServiceForUser(Guid userId, CancellationToken cancellationToken)
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var service = scope.ServiceProvider.GetService<SomeService>();
            if (service == null) throw new Exception("Service is null.");

            service.SetUserId(userId);
            service.UpdateUiEvent += OnUiUpdated;

            await service.StartAsync(cancellationToken);
        }

        return Ok("Service has started");
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

    ///
    /// Called when the UpdateUI event is fired in the 'SomeService' class.
    ///
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnUiUpdated(object? sender, EventArgs e)
    {
        // How will I push this update to the user?
    }
}

As seen in the comment of the OnUiUpdated method, I do not understand how to proceed further...
How will I push this update to the user?
I have the feeling I am doing something completely wrong and do not know how else to get my head around this problem. Any help is appreciated!

Edit 1 somebody suggested in the comments I should take a look at SignalR for client-server communication. This helps, however does not yet solve the problem of having a long-running (or continuous-running) operation and updating the UI regularly.


问:
Exception error when I try to run the start of my javaFxApplication
I need to make an application in JavaFX while using scene builder to make the lay-out (in Intellij). but when I try to run the application "javaFxApplication" (so it will call the first fxml file (made in scenebuilder) and show the startscreen, it throws again and again an exception. I have no idea how to solve this and can't so test and run the application/site... I also don't see where the error is. The VM options and libraries are added. Does someaone knows how to solve this  and can help me out? Thank you

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3324)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3287)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3255)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3227)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3203)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3196)
    at gui.JavaFXApplication.start(JavaFXApplication.java:17)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
    at javafx.graphics@19/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
    at javafx.graphics@19/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@19/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
    at javafx.graphics@19/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    ... 1 more
Exception running application gui.JavaFXApplication
</code>```

this is the error I get when i run the following:

```<code>package gui;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class JavaFXApplication extends Application {

        @Override
        public void start(Stage stage) throws IOException {

            Parent root = FXMLLoader.load(getClass().getResource("src/misproject23/StartScreen.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

           /* FXMLLoader loader = new FXMLLoader(getClass().getResource("com/example/misproject23/StartScreen.fxml"));
            Parent root = loader.load();

            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();*/

        }

        public static void main(String[] args) {
            launch(args);
        }

    }

</code>```

Body:
I need to make an application in JavaFX while using scene builder to make the lay-out (in Intellij). but when I try to run the application "javaFxApplication" (so it will call the first fxml file (made in scenebuilder) and show the startscreen, it throws again and again an exception. I have no idea how to solve this and can't so test and run the application/site... I also don't see where the error is. The VM options and libraries are added. Does someaone knows how to solve this  and can help me out? Thank you

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3324)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3287)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3255)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3227)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3203)
    at javafx.fxml@19/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3196)
    at gui.JavaFXApplication.start(JavaFXApplication.java:17)
    at javafx.graphics@19/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
    at javafx.graphics@19/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
    at javafx.graphics@19/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@19/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
    at javafx.graphics@19/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    ... 1 more
Exception running application gui.JavaFXApplication

this is the error I get when i run the following:

package gui;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class JavaFXApplication extends Application {

        @Override
        public void start(Stage stage) throws IOException {

            Parent root = FXMLLoader.load(getClass().getResource("src/misproject23/StartScreen.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

           /* FXMLLoader loader = new FXMLLoader(getClass().getResource("com/example/misproject23/StartScreen.fxml"));
            Parent root = loader.load();

            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();*/

        }

        public static void main(String[] args) {
            launch(args);
        }

    }


问:
Play Lottie animation with a different delay when in viewport
I want to play lottie animations in a section with a  delay when they enter the viewport - how would I do that?

I tried this code from the interacitivty lottie library but it didnt work:

HTML:

  <lottie-player id="lead" src="https://lottie.host/9af8230c-e744-48d9-b2d4-1aff06e464b8/tykFOU2onq.json" background="#ffffff" speed="1" style="width: 100%; height: 50vh;" autoplay></lottie-player>```
</div>
</div>
</p>
<p>JS:</p>
<pre class="lang-css prettyprint-override"><code><script>
LottieInteractivity.create({
    player: '#lead',
    mode: 'scroll',
    actions: [
        {
            visibility[0.1,1],
            type: 'seek',
            frames: [0, 300],
        },
    ]
});
</script>
</code>```

Body:
I want to play lottie animations in a section with a  delay when they enter the viewport - how would I do that?

I tried this code from the interacitivty lottie library but it didnt work:

HTML:

  <lottie-player id="lead" src="https://lottie.host/9af8230c-e744-48d9-b2d4-1aff06e464b8/tykFOU2onq.json" background="#ffffff" speed="1" style="width: 100%; height: 50vh;" autoplay></lottie-player>

JS:


问:
Error: org.apache.spark.SparkException: Job aborted. in pyspark
I am segregating my pyspark dataframe based on multiple columns using the following code

```<code>data.write.option("header",True).partitionBy("Col1","Col2","Col3","Col4").mode("overwrite").csv("/../")
</code>```

When I segregate by 2 columns, it works but when I mention more than 2 columns, Its stopping by showing the error : 'org.apache.spark.SparkException: Job aborted'. Can anyone please tell me how to do it?

Body:
I am segregating my pyspark dataframe based on multiple columns using the following code

data.write.option("header",True).partitionBy("Col1","Col2","Col3","Col4").mode("overwrite").csv("/../")

When I segregate by 2 columns, it works but when I mention more than 2 columns, Its stopping by showing the error : 'org.apache.spark.SparkException: Job aborted'. Can anyone please tell me how to do it?


问:
aiplatform.PipelineJob.submit() fails due to ServiceUnavailable: 503 failed to connect to all addresses
Trying to run a PipelineJob from local instance (local machine with windows, GCP CLI installed /local jupyter lab), but I'm getting

```<code>_InactiveRpcError                         Traceback (most recent call last)

The above exception was the direct cause of the following exception:

ServiceUnavailable                        Traceback (most recent call last)
~\AppData\Local\Temp\1\ipykernel_8896\1564544395.py in <module>
     15 #credentials=CREDENTIALS,
     16
---> 17 job.submit() #service_account=SERVICE_ACCOUNT
     18 # job.run()

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\cloud\aiplatform\pipeline_jobs.py in submit(self, service_account, network)
    284             parent=self._parent,
    285             pipeline_job=self._gca_resource,
--> 286             pipeline_job_id=self.job_id,
    287         )
    288

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\cloud\aiplatform_v1\services\pipeline_service\client.py in create_pipeline_job(self, request, parent, pipeline_job, pipeline_job_id, retry, timeout, metadata)
   1197
   1198         # Send the request.
-> 1199         response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
   1200
   1201         # Done; return the response.

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\api_core\gapic_v1\method.py in __call__(self, timeout, retry, *args, **kwargs)
    152             kwargs["metadata"] = metadata
    153
--> 154         return wrapped_func(*args, **kwargs)
    155
    156

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\api_core\grpc_helpers.py in error_remapped_callable(*args, **kwargs)
     66             return callable_(*args, **kwargs)
     67         except grpc.RpcError as exc:
---> 68             raise exceptions.from_grpc_error(exc) from exc
     69
     70     return error_remapped_callable

ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:xxx.xx.xxx.x:443: tcp handshaker shutdown
</code>```

I was trying to run the code, that is below:

The user, project is set up, and the same code runs perfectly fine on machine with MacOS (same user account, same project).

```<code>#code for the pipeline here, was too long for the question

compiler.Compiler().compile(pipeline_func=pipeline, package_path="intro_pipeline.json")

DISPLAY_NAME = "intro_" + UUID

job = aiplatform.PipelineJob(
    display_name=DISPLAY_NAME,
    template_path="intro_pipeline.json",
    pipeline_root=PIPELINE_ROOT,
    project=PROJECT_ID,

)

job.submit()
</code>```

Please, help me to debug, maybe there is an issue with some certificates, but I have no idea were should I look . Thanks for any help

Body:
Trying to run a PipelineJob from local instance (local machine with windows, GCP CLI installed /local jupyter lab), but I'm getting

_InactiveRpcError                         Traceback (most recent call last)

The above exception was the direct cause of the following exception:

ServiceUnavailable                        Traceback (most recent call last)
~\AppData\Local\Temp\1\ipykernel_8896\1564544395.py in <module>
     15 #credentials=CREDENTIALS,
     16
---> 17 job.submit() #service_account=SERVICE_ACCOUNT
     18 # job.run()

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\cloud\aiplatform\pipeline_jobs.py in submit(self, service_account, network)
    284             parent=self._parent,
    285             pipeline_job=self._gca_resource,
--> 286             pipeline_job_id=self.job_id,
    287         )
    288

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\cloud\aiplatform_v1\services\pipeline_service\client.py in create_pipeline_job(self, request, parent, pipeline_job, pipeline_job_id, retry, timeout, metadata)
   1197
   1198         # Send the request.
-> 1199         response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
   1200
   1201         # Done; return the response.

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\api_core\gapic_v1\method.py in __call__(self, timeout, retry, *args, **kwargs)
    152             kwargs["metadata"] = metadata
    153
--> 154         return wrapped_func(*args, **kwargs)
    155
    156

c:\users\<user>\pipelines_draft_env\lib\site-packages\google\api_core\grpc_helpers.py in error_remapped_callable(*args, **kwargs)
     66             return callable_(*args, **kwargs)
     67         except grpc.RpcError as exc:
---> 68             raise exceptions.from_grpc_error(exc) from exc
     69
     70     return error_remapped_callable

ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:xxx.xx.xxx.x:443: tcp handshaker shutdown

I was trying to run the code, that is below:

The user, project is set up, and the same code runs perfectly fine on machine with MacOS (same user account, same project).

#code for the pipeline here, was too long for the question

compiler.Compiler().compile(pipeline_func=pipeline, package_path="intro_pipeline.json")

DISPLAY_NAME = "intro_" + UUID

job = aiplatform.PipelineJob(
    display_name=DISPLAY_NAME,
    template_path="intro_pipeline.json",
    pipeline_root=PIPELINE_ROOT,
    project=PROJECT_ID,

)

job.submit()

Please, help me to debug, maybe there is an issue with some certificates, but I have no idea were should I look . Thanks for any help


问:
Python dataset export as cvs
i want to export dataset fetch_lfw_people from sklearn.datasets to continue create model in R i never used Python could anyone help me export this file as .csv.
Thank u,

Exported dataset as cvs file to load in in RStudio

Title: Python dataset export as cvs


问:
How do I make my HTML radio form response an animated SVG?
I have a simple survey radio form, and right now it only provides a text as the output 'style'

```<code>if (option5.checked) {
resultquestion2.style = "background-color:green;"
resultquestion2.innerHTML = 'Correct'
</code>```

I want to try animate an SVG file I have to appear as a response when the option or 'input' has been given.

To be clear, I know how to animate an SVG, but not in this particular context. I need to know how to customize the response element so that an animated object can be placed there first.
PSA! I'm new to coding HTML and CSS

```<code></head>
<body>
    <form id="questions">
     <div>  Example question?

 <input type="radio" id="anw1" name="question1" value="anw1"><label for="anw1">Yes</label>

<input type="radio" id="anw2" name="question1" value="anw2"><label for="anw2">No</label>

<input type="radio" id="anw3" name="question1" value="anw3"><label for="anw3">Maybe</label>

<input type="submit" value="send">
</code>```
```<code><div class="bar" id="result">-</div>

<script>

const form = document.getElementById('questions')

          const option1 = document.getElementById('anw1');
          const option2 = document.getElementById('anw2');
          const option3 = document.getElementById('anw3');

</code>```
```<code>if (option1.checked) {
            result.style = "background-color:green;"
            result.innerHTML = 'Correct'
          }
          if (option2.checked) {
            result.style = "background-color:yellow;"
            result.innerHTML = 'Close, have a banana'
          }
          if (option3.checked) {
            result.style = "background-color:red;"
            result.innerHTML = 'Wrong'
</code>```

Body:
I have a simple survey radio form, and right now it only provides a text as the output 'style'

if (option5.checked) {
resultquestion2.style = "background-color:green;"
resultquestion2.innerHTML = 'Correct'

I want to try animate an SVG file I have to appear as a response when the option or 'input' has been given.

To be clear, I know how to animate an SVG, but not in this particular context. I need to know how to customize the response element so that an animated object can be placed there first.
PSA! I'm new to coding HTML and CSS

    <form id="questions">

  Example question?

 <input type="radio" id="anw1" name="question1" value="anw1">Yes

<input type="radio" id="anw2" name="question1" value="anw2">No

<input type="radio" id="anw3" name="question1" value="anw3">Maybe

<input type="submit" value="send">

-


问:
Sort for Excel worksheet using C# EPPLUS
I am trying to sort an Excel worksheet using C# EPPLUS.  I have reviewed the sort code method here

I am doing this

```<code>  ` var startRow = 11;
    var startColumn= 1;
    var endRow= 150;
    var endColumn= 41;
    var sortColumn = 1;
    using (ExcelRange excelRange =
    yourWorkSheet.Cells[startRow,startColumn, endRow, endColumn])
    {
    excelRange.Sort(sortColumn, true);
    }
     `
</code>```

but that is not working.

The first two columns define what kind of record it is
ex.  column one GSMO  column 2 is Cost.  There are 6 types of record for GSMO
ex GSMO Cost GSMO Profit GSMO LOSS etc..  Then it starts with another value in column 1 such as SESS etc all the way down to the final row
The columns from 3 to 41 are the dollar values associated with the row. So when I sort ascending on column one I want the rest of the columns (2-41) to stay with the same row.  I hope this makes sense.  Any help would be appreciated Thanks Pene

Body:
I am trying to sort an Excel worksheet using C# EPPLUS.  I have reviewed the sort code method here

I am doing this

  ` var startRow = 11;
    var startColumn= 1;
    var endRow= 150;
    var endColumn= 41;
    var sortColumn = 1;
    using (ExcelRange excelRange =
    yourWorkSheet.Cells[startRow,startColumn, endRow, endColumn])
    {
    excelRange.Sort(sortColumn, true);
    }
     `

but that is not working.

The first two columns define what kind of record it is
ex.  column one GSMO  column 2 is Cost.  There are 6 types of record for GSMO
ex GSMO Cost GSMO Profit GSMO LOSS etc..  Then it starts with another value in column 1 such as SESS etc all the way down to the final row
The columns from 3 to 41 are the dollar values associated with the row. So when I sort ascending on column one I want the rest of the columns (2-41) to stay with the same row.  I hope this makes sense.  Any help would be appreciated Thanks Pene


问:
How to register bundles in ASP.NET Core 6?
As the style of application startup has changed I can't find a way to register bundles of js files:

```<code>public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddBundle    // this is no longer there
}
</code>```

How to register bundles in ASP.NET Core 6 MVC?

Body:
As the style of application startup has changed I can't find a way to register bundles of js files:

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddBundle    // this is no longer there
}

How to register bundles in ASP.NET Core 6 MVC?


问:
Using 'group()' got "No result backend is configured." error in Django
With the code below, I use Celery 5.2.7 and django-celery-results in Django on Windows 11:

# "core/celery.py"

import os

from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

app = Celery('core')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')
```
<pre class="lang-py prettyprint-override"><code># "core/settings.py"

INSTALLED_APPS = [
    # ...
    'django_celery_results'
]

CELERY_RESULT_BACKEND = 'django-db'

CELERY_CACHE_BACKEND = 'django-cache'
</code>```

# "store/tasks.py"

from celery import shared_task

@shared_task
def add(x, y):
    return x + y
```
<p>Then, I ran <strong>Celery</strong> with the command below:</p>
<pre class="lang-none prettyprint-override"><code>celery -A core worker --pool=solo -l info
</code>```

Then, called add.delay(3, 4) in test() as shown below:

# "store/views.py"

from .tasks import add
from django.http import HttpResponse

def test(request):

    add.delay(3, 4) # Here

    return HttpResponse("Test")
```
<p>Then, I could properly get the result below:</p>
<pre class="lang-none prettyprint-override"><code>Task store.tasks.add[...] succeeded in 0.04s: 7 # Here
</code>```

But, when calling group(add.delay(i, i) for i in range(10))().get() in test() as shown below:

# "store/views.py"

from celery import group
from django.http import HttpResponse

def test(request):

    group(add.delay(i, i) for i in range(10))().get() # Here

    return HttpResponse("Test")
```
<p>I got the error below:</p>
<blockquote>
<p>NotImplementedError: No result backend is configured. Please see the
documentation for more information.</p>
</blockquote>
<p>So, I tried <code>si()</code> as shown below:</p>
<pre class="lang-py prettyprint-override"><code># "store/views.py"

from celery import group
from django.http import HttpResponse

def call_test(request):
             # ↓ Here
    group(add.si(i, i) for i in range(10))().get()

    return HttpResponse("Call_test")
</code>```

But, I still got the same error below:

NotImplementedError: No result backend is configured. Please see the
documentation for more information.

So, how can I solve the error above to use group()?

Body:
With the code below, I use Celery 5.2.7 and django-celery-results in Django on Windows 11:

# "core/celery.py"

import os

from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

app = Celery('core')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

# "core/settings.py"

INSTALLED_APPS = [
    # ...
    'django_celery_results'
]

CELERY_RESULT_BACKEND = 'django-db'

CELERY_CACHE_BACKEND = 'django-cache'

# "store/tasks.py"

from celery import shared_task

@shared_task
def add(x, y):
    return x + y

Then, I ran Celery with the command below:

celery -A core worker --pool=solo -l info

Then, called add.delay(3, 4) in test() as shown below:

# "store/views.py"

from .tasks import add
from django.http import HttpResponse

def test(request):

    add.delay(3, 4) # Here

    return HttpResponse("Test")

Then, I could properly get the result below:

Task store.tasks.add[...] succeeded in 0.04s: 7 # Here

But, when calling group(add.delay(i, i) for i in range(10))().get() in test() as shown below:

# "store/views.py"

from celery import group
from django.http import HttpResponse

def test(request):

    group(add.delay(i, i) for i in range(10))().get() # Here

    return HttpResponse("Test")

I got the error below:

NotImplementedError: No result backend is configured. Please see the
documentation for more information.

So, I tried si() as shown below:

# "store/views.py"

from celery import group
from django.http import HttpResponse

def call_test(request):
             # ↓ Here
    group(add.si(i, i) for i in range(10))().get()

    return HttpResponse("Call_test")

But, I still got the same error below:

NotImplementedError: No result backend is configured. Please see the
documentation for more information.

So, how can I solve the error above to use group()?


问:
How to decode document vectors to document using TfidfVectorizer? | Python
I know that we can encode text documents to vector representations by using

```<code>vectorizer = TfidfVectorizer(stop_words='english')
document_vectors = vectorizer.fit_transform(df)
</code>```

My question is if I have a document vector representation (an array), how should I transform it back to a document (texts) if I know that it was previous transformed to a vector using TFIDF.

Body:
I know that we can encode text documents to vector representations by using

vectorizer = TfidfVectorizer(stop_words='english')
document_vectors = vectorizer.fit_transform(df)

My question is if I have a document vector representation (an array), how should I transform it back to a document (texts) if I know that it was previous transformed to a vector using TFIDF.


问:
IT-140 Project 2 Python
I am working on my final project for my intro to scripting class. we are using python. my code seems to be doing well except a a few lines of code, i cannot seem to define my item and state. The errors are traceback errors on lines 27 and 45.
Here is my code:

```<code># declaration
rooms = {
        'Town Square': {'North': 'Bookstore', 'South': 'Restaurant', 'East': 'Tailor', 'West': 'Jeweler'},
        'Tailor': {'East': ' Town Square', 'item': 'Suit'},
        'Restaurant': {'North': 'Town Square', 'East': 'Hair Dresser', 'item': 'salad'},
        'Hair Dresser': {'West': 'Restaurant', 'item': 'Comb'},
        'Book Store': {'South': 'Town Square', 'East': 'Shoemaker', 'item': 'Bible'},
        'Shoemaker': {'West': 'Book Store', 'item': 'Shoes'},
        'Jeweler': {'North': 'Chapel', 'West': 'Town Square', 'item': 'Ring'},
        'Chapel': {'South': 'Chapel', 'item': 'Wife'}
}
state = 'Town Square'

# function
def get_new_state(state, direction):
    new_state = state  # declaraing
    for i in rooms:  # loop
        if i == state:  # if
            if direction in rooms[i]:  # if
                new_state = rooms[i][direction]  # assigning new_state
    return new_state  # return

# function
def get_item(state):
    return rooms[state]['Item']  # returning Item value

# function
def show_instructions():
    # print a main menu and the commands
    print("Welcome to the Wedding Adventure!")
    print("Collect all 6 items before you reach the chapel, so you will not die of embarrassment when you get left at "
          "the altar")
    print("Move commands: go South, go North, go East, go West")
    print("Add to Inventory: get 'item name'")

show_instructions()  # calling function
inventory = []
while (1):  # gameplay loop
    print('You are in ', state)  # printing state
    print('Inventory:', inventory)  # printing inventory
    item = get_item(state)  # calling get_item function
    print('You see a', item)  # print
    print('------------------------------')
    if item == 'Wife':  # if
        print('SLAP ... GAME OVER!')
        print('Thanks for playing! Hope you enjoyed it!')
        exit(0)
    direction = input('Enter your move: ')  # asking user
    if (direction == 'go East' or direction == 'go West' or direction == 'go North' or direction == 'go South'):  # if
        direction = direction[3:]
        new_state = get_new_state(state, direction)  # calling function
        if new_state == state:  # if
            print('The room has wall in that direction enter other direction!')  # print
        else:
            state = new_state  # changing state value to new_state
    elif direction == str('get '+item):  # if
        if item in inventory:  # if item already present in inventory
            print('Item already taken go to another room!!')
        else:
            print(f"{item} retrieved!\n")
            inventory.append(item)  # appending
    else:
        print('Invalid direction!!')  # print
    if len(inventory) == 6:
        # print
        print('Congratulations! You have collected all items and got married!')
        print('Thanks for playing! Hope you enjoyed it!')
        exit(0)
</code>```

The code runs but has traceback errors on when initially run. I am not certain on how to trace the inventory for the items. Should I create a new dictionary for inventory?

Title: IT-140 Project 2 Python

Body:
I am working on my final project for my intro to scripting class. we are using python. my code seems to be doing well except a a few lines of code, i cannot seem to define my item and state. The errors are traceback errors on lines 27 and 45.
Here is my code:

# declaration
rooms = {
        'Town Square': {'North': 'Bookstore', 'South': 'Restaurant', 'East': 'Tailor', 'West': 'Jeweler'},
        'Tailor': {'East': ' Town Square', 'item': 'Suit'},
        'Restaurant': {'North': 'Town Square', 'East': 'Hair Dresser', 'item': 'salad'},
        'Hair Dresser': {'West': 'Restaurant', 'item': 'Comb'},
        'Book Store': {'South': 'Town Square', 'East': 'Shoemaker', 'item': 'Bible'},
        'Shoemaker': {'West': 'Book Store', 'item': 'Shoes'},
        'Jeweler': {'North': 'Chapel', 'West': 'Town Square', 'item': 'Ring'},
        'Chapel': {'South': 'Chapel', 'item': 'Wife'}
}
state = 'Town Square'

# function
def get_new_state(state, direction):
    new_state = state  # declaraing
    for i in rooms:  # loop
        if i == state:  # if
            if direction in rooms[i]:  # if
                new_state = rooms[i][direction]  # assigning new_state
    return new_state  # return

# function
def get_item(state):
    return rooms[state]['Item']  # returning Item value

# function
def show_instructions():
    # print a main menu and the commands
    print("Welcome to the Wedding Adventure!")
    print("Collect all 6 items before you reach the chapel, so you will not die of embarrassment when you get left at "
          "the altar")
    print("Move commands: go South, go North, go East, go West")
    print("Add to Inventory: get 'item name'")

show_instructions()  # calling function
inventory = []
while (1):  # gameplay loop
    print('You are in ', state)  # printing state
    print('Inventory:', inventory)  # printing inventory
    item = get_item(state)  # calling get_item function
    print('You see a', item)  # print
    print('------------------------------')
    if item == 'Wife':  # if
        print('SLAP ... GAME OVER!')
        print('Thanks for playing! Hope you enjoyed it!')
        exit(0)
    direction = input('Enter your move: ')  # asking user
    if (direction == 'go East' or direction == 'go West' or direction == 'go North' or direction == 'go South'):  # if
        direction = direction[3:]
        new_state = get_new_state(state, direction)  # calling function
        if new_state == state:  # if
            print('The room has wall in that direction enter other direction!')  # print
        else:
            state = new_state  # changing state value to new_state
    elif direction == str('get '+item):  # if
        if item in inventory:  # if item already present in inventory
            print('Item already taken go to another room!!')
        else:
            print(f"{item} retrieved!\n")
            inventory.append(item)  # appending
    else:
        print('Invalid direction!!')  # print
    if len(inventory) == 6:
        # print
        print('Congratulations! You have collected all items and got married!')
        print('Thanks for playing! Hope you enjoyed it!')
        exit(0)

The code runs but has traceback errors on when initially run. I am not certain on how to trace the inventory for the items. Should I create a new dictionary for inventory?


问:
How to make a Mystreamlistener class for tweepy
```<code>`import tweepy
import stream
import openai
from PIL import Image
from io import BytesIO

# Twitter API credentials
consumer_key = "removed"
consumer_secret = "removed"
access_key = "removed"
access_secret = "removed"

# OpenAI API credentials
openai_key = "removed"

# set up tweepy to authenticate with Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)

# set up OpenAI
openai.api_key = openai_key

# create a tweepy API object
api = tweepy.API(auth)

# function to handle incoming tweets that mention your account
def handle_mention(tweet):
  # get the text of the tweet
  text = tweet.text

  # generate a response using ChatGPT
  response = openai.Completion.create(
    model="text-davinci-002",
    prompt=text,
    temperature=0.5,
    max_tokens=1024,
    top_p=1,
    frequency_penalty=0,
    presence_penalty=0
  )

  # take a screenshot of the ChatGPT response
  img = Image.new("RGB", (1024, 1024), "white")
  d = ImageDraw.Draw(img)
  font = ImageFont.truetype("font.ttf", 36)
  d.text((10, 10), response, font=font, fill=(0, 0, 0))
  img_bytes = BytesIO()
  img.save(img_bytes, format="PNG")
  img_bytes.seek(0)

  # tweet the screenshot
  api.update_with_media(
    filename="response.png",
    file=img_bytes,
    in_reply_to_status_id=tweet.id
  )

# function to listen for tweets that mention your account
def listen_for_mentions():
# create a tweepy Stream object to listen for mentions
  stream = tweepy.stream(auth, listener=MyStreamListener(), bearer_token="removed", track=["@askAIguy"])

# create a tweepy StreamListener to handle incoming tweets
class MyStreamListener(stream):
  def on_status(self, status):
    # only handle tweets that mention @askaiguy
    if "@" in status.text and "@askaiguy" in status.text:
      # parse the tweet text to extract the mention of @askaiguy
      tweet_text = status.text.lower()
      mention_start = tweet_text.index("@askaiguy")
      mention_end = mention_start + len("@askaiguy")
      mention = tweet_text[mention_start:mention_end]

      # handle the mention by calling the handle_mention() function
      handle_mention(status)

# start listening for mentions of your account
listen_for_mentions()`

</code>```

This is the error response I keep getting:

```<code>Traceback (most recent call last):
  File "main.py", line 67, in <module>
    class MyStreamListener(stream):
# TypeError: module() takes at most 2 arguments (3 given)
</code>```

I know there was an update to the tweepy API and  it merged StreamListener into Stream. Can someone please give me some guidance as to what I'm missing?

I've tried changing the name of the funciton, rearranging the structure, removing the arguments given, etc. I've spent about 4 hours working on this problem researching and I've gotten progressively closer but I can't seem to get the bot to listen for mentions.

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

Body:
`import tweepy
import stream
import openai
from PIL import Image
from io import BytesIO

# Twitter API credentials
consumer_key = "removed"
consumer_secret = "removed"
access_key = "removed"
access_secret = "removed"

# OpenAI API credentials
openai_key = "removed"

# set up tweepy to authenticate with Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)

# set up OpenAI
openai.api_key = openai_key

# create a tweepy API object
api = tweepy.API(auth)

# function to handle incoming tweets that mention your account
def handle_mention(tweet):
  # get the text of the tweet
  text = tweet.text

  # generate a response using ChatGPT
  response = openai.Completion.create(
    model="text-davinci-002",
    prompt=text,
    temperature=0.5,
    max_tokens=1024,
    top_p=1,
    frequency_penalty=0,
    presence_penalty=0
  )

  # take a screenshot of the ChatGPT response
  img = Image.new("RGB", (1024, 1024), "white")
  d = ImageDraw.Draw(img)
  font = ImageFont.truetype("font.ttf", 36)
  d.text((10, 10), response, font=font, fill=(0, 0, 0))
  img_bytes = BytesIO()
  img.save(img_bytes, format="PNG")
  img_bytes.seek(0)

  # tweet the screenshot
  api.update_with_media(
    filename="response.png",
    file=img_bytes,
    in_reply_to_status_id=tweet.id
  )

# function to listen for tweets that mention your account
def listen_for_mentions():
# create a tweepy Stream object to listen for mentions
  stream = tweepy.stream(auth, listener=MyStreamListener(), bearer_token="removed", track=["@askAIguy"])

# create a tweepy StreamListener to handle incoming tweets
class MyStreamListener(stream):
  def on_status(self, status):
    # only handle tweets that mention @askaiguy
    if "@" in status.text and "@askaiguy" in status.text:
      # parse the tweet text to extract the mention of @askaiguy
      tweet_text = status.text.lower()
      mention_start = tweet_text.index("@askaiguy")
      mention_end = mention_start + len("@askaiguy")
      mention = tweet_text[mention_start:mention_end]

      # handle the mention by calling the handle_mention() function
      handle_mention(status)

# start listening for mentions of your account
listen_for_mentions()`

This is the error response I keep getting:

Traceback (most recent call last):
  File "main.py", line 67, in <module>
    class MyStreamListener(stream):
# TypeError: module() takes at most 2 arguments (3 given)

I know there was an update to the tweepy API and  it merged StreamListener into Stream. Can someone please give me some guidance as to what I'm missing?

I've tried changing the name of the funciton, rearranging the structure, removing the arguments given, etc. I've spent about 4 hours working on this problem researching and I've gotten progressively closer but I can't seem to get the bot to listen for mentions.