问:
How can I get Racaty direct link?
I'm currently using a base to try to get the Racaty.io link directly, but I'm not succeeding, see my formula below.

```<code><?php
class racaty
{
    public $name = 'Racaty';
    private $id = '';
    private $title = '';
    private $image = '';
    private $referer = '';
    private $status = 'fail';
    private $url = 'https://racaty.net/';
    private $cookies = [];
    private $ch;
    private $proxy = false;

    function __construct($id = '')
    {
        session_write_close();
        if (!empty($id)) {
            $this->id = $id;
            $this->url .= $this->id . '.html';

            $scheme = parse_url($this->url, PHP_URL_SCHEME);
            $host = parse_url($this->url, PHP_URL_HOST);
            $port = parse_URL($this->url, PHP_URL_PORT);
            if (empty($port)) $port = $scheme == 'https' ? 443 : 80;
            $ipv4 = gethostbyname($host);
            $resolveHost = implode(':', array($host, $port, $ipv4));

            session_write_close();
            $this->ch = curl_init();
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($this->ch, CURLOPT_MAXREDIRS, 5);
            curl_setopt($this->ch, CURLOPT_ENCODING, '');
            curl_setopt($this->ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->ch, CURLOPT_RESOLVE, array($resolveHost));
            curl_setopt($this->ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
            curl_setopt($this->ch, CURLOPT_DNS_SERVERS, dns_servers());
            curl_setopt($this->ch, CURLOPT_NOSIGNAL, true);
            curl_setopt($this->ch, CURLOPT_DNS_CACHE_TIMEOUT, 300);
            curl_setopt($this->ch, CURLOPT_TCP_KEEPALIVE, true);
            if (defined('CURLOPT_TCP_FASTOPEN')) {
                curl_setopt($this->ch, CURLOPT_TCP_FASTOPEN, true);
            }
            curl_setopt($this->ch, CURLOPT_TCP_NODELAY, true);
            curl_setopt($this->ch, CURLOPT_FORBID_REUSE, true);
            curl_setopt($this->ch, CURLOPT_FAILONERROR, true);
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, array(
                'host: racaty.net',
                'origin: https://racaty.net',
            ));
            curl_setopt($this->ch, CURLOPT_REFERER, $this->url);
            curl_setopt($this->ch, CURLOPT_USERAGENT, USER_AGENT);
            curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, function ($ch, $headerLine) {
                if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) && !empty($cookie[1])) {
                    $this->cookies[] = $cookie[1];
                }
                return strlen($headerLine);
            });
        }
    }

    private function embedSources()
    {
        session_write_close();
        curl_setopt($this->ch, CURLOPT_URL, 'https://racaty.net/embed-' . $this->id . '.html');
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'GET');
        $response = curl_exec($this->ch);
        $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
        $err = curl_error($this->ch);
        if ($status >= 200 && $status < 400) {
            $dom = \KubAT\PhpSimple\HtmlDomParser::str_get_html($response);
            $vjs = $dom->find('#vjsplayer');
            if ($vjs) {
                $this->status = 'ok';
                $this->image = $vjs[0]->poster;

                $result[] = [
                    'file' => $vjs[0]->find('source', 0)->src,
                    'type' => 'video/mp4',
                    'label' => 'Original'
                ];
                return $result;
            } else {
                $player = $dom->find('#player_code', 0);
                if (!empty($player)) {
                    $eval = $player->find('script', 0)->innertext;
                    if (strpos($eval, 'eval(function(p,a,c,k,e,d)') !== FALSE) {
                        $unpacker = new \JavascriptUnpacker\JavascriptUnpacker();
                        $decode = $unpacker->unpack($eval);

                        $dom = \KubAT\PhpSimple\HtmlDomParser::str_get_html($decode);
                        $embed = $dom->find('#np_vid', 0);
                        if (!empty($embed)) {
                            $this->status = 'ok';
                            $this->image = $dom->find('param[name="previewImage"]', 0)->value;

                            $result[] = [
                                'file' => $embed->src,
                                'type' => 'video/mp4',
                                'label' => 'Original'
                            ];
                            return $result;
                        } else {
                            error_log("racaty embedSources {$this->id} => np_vid not found");
                        }
                    } else {
                        error_log("racaty embedSources {$this->id} => eval not found");
                    }
                } else {
                    error_log("racaty embedSources {$this->id} => player_code not found");
                }
            }
        } else {
            error_log("racaty embedSources {$this->id} => $status: $err");
        }
        return [];
    }

    function get_sources()
    {
        session_write_close();
        if (!empty($this->id)) {
            $data = $this->embedSources();
            if (!empty($data)) {
                return $data;
            } else {
                session_write_close();
                curl_setopt($this->ch, CURLOPT_URL, $this->url);
                curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'POST');
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, 'op=download2&id=' . $this->id . '&rand=&referer=&method_free=&method_premium=');
                $response = curl_exec($this->ch);
                $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
                $err = curl_error($this->ch);

                if ($status >= 200 && $status < 400) {
                    $dom = \KubAT\PhpSimple\HtmlDomParser::str_get_html($response);
                    $dl = $dom->find('#uniqueExpirylink');
                    if ($dl) {
                        $this->status = 'ok';
                        $this->referer = $this->url;
                        $this->title = trim($dom->find('.name', 0)->find('strong', 0)->plaintext);

                        $result[] = [
                            'file' => $dl[0]->href,
                            'type' => 'video/mp4',
                            'label' => 'Original'
                        ];
                        return $result;
                    } else {
                        error_log("racaty get_sources {$this->id} => uniqueExpirylink not found");
                    }
                } else {
                    error_log("racaty get_sources {$this->id} => $status: $err");
                }
            }
        }
        return [];
    }

    function get_cookies()
    {
        session_write_close();
        return $this->cookies;
    }

    function get_status()
    {
        session_write_close();
        return $this->status;
    }

    function get_title()
    {
        session_write_close();
        return $this->title;
    }

    function get_image()
    {
        session_write_close();
        return $this->image;
    }

    function get_referer()
    {
        session_write_close();
        return $this->referer;
    }

    function get_id()
    {
        session_write_close();
        return $this->id;
    }

    function __destruct()
    {
        session_write_close();
        curl_close($this->ch);
    }
}

</code>```

I would like to know if there is a simpler way, could someone help me?

I tried to use the mentioned code as an example, but I couldn't get the original source of the video, I believe I'm forgetting some important factor, I would like to get only the direct link of the video, using GET of the ID.

Title: How can I get Racaty direct link?

Body:
I'm currently using a base to try to get the Racaty.io link directly, but I'm not succeeding, see my formula below.

<?php
class racaty
{
    public $name = 'Racaty';
    private $id = '';
    private $title = '';
    private $image = '';
    private $referer = '';
    private $status = 'fail';
    private $url = 'https://racaty.net/';
    private $cookies = [];
    private $ch;
    private $proxy = false;

    function __construct($id = '')
    {
        session_write_close();
        if (!empty($id)) {
            $this->id = $id;
            $this->url .= $this->id . '.html';

            $scheme = parse_url($this->url, PHP_URL_SCHEME);
            $host = parse_url($this->url, PHP_URL_HOST);
            $port = parse_URL($this->url, PHP_URL_PORT);
            if (empty($port)) $port = $scheme == 'https' ? 443 : 80;
            $ipv4 = gethostbyname($host);
            $resolveHost = implode(':', array($host, $port, $ipv4));

            session_write_close();
            $this->ch = curl_init();
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($this->ch, CURLOPT_MAXREDIRS, 5);
            curl_setopt($this->ch, CURLOPT_ENCODING, '');
            curl_setopt($this->ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->ch, CURLOPT_RESOLVE, array($resolveHost));
            curl_setopt($this->ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
            curl_setopt($this->ch, CURLOPT_DNS_SERVERS, dns_servers());
            curl_setopt($this->ch, CURLOPT_NOSIGNAL, true);
            curl_setopt($this->ch, CURLOPT_DNS_CACHE_TIMEOUT, 300);
            curl_setopt($this->ch, CURLOPT_TCP_KEEPALIVE, true);
            if (defined('CURLOPT_TCP_FASTOPEN')) {
                curl_setopt($this->ch, CURLOPT_TCP_FASTOPEN, true);
            }
            curl_setopt($this->ch, CURLOPT_TCP_NODELAY, true);
            curl_setopt($this->ch, CURLOPT_FORBID_REUSE, true);
            curl_setopt($this->ch, CURLOPT_FAILONERROR, true);
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, array(
                'host: racaty.net',
                'origin: https://racaty.net',
            ));
            curl_setopt($this->ch, CURLOPT_REFERER, $this->url);
            curl_setopt($this->ch, CURLOPT_USERAGENT, USER_AGENT);
            curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, function ($ch, $headerLine) {
                if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) && !empty($cookie[1])) {
                    $this->cookies[] = $cookie[1];
                }
                return strlen($headerLine);
            });
        }
    }

    private function embedSources()
    {
        session_write_close();
        curl_setopt($this->ch, CURLOPT_URL, 'https://racaty.net/embed-' . $this->id . '.html');
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'GET');
        $response = curl_exec($this->ch);
        $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
        $err = curl_error($this->ch);
        if ($status >= 200 && $status < 400) {
            $dom = \KubAT\PhpSimple\HtmlDomParser::str_get_html($response);
            $vjs = $dom->find('#vjsplayer');
            if ($vjs) {
                $this->status = 'ok';
                $this->image = $vjs[0]->poster;

                $result[] = [
                    'file' => $vjs[0]->find('source', 0)->src,
                    'type' => 'video/mp4',
                    'label' => 'Original'
                ];
                return $result;
            } else {
                $player = $dom->find('#player_code', 0);
                if (!empty($player)) {
                    $eval = $player->find('script', 0)->innertext;
                    if (strpos($eval, 'eval(function(p,a,c,k,e,d)') !== FALSE) {
                        $unpacker = new \JavascriptUnpacker\JavascriptUnpacker();
                        $decode = $unpacker->unpack($eval);

                        $dom = \KubAT\PhpSimple\HtmlDomParser::str_get_html($decode);
                        $embed = $dom->find('#np_vid', 0);
                        if (!empty($embed)) {
                            $this->status = 'ok';
                            $this->image = $dom->find('param[name="previewImage"]', 0)->value;

                            $result[] = [
                                'file' => $embed->src,
                                'type' => 'video/mp4',
                                'label' => 'Original'
                            ];
                            return $result;
                        } else {
                            error_log("racaty embedSources {$this->id} => np_vid not found");
                        }
                    } else {
                        error_log("racaty embedSources {$this->id} => eval not found");
                    }
                } else {
                    error_log("racaty embedSources {$this->id} => player_code not found");
                }
            }
        } else {
            error_log("racaty embedSources {$this->id} => $status: $err");
        }
        return [];
    }

    function get_sources()
    {
        session_write_close();
        if (!empty($this->id)) {
            $data = $this->embedSources();
            if (!empty($data)) {
                return $data;
            } else {
                session_write_close();
                curl_setopt($this->ch, CURLOPT_URL, $this->url);
                curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'POST');
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, 'op=download2&id=' . $this->id . '&rand=&referer=&method_free=&method_premium=');
                $response = curl_exec($this->ch);
                $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
                $err = curl_error($this->ch);

                if ($status >= 200 && $status < 400) {
                    $dom = \KubAT\PhpSimple\HtmlDomParser::str_get_html($response);
                    $dl = $dom->find('#uniqueExpirylink');
                    if ($dl) {
                        $this->status = 'ok';
                        $this->referer = $this->url;
                        $this->title = trim($dom->find('.name', 0)->find('strong', 0)->plaintext);

                        $result[] = [
                            'file' => $dl[0]->href,
                            'type' => 'video/mp4',
                            'label' => 'Original'
                        ];
                        return $result;
                    } else {
                        error_log("racaty get_sources {$this->id} => uniqueExpirylink not found");
                    }
                } else {
                    error_log("racaty get_sources {$this->id} => $status: $err");
                }
            }
        }
        return [];
    }

    function get_cookies()
    {
        session_write_close();
        return $this->cookies;
    }

    function get_status()
    {
        session_write_close();
        return $this->status;
    }

    function get_title()
    {
        session_write_close();
        return $this->title;
    }

    function get_image()
    {
        session_write_close();
        return $this->image;
    }

    function get_referer()
    {
        session_write_close();
        return $this->referer;
    }

    function get_id()
    {
        session_write_close();
        return $this->id;
    }

    function __destruct()
    {
        session_write_close();
        curl_close($this->ch);
    }
}

I would like to know if there is a simpler way, could someone help me?

I tried to use the mentioned code as an example, but I couldn't get the original source of the video, I believe I'm forgetting some important factor, I would like to get only the direct link of the video, using GET of the ID.


来源: stackexchange

问:
Node js Typescript Jest spy result dependency in another jest spy function
My scenario is

Repo :

```<code>const result2=Artist.findOne({where:{uid:'sdfdfdfdfddsfdfdfdfdf'});
const result2count=ArtistAccount.count({where:{artist_id:result2.id}});
</code>```

test case :

```<code> const artistSQueryfn: any = {
            findOne: jest.fn().mockImplementation(() => ({
                uid: artist_uid,
                id: artist_id,
                ...dataArtistInput
            })),
           get: jest.fn().mockImplementation(() => ({
                 uid: artist_uid,
                 id: artist_id,
                 ...dataArtistInput
             }))
        };

const artist = jest.spyOn(models.Artist, 'findOne').mockImplementation(artistSQueryfn);

jest.spyOn(models.ArtistAccount, 'count').mockResolvedValueOnce(1);
</code>```

tried like this but getting

WHERE parameter "artist_id" has invalid "undefined" value

test case :

```<code>const artistSQueryfn: any = {
            findOne: jest.fn().mockImplementation(() => ({
                uid: artist_uid,
                id: artist_id,
                ...dataArtistInput
            })),
           get: jest.fn().mockImplementation(() => ({
                 uid: artist_uid,
                 id: artist_id,
                 ...dataArtistInput
             }))
        };

const artist = jest.spyOn(models.Artist, 'findOne').mockImplementation(artistSQueryfn);

jest.spyOn(models.ArtistAccount, 'count').mockResolvedValueOnce(1);
</code>```

tried like this but getting

WHERE parameter "artist_id" has invalid "undefined" value

ContentLicense: CC BY-SA 4.0

Body:
My scenario is

Repo :

const result2=Artist.findOne({where:{uid:'sdfdfdfdfddsfdfdfdfdf'});
const result2count=ArtistAccount.count({where:{artist_id:result2.id}});

test case :

 const artistSQueryfn: any = {
            findOne: jest.fn().mockImplementation(() => ({
                uid: artist_uid,
                id: artist_id,
                ...dataArtistInput
            })),
           get: jest.fn().mockImplementation(() => ({
                 uid: artist_uid,
                 id: artist_id,
                 ...dataArtistInput
             }))
        };

const artist = jest.spyOn(models.Artist, 'findOne').mockImplementation(artistSQueryfn);

jest.spyOn(models.ArtistAccount, 'count').mockResolvedValueOnce(1);

tried like this but getting

WHERE parameter "artist_id" has invalid "undefined" value

test case :

const artistSQueryfn: any = {
            findOne: jest.fn().mockImplementation(() => ({
                uid: artist_uid,
                id: artist_id,
                ...dataArtistInput
            })),
           get: jest.fn().mockImplementation(() => ({
                 uid: artist_uid,
                 id: artist_id,
                 ...dataArtistInput
             }))
        };

const artist = jest.spyOn(models.Artist, 'findOne').mockImplementation(artistSQueryfn);

jest.spyOn(models.ArtistAccount, 'count').mockResolvedValueOnce(1);

tried like this but getting

WHERE parameter "artist_id" has invalid "undefined" value


问:
Pandas: convert UTC to Local time using timezone, then drop timezone
I have a dataframe with columns:

time: time in UTC format

timezone: the corresponding timezone.

```<code>
                       time             timezone
0  2022-12-28T20:16:31.373Z        Europe/Athens
1  2022-07-28T20:16:31.373Z        Europe/Athens
2  2022-11-01T21:35:35.865Z        Europe/Dublin
3  2022-08-03T19:44:07.611Z  America/Los_Angeles
4  2022-08-02T12:44:44.360Z         Europe/Minsk
</code>```

I want to:

Convert UTC time to Local time (using timezone)

Remove the Timezone and just keep the datetime

It seems to me that this solution works, but want to make sure that I am not missing something (eg. doesn't deal with dailight saving or something)

import pandas as pd
 # example dataframe
df = pd.DataFrame({
    'time' :    ['2022-12-28T20:16:31.373Z', '2022-07-28T20:16:31.373Z', '2022-11-01T21:35:35.865Z', '2022-08-03T19:44:07.611Z', '2022-08-02T12:44:44.360Z'],
    'timezone': ['Europe/Athens', 'Europe/Athens', 'Europe/Dublin', 'America/Los_Angeles', 'Europe/Minsk']

})

 # function
def get_local_time (timestamp: pd.Timestamp, timezone: str) -> pd.Timestamp:
    timestamp = pd.to_datetime(timestamp).tz_convert(timezone).replace(tzinfo=None)
    return timestamp

df['local_time'] = df.apply(lambda row: get_local_time(row['time'], row['timezone']), axis = 1).dt.round(freq='S')

print (df)

---
OUT:
                       time             timezone          local_time
0  2022-12-28T20:16:31.373Z        Europe/Athens 2022-12-28 22:16:31
1  2022-07-28T20:16:31.373Z        Europe/Athens 2022-07-28 23:16:31
2  2022-11-01T21:35:35.865Z        Europe/Dublin 2022-11-01 21:35:36
3  2022-08-03T19:44:07.611Z  America/Los_Angeles 2022-08-03 12:44:08
4  2022-08-02T12:44:44.360Z         Europe/Minsk 2022-08-02 15:44:44
```

Body:
I have a dataframe with columns:

time: time in UTC format

timezone: the corresponding timezone.

                       time             timezone
0  2022-12-28T20:16:31.373Z        Europe/Athens
1  2022-07-28T20:16:31.373Z        Europe/Athens
2  2022-11-01T21:35:35.865Z        Europe/Dublin
3  2022-08-03T19:44:07.611Z  America/Los_Angeles
4  2022-08-02T12:44:44.360Z         Europe/Minsk

I want to:

Convert UTC time to Local time (using timezone)

Remove the Timezone and just keep the datetime

It seems to me that this solution works, but want to make sure that I am not missing something (eg. doesn't deal with dailight saving or something)

import pandas as pd
 # example dataframe
df = pd.DataFrame({
    'time' :    ['2022-12-28T20:16:31.373Z', '2022-07-28T20:16:31.373Z', '2022-11-01T21:35:35.865Z', '2022-08-03T19:44:07.611Z', '2022-08-02T12:44:44.360Z'],
    'timezone': ['Europe/Athens', 'Europe/Athens', 'Europe/Dublin', 'America/Los_Angeles', 'Europe/Minsk']

})

 # function
def get_local_time (timestamp: pd.Timestamp, timezone: str) -> pd.Timestamp:
    timestamp = pd.to_datetime(timestamp).tz_convert(timezone).replace(tzinfo=None)
    return timestamp

df['local_time'] = df.apply(lambda row: get_local_time(row['time'], row['timezone']), axis = 1).dt.round(freq='S')

print (df)

---
OUT:
                       time             timezone          local_time
0  2022-12-28T20:16:31.373Z        Europe/Athens 2022-12-28 22:16:31
1  2022-07-28T20:16:31.373Z        Europe/Athens 2022-07-28 23:16:31
2  2022-11-01T21:35:35.865Z        Europe/Dublin 2022-11-01 21:35:36
3  2022-08-03T19:44:07.611Z  America/Los_Angeles 2022-08-03 12:44:08
4  2022-08-02T12:44:44.360Z         Europe/Minsk 2022-08-02 15:44:44


问:
JSON parsin error - How I using CodingKeys Swift parse a dynamic key?
My code

```<code>struct Functionality: Codable {
  let subCod: String?
  let parentFunctionality: String?
  let transaccional: String?
  let permissions: MyModel?

  private enum CodingKeys: String, CodingKey {
    case subCod
    case parentFunctionality
    case transaccional
    case "permissions" -> dynamic key
  }
</code>```

I need to parse a JSON where, in place of permission, there will be a dynamic key. Do you know how I can achieve this?

Body:
My code

struct Functionality: Codable {
  let subCod: String?
  let parentFunctionality: String?
  let transaccional: String?
  let permissions: MyModel?

  private enum CodingKeys: String, CodingKey {
    case subCod
    case parentFunctionality
    case transaccional
    case "permissions" -> dynamic key
  }

I need to parse a JSON where, in place of permission, there will be a dynamic key. Do you know how I can achieve this?


问:
How to link pricing table with affiliate product?
I have a pricing table on my home page that lists 3 nutrition plans. Each of these plans is actually an affiliate product. Currently, I've manually added the affiliate link to each of the buttons (which redirects to the affiliate website by clicking a button), without using woocomerce products.

I have another page called Plans in which I use the product grid widget from Elementor, which automatically adds my external products that are added to Woocomerce product list (links are the same as in the pricing table product list).

So here I got totally confused due to lack of my experience. Here are the problems:

I can't use some kind of grid on my homepage as well (for additional widget cost and design reasons), but I will need to edit 2 places if an affiliate link would change.

In addition to that, I'm not sure if WooCommerce will be able to
track which products sell the best because it's not actually
directly coupled, it's just a link. Or I'm wrong here and Woocomerce
will only look into the affiliate link?

I would be able to live with changing 2 places in the future, but I'm totally not sure about the second one.I tried to dig deep into that, but only found information with an actual products and not affiliate ones, which is not the case in my scenario.


问:
return <Instance of '_FakeEither_0<Failure, ManagerEntity>'> rather than <Right(Instance of 'ManagerEntity')>
```<code>Erro:

</code>```
```<code>Expected: Right<dynamic, ManagerEntity>:<Right(Instance of 'ManagerEntity')>
Actual: <Instance of '_FakeEither_0<Failure, ManagerEntity>'>

package:test_api                                               expect
expect
package:flutter_test/src/widget_tester.dart:460
main.<fn>
</code>```
```<code></code>```
```<code>auth_repository.dart

</code>```
```<code>`import 'package:dartz/dartz.dart';
import 'package:firebase_auth/firebase_auth.dart';

abstract class AuthRepository {
  Future<Either<Failure, ManagerEntity>> loginWithEmail(
      ManagerEntity newUserInfo);
  Future<Either<Failure, User>>? logUp(ManagerEntity userInfo);
  Future<void> LogOut({required String userId});
}`
</code>```
```<code>

 login_with_email.dart

</code>```
```<code>`import 'package:barmusic_admin/core/erros/connection_error.dart';
import 'package:barmusic_admin/core/erros/error_login.dart';
import 'package:barmusic_admin/core/erros/failures.dart';
import 'package:barmusic_admin/core/services/connectivity_service.dart';
import 'package:barmusic_admin/features/domain/entities/manager_entity.dart';
import 'package:barmusic_admin/features/domain/repositories/auth_repository.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:dartz/dartz.dart';

abstract class LoginWithEmail {
  Future<Either<Failure, ManagerEntity>> call(ManagerEntity manager);
}

class LoginWithEmailImp implements LoginWithEmail {
  final AuthRepository _repository;
  final ConnectivityService _service;

  LoginWithEmailImp(this._repository, this._service);

  @override
  Future<Either<Failure, ManagerEntity>> call(ManagerEntity manager) async {
    var result = await _service.isOnline();
    if (result.isLeft()) {
      result.map((r) => null);
      return Left(ConnectionError(
          message: 'Verifique sua conexão com a internet e tente novamente'));
    }

    if (!manager.isValidEmail) {
      return Left(ErrorLoginEmail(message: 'E-mail inválido'));
    } else if (!manager.isValidPassword) {
      return Left(ErrorLoginEmail(message: 'Senha inválida'));
    }

    return await _repository.loginWithEmail(manager);
  }
}`
</code>```
```<code>

     login_with_email_test.dart

</code>```
<p>` import 'package:barmusic_admin/core/erros/error_login.dart';
import 'package:barmusic_admin/core/services/connectivity_service.dart';
import 'package:barmusic_admin/features/domain/entities/manager_entity.dart';
import 'package:barmusic_admin/features/domain/repositories/auth_repository.dart';
import 'package:barmusic_admin/features/domain/usecases/auth/login_with_email.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';</p>
```<code>import 'login_with_email_test.mocks.dart';

// @GenerateMocks([AuthRepository, ConnectivityService])
@GenerateNiceMocks(
    [MockSpec<AuthRepository>(), MockSpec<ConnectivityService>()])
void main() {
  final repository = MockAuthRepository();
  final service = MockConnectivityService();
  final usecase = LoginWithEmailImp(repository, service);

  setUpAll(() {
    when(service.isOnline()).thenAnswer((_) async => Right(unit));
  });

  test('should consume repository loginEmail', () async {
    var user = ManagerEntity(email: 'test@gmail.com', password: 'teste');
    when(repository.loginWithEmail(user)).thenAnswer((_) async => Right(user));
    var result = await usecase(ManagerEntity.withEmailAndPass(
        email: "test@gmail.com", password: "teste"));

    expect(result, Right(user));
  });
}`
</code>```
```<code>

</code>```

Body:
Erro:

Expected: Right<dynamic, ManagerEntity>:<Right(Instance of 'ManagerEntity')>
Actual: <Instance of '_FakeEither_0<Failure, ManagerEntity>'>

package:test_api                                               expect
expect
package:flutter_test/src/widget_tester.dart:460
main.<fn>

auth_repository.dart

`import 'package:dartz/dartz.dart';
import 'package:firebase_auth/firebase_auth.dart';

abstract class AuthRepository {
  Future<Either<Failure, ManagerEntity>> loginWithEmail(
      ManagerEntity newUserInfo);
  Future<Either<Failure, User>>? logUp(ManagerEntity userInfo);
  Future<void> LogOut({required String userId});
}`

 login_with_email.dart

`import 'package:barmusic_admin/core/erros/connection_error.dart';
import 'package:barmusic_admin/core/erros/error_login.dart';
import 'package:barmusic_admin/core/erros/failures.dart';
import 'package:barmusic_admin/core/services/connectivity_service.dart';
import 'package:barmusic_admin/features/domain/entities/manager_entity.dart';
import 'package:barmusic_admin/features/domain/repositories/auth_repository.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:dartz/dartz.dart';

abstract class LoginWithEmail {
  Future<Either<Failure, ManagerEntity>> call(ManagerEntity manager);
}

class LoginWithEmailImp implements LoginWithEmail {
  final AuthRepository _repository;
  final ConnectivityService _service;

  LoginWithEmailImp(this._repository, this._service);

  @override
  Future<Either<Failure, ManagerEntity>> call(ManagerEntity manager) async {
    var result = await _service.isOnline();
    if (result.isLeft()) {
      result.map((r) => null);
      return Left(ConnectionError(
          message: 'Verifique sua conexão com a internet e tente novamente'));
    }

    if (!manager.isValidEmail) {
      return Left(ErrorLoginEmail(message: 'E-mail inválido'));
    } else if (!manager.isValidPassword) {
      return Left(ErrorLoginEmail(message: 'Senha inválida'));
    }

    return await _repository.loginWithEmail(manager);
  }
}`

     login_with_email_test.dart

` import 'package:barmusic_admin/core/erros/error_login.dart';
import 'package:barmusic_admin/core/services/connectivity_service.dart';
import 'package:barmusic_admin/features/domain/entities/manager_entity.dart';
import 'package:barmusic_admin/features/domain/repositories/auth_repository.dart';
import 'package:barmusic_admin/features/domain/usecases/auth/login_with_email.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';

import 'login_with_email_test.mocks.dart';

// @GenerateMocks([AuthRepository, ConnectivityService])
@GenerateNiceMocks(
    [MockSpec<AuthRepository>(), MockSpec<ConnectivityService>()])
void main() {
  final repository = MockAuthRepository();
  final service = MockConnectivityService();
  final usecase = LoginWithEmailImp(repository, service);

  setUpAll(() {
    when(service.isOnline()).thenAnswer((_) async => Right(unit));
  });

  test('should consume repository loginEmail', () async {
    var user = ManagerEntity(email: 'test@gmail.com', password: 'teste');
    when(repository.loginWithEmail(user)).thenAnswer((_) async => Right(user));
    var result = await usecase(ManagerEntity.withEmailAndPass(
        email: "test@gmail.com", password: "teste"));

    expect(result, Right(user));
  });
}`


问:
Using the same docker images for all the jobs in a workflow of Github actions
I want to use the same container for all the jobs in the workflow. However for every job, it fetches the image. Is there any way to override this and get the image before hand and spin off containers from this image.

```<code>jobs:
  name: job1
  runs-on: ubuntu-latest
  container: alpine/hello-world
  steps:
    ......
    ......

  name: job2
  runs-on: ubuntu-latest
  container: alpine/hello-world
  strategy:
   matrix: ['abc','def']
  steps:
    ......
    ......

</code>```

So in the above, as you can see everytime I use the container, it's going to pull the image. Is there a way to limit this and reuse the image from the job1 and use it in job2. Also in job2, when I use the matrix strategy, it again pulls the image.

Body:
I want to use the same container for all the jobs in the workflow. However for every job, it fetches the image. Is there any way to override this and get the image before hand and spin off containers from this image.

jobs:
  name: job1
  runs-on: ubuntu-latest
  container: alpine/hello-world
  steps:
    ......
    ......

  name: job2
  runs-on: ubuntu-latest
  container: alpine/hello-world
  strategy:
   matrix: ['abc','def']
  steps:
    ......
    ......

So in the above, as you can see everytime I use the container, it's going to pull the image. Is there a way to limit this and reuse the image from the job1 and use it in job2. Also in job2, when I use the matrix strategy, it again pulls the image.


问:
How to read errors when compiling from source code
Goal:

Compile multiple libraries from source code to ultimately install a fully compiled version of FFmpeg with desirable libraries attached.

Problem:

During the compilation, all libraries (seemingly) are successful until liblv2 is reached.

Error output via terminal:

```<code>building lv2 - version 1.18.10
=======================
Downloading https://lv2plug.in/spec/lv2-1.18.10.tar.xz as lv2-1.18.10.tar.bz2
... Done
Extracted lv2-1.18.10.tar.bz2
$ python3 ./waf configure --prefix=/home/jman/tmp/ffmpeg/ffmpeg-build/workspace --lv2-user
python3: can't open file '/home/jman/tmp/ffmpeg/ffmpeg-build/packages/lv2-1.18.10/./waf': [Errno 2] No such file or directory

Failed to Execute python3 ./waf configure --prefix=/home/jman/tmp/ffmpeg/ffmpeg-build/workspace --lv2-user
</code>```

Where I need guidance:

```<code>python3: can't open file '/home/jman/tmp/ffmpeg/ffmpeg-build/packages/lv2-1.18.10/./waf': [Errno 2] No such file or directory
</code>```

My question:

What does this part mean?

```<code>lv2-1.18.10/./waf'

specifically the part /./
</code>```

My best guess so far is it:

obviously is looking for a directory it can't find (perhaps because it truly doesn't exist)

The missing 'waf' directory should be located inside either the "${PACKAGES}" or "${WORKSPACE}" directory.

The ${PACKAGES}" path in this script should = /home/jman/tmp/ffmpeg/ffmpeg-build/packages

The ${WORKSPACE}" path in this script should = /home/jman/tmp/ffmpeg/ffmpeg-build/workspace

The full build script:

https://github.com/slyfox1186/ffmpeg-build-script/blob/master/scripts/build-ffmpeg

I tried my best to make this worth sometimes time without giving too much info... sorry if I don't meet the expectations of this forum.

Am I even close?

Body:
Goal:

Compile multiple libraries from source code to ultimately install a fully compiled version of FFmpeg with desirable libraries attached.

Problem:

During the compilation, all libraries (seemingly) are successful until liblv2 is reached.

Error output via terminal:

building lv2 - version 1.18.10
=======================
Downloading https://lv2plug.in/spec/lv2-1.18.10.tar.xz as lv2-1.18.10.tar.bz2
... Done
Extracted lv2-1.18.10.tar.bz2
$ python3 ./waf configure --prefix=/home/jman/tmp/ffmpeg/ffmpeg-build/workspace --lv2-user
python3: can't open file '/home/jman/tmp/ffmpeg/ffmpeg-build/packages/lv2-1.18.10/./waf': [Errno 2] No such file or directory

Failed to Execute python3 ./waf configure --prefix=/home/jman/tmp/ffmpeg/ffmpeg-build/workspace --lv2-user

Where I need guidance:

python3: can't open file '/home/jman/tmp/ffmpeg/ffmpeg-build/packages/lv2-1.18.10/./waf': [Errno 2] No such file or directory

My question:

What does this part mean?

lv2-1.18.10/./waf'

specifically the part /./

My best guess so far is it:

obviously is looking for a directory it can't find (perhaps because it truly doesn't exist)

The missing 'waf' directory should be located inside either the "${PACKAGES}" or "${WORKSPACE}" directory.

The ${PACKAGES}" path in this script should = /home/jman/tmp/ffmpeg/ffmpeg-build/packages

The ${WORKSPACE}" path in this script should = /home/jman/tmp/ffmpeg/ffmpeg-build/workspace

The full build script:

https://github.com/slyfox1186/ffmpeg-build-script/blob/master/scripts/build-ffmpeg

I tried my best to make this worth sometimes time without giving too much info... sorry if I don't meet the expectations of this forum.

Am I even close?


问:
React native firestore not working properly because of undefined FirebaseStorageTypes.TaskSnapshot ref
I have a react native app and I am trying to save a post using firestore. I am using @react-native-firebase/firestore and am using the following code:
`

```<code>import firebase from "@react-native-firebase/app";
import "@react-native-firebase/firestore";
import "@react-native-firebase/storage";

export const saveMediaToStorage = (media, path) =>
  new Promise((resolve, reject) => {
    const fileRef = firebase.storage().ref().child(path);

    fetch(media)
      .then((response) => response.blob())
      .then((blob) => fileRef.put(blob))
      .then((task) => {
        task.ref.getDownloadURL();
      })
      .then((downloadUrl) => {
        // console.log(downloadUrl);
        resolve(downloadUrl);
      })
      .catch((error) => {
        console.log(error);
        reject();
      });
  });

</code>```

Response, blob and task all look good and task variable looks like this:

```<code>Object {
  "bytesTransferred": 2274761,
  "metadata": Object {
    "bucket": "_______.appspot.com",
    "contentDisposition": "inline; filename*=utf-8''image2",
    "contentEncoding": "identity",
    "contentType": "image/jpeg",
    "fullPath": "post/*****/****/image1",
    "generation": "1672255330334821",
    "md5Hash": "vVYL9wVo/***==",
    "metageneration": "1",
    "name": "image2",
    "size": 2274761,
    "timeCreated": "2022-12-28T19:22:10Z",
    "updated": "2022-12-28T19:22:10Z",
  },
  "state": "success",
  "totalBytes": 2274761,
}
</code>```

I also checked firebase and see that the images are saved in the storage, but it looks like the issue is with the download url.

task.ref.getDownloadUrl() returns undefined because task.ref is undefined. Any idea what might be going wrong?

I have been working in an expo managed workflow and was using firebase/firebase-storage, and it was working fine, but I recently ejected and switched to a bare workflow in android and started using @react-native-firebase/firestore instead, which is when it broke. I added the required permissions for android (READ/WRITE_EXTERNAL_STORAGE), but I'm wondering if I am missing something android-specific, or if the syntax is different for @react-native-firebase.

Body:
I have a react native app and I am trying to save a post using firestore. I am using @react-native-firebase/firestore and am using the following code:
`

import firebase from "@react-native-firebase/app";
import "@react-native-firebase/firestore";
import "@react-native-firebase/storage";

export const saveMediaToStorage = (media, path) =>
  new Promise((resolve, reject) => {
    const fileRef = firebase.storage().ref().child(path);

    fetch(media)
      .then((response) => response.blob())
      .then((blob) => fileRef.put(blob))
      .then((task) => {
        task.ref.getDownloadURL();
      })
      .then((downloadUrl) => {
        // console.log(downloadUrl);
        resolve(downloadUrl);
      })
      .catch((error) => {
        console.log(error);
        reject();
      });
  });

Response, blob and task all look good and task variable looks like this:

Object {
  "bytesTransferred": 2274761,
  "metadata": Object {
    "bucket": "_______.appspot.com",
    "contentDisposition": "inline; filename*=utf-8''image2",
    "contentEncoding": "identity",
    "contentType": "image/jpeg",
    "fullPath": "post/*****/****/image1",
    "generation": "1672255330334821",
    "md5Hash": "vVYL9wVo/***==",
    "metageneration": "1",
    "name": "image2",
    "size": 2274761,
    "timeCreated": "2022-12-28T19:22:10Z",
    "updated": "2022-12-28T19:22:10Z",
  },
  "state": "success",
  "totalBytes": 2274761,
}

I also checked firebase and see that the images are saved in the storage, but it looks like the issue is with the download url.

task.ref.getDownloadUrl() returns undefined because task.ref is undefined. Any idea what might be going wrong?

I have been working in an expo managed workflow and was using firebase/firebase-storage, and it was working fine, but I recently ejected and switched to a bare workflow in android and started using @react-native-firebase/firestore instead, which is when it broke. I added the required permissions for android (READ/WRITE_EXTERNAL_STORAGE), but I'm wondering if I am missing something android-specific, or if the syntax is different for @react-native-firebase.


问:
JS. How to Break selection/range into fragments per containing blocks and remove inline element formatting?
Lets say we have a div

Lorem ipsum dolor sit amet |consequat pharetra auctor condimentum lacus purus tortor habitasse molestie.

Auctor luctus lacus imperdiet pharetra| consequat egestas faucibus.

```
<p>And user selects a portion similar the one between "|".</p>
<pre class="lang-js prettyprint-override"><code>function getSelectionPortion(){
  const div = document.getElementById('my-div');
  const selection = document.getSelection().getRangeAt(0).cloneContents(); // or extractContents();
  return selection;
}
</code>```

getSelectionPortion() will return the following:

consequat pharetra auctor condimentum lacus purus tortor habitasse molestie.

Auctor luctus lacus imperdiet pharetra

```
<p>now we can get portions of the range by paragraphs, simply by e.g. <code>fragment.querySelectorAll('p')</code>.
And if we extract the range contents and loop over each portion, we can take each <code>strong</code> inside each <code>p</code> and replace with its innerHTML</p>
<pre class="lang-js prettyprint-override"><code>let blocks = getSelectionPortion().querySelectorAll('p');
for (let block of blocks){
  let inlines = block.querySelectorAll('strong');
  for (let inline of inlines){
    inline.replaceWith(inline.innerHTML);
  }
}
</code>```

However, this outputs with additional paragraphs, because extracted fragment closes the paragraph tags. So we end up with

Lorem ipsum dolor sit amet

consequat pharetra auctor condimentum lacus purus tortor habitasse molestie.

Auctor luctus lacus imperdiet pharetra

consequat egestas faucibus.

```

How do you remove the inline tag from the selection without creating additional block level elements with fragment? Is there a way to divide the range into peaces instead of its extract?

Body:
Lets say we have a div

Lorem ipsum dolor sit amet |consequat pharetra auctor condimentum lacus purus tortor habitasse molestie.

Auctor luctus lacus imperdiet pharetra| consequat egestas faucibus.

And user selects a portion similar the one between "|".

function getSelectionPortion(){
  const div = document.getElementById('my-div');
  const selection = document.getSelection().getRangeAt(0).cloneContents(); // or extractContents();
  return selection;
}

getSelectionPortion() will return the following:

consequat pharetra auctor condimentum lacus purus tortor habitasse molestie.

Auctor luctus lacus imperdiet pharetra

now we can get portions of the range by paragraphs, simply by e.g. fragment.querySelectorAll('p').
And if we extract the range contents and loop over each portion, we can take each strong inside each p and replace with its innerHTML

let blocks = getSelectionPortion().querySelectorAll('p');
for (let block of blocks){
  let inlines = block.querySelectorAll('strong');
  for (let inline of inlines){
    inline.replaceWith(inline.innerHTML);
  }
}

However, this outputs with additional paragraphs, because extracted fragment closes the paragraph tags. So we end up with

Lorem ipsum dolor sit amet

consequat pharetra auctor condimentum lacus purus tortor habitasse molestie.

Auctor luctus lacus imperdiet pharetra

consequat egestas faucibus.

How do you remove the inline tag from the selection without creating additional block level elements with fragment? Is there a way to divide the range into peaces instead of its extract?


问:
how i can use django context inside context
Well I know that what I'm doing is not very feasible, but I wanted to know if there's any way to do this.I want to create a portfolio blog to post some 3d renders, for that I want to have more control over the structure of the page. for this I created two models (one for the post and another to receive the images, linking them to the post through a foreign key) so that I could have an indefinite number of images, the problem came when I decided that I wanted to be able to choose the one positioning of the images according to my need/desire, for that I did the following:

I used django summernote temporarily to be able to test the written posts, I knew that it would probably not be possible to do this because the content sent from the models is static.

I have the following models:

```<code>class Post(models.Model):
    titulo_post=models.CharField(max_length=255, verbose_name='Titulo')
    autor_post=models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='autor')
    data_post=models.DateTimeField(default=timezone.now, verbose_name='Data publicação')
    conteudo_post =models.TextField()
    publicado_post=models.BooleanField(default=False, verbose_name='Status publicação')

    def __str__(self) :
        return self.titulo_post
</code>```

and:

```<code>class Estudo(models.Model):
    imagem=models.ImageField(upload_to='estd_img/%Y/%m/%d', blank=True,  null=True)
    post=models.ForeignKey(Post, on_delete=models.CASCADE)
</code>```

I tried to put the following value in the field "conteudo_post" through the administrative area to  see if it would work

```<code>  <div class="container">
    <div class="col-10 mx-auto">
      <img class="img-fluid " src="{{imagem.0.url}}" alt="">
    </div>
  </div>
</code>```

as I thought it didn't work,  when I use {{post_conteudo}} the rendered html displays an escaped version of the content, when I use {{post_conteudo |safe}} it creates the image container, but is not able to find it. when checking the browser's developer mode I can see that the value of {{image.0.url}} was not processed and it remains in that format in the final html

Body:
Well I know that what I'm doing is not very feasible, but I wanted to know if there's any way to do this.I want to create a portfolio blog to post some 3d renders, for that I want to have more control over the structure of the page. for this I created two models (one for the post and another to receive the images, linking them to the post through a foreign key) so that I could have an indefinite number of images, the problem came when I decided that I wanted to be able to choose the one positioning of the images according to my need/desire, for that I did the following:

I used django summernote temporarily to be able to test the written posts, I knew that it would probably not be possible to do this because the content sent from the models is static.

I have the following models:

class Post(models.Model):
    titulo_post=models.CharField(max_length=255, verbose_name='Titulo')
    autor_post=models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='autor')
    data_post=models.DateTimeField(default=timezone.now, verbose_name='Data publicação')
    conteudo_post =models.TextField()
    publicado_post=models.BooleanField(default=False, verbose_name='Status publicação')

    def __str__(self) :
        return self.titulo_post

and:

class Estudo(models.Model):
    imagem=models.ImageField(upload_to='estd_img/%Y/%m/%d', blank=True,  null=True)
    post=models.ForeignKey(Post, on_delete=models.CASCADE)

I tried to put the following value in the field "conteudo_post" through the administrative area to  see if it would work

as I thought it didn't work,  when I use {{post_conteudo}} the rendered html displays an escaped version of the content, when I use {{post_conteudo |safe}} it creates the image container, but is not able to find it. when checking the browser's developer mode I can see that the value of {{image.0.url}} was not processed and it remains in that format in the final html


问:
How can I send jquery ajax result to containing scope?
I'm using the jQuery validation plugin, which is very impressive. I define some custom validation methods with custom error messages, and all works well. I just write a function that takes the value of an input element, and the element itself, and specify that function in rules for elements with a given name attribute. The function must return true if the element is valid, and false if it is invalid.

But now I need to do a validation that involves an ajax call. I use code like this:

```<code>let retval = true;
$.get(`url`, function(data) {
    console.log( "success: ");
    console.log(data);
    retval = true;
}).fail(function(data) {
    console.log( "error: " );
    console.log(data);
    retval = false;
})
return retval;
</code>```

The idea being to let the result of the ajax call determine whether the validation method returns true or false. But stepping through it in Chrome developer tools, the return statement is never reached. So the .fail() function that sets retval to false has no effect: stepping off the end of the .fail() function goes into jQuery code, and the validation method returns true. How can I get the function containing the ajax call to return a value that reflects the status of the call?

Body:
I'm using the jQuery validation plugin, which is very impressive. I define some custom validation methods with custom error messages, and all works well. I just write a function that takes the value of an input element, and the element itself, and specify that function in rules for elements with a given name attribute. The function must return true if the element is valid, and false if it is invalid.

But now I need to do a validation that involves an ajax call. I use code like this:

let retval = true;
$.get(`url`, function(data) {
    console.log( "success: ");
    console.log(data);
    retval = true;
}).fail(function(data) {
    console.log( "error: " );
    console.log(data);
    retval = false;
})
return retval;

The idea being to let the result of the ajax call determine whether the validation method returns true or false. But stepping through it in Chrome developer tools, the return statement is never reached. So the .fail() function that sets retval to false has no effect: stepping off the end of the .fail() function goes into jQuery code, and the validation method returns true. How can I get the function containing the ajax call to return a value that reflects the status of the call?


问:
My wordpress home_url and site_url are switched
I have a WordPress setup(admin.xyz.com) which is used as backend to serve a frontend with an angular app(xyz.com). I manage my backend/admin panel from admin.xyz.com/wp-admin. But, I don't want the WordPress to have a frontend of its own at admin.xyz.com, but still want to access the admin panel at admin.xyz.com/wp-admin.

Many blogs suggest changing the WP_SITEURL in the wp-config.php file to my actual site at xyz.com. But if I do so, the admin-panel throws the critical error. Instead, if I change the WP_HOME to xyz.com, it does actually work and I can access my backend admin panel at admin.xyz.com/wp-admin and also admin.xyz.com redirects me to xyz.com, as intended. And interestingly, the settings>general shows my WordPress Address (URL) to be admin.xyz.com and Site Address (URL) to be xyz.com. Also, all my permalinks are also fixed for the WooCommerce products pages, which previously showed admin.xyz.com/products/* instead of xyz.com/products/*.

But now, the WooCommerce itself starts throwing other errors and its Api with OAuth 1.0 also stops working. The WooCommerce errors are like "There was an error getting your stats. Please try again." The OAuth 1.0 Api errors are like "Invalid signature - provided signature does not match."


问:
Azure Action Group email notifications - fail, not reliable
This is part public awareness and part actual question for better workarounds.

Overall, we have recently discovered (the hard way) that emailing via an Azure Action Group is unreliable and occasionally fails. Basically, sometimes their IPs get blacklisted for various reasons (very common).  They have nothing in place to alert those relying on an email notification that it failed, even though they have all the information they need to do so (they showed me a screenshot showing the SMTP failure due to the IP blacklisting from their log).  The Azure portal will still show "fired".  And, so, it just fails silently in the background with no indication to the user it was never sent.  According to one of the technical Azure reps we have discussed this with:

The way of identifying a failure is to evaluate any kind of rejection message received from the target server but those are not guaranteed and not generated in all scenarios.  Take into account that email actions are provided free of charge and performing post-send operations to try and verify delivery would consume additional computing that would make providing this notification mechanism free of charge less desirable

I know that many rely on these for production notifications of various scenarios.  You should not rely on this going forward, or at least have a backup in place (e.g. SMS, web-hook, etc).

I would like to know if anyone has experienced this as well and, if so, what is the better, more reliable method to use.

Thanks in advance!


问:
c++ Template Class Syntax for Methods
I am learning templates and am struggling to set up my put method without compiler errors. Can someone point me in the right direction? The commented sections are not implemented yet, but based on an Integer-key, String-value implementation.

The concrete error I am having: Severity    Code    Description Project File    Line    Suppression State
Error   C2923   'HashTable<int,std::string>::HashItem': 'key' is not a valid template type argument for parameter 'Key'

```<code>#pragma once

#include <cmath>
#include <iostream>
#include <list>

using namespace std;

template<typename Key, typename Value>
class HashTable
{
  template<typename Key, typename Value>
  class HashItem {
  public:
    Key key;
    Value value = nullptr;
    bool operator==(const HashItem& hi) const { return key == hi.key && value == hi.value; }
    HashItem(const Key& k, const Value& v)
      : key(k), value(v) {}
    // for part b)
    HashItem& operator=(const Value& v) {
      this->value = v;
      return *this;
    }
    operator string() { return this->value; }
  };

  list<HashItem<Key, Value>>* table;
  int current_total = 0;

  float FILL_LEVEL = 0.8; // Füllgrad, between 0 and 1

  // not const:
  int CAPACITY = 100; // default value

  // for hash functions/preparing for use with strings:
  const int PRIME_CONST = 31;

  int hash_function(string key);
  int hash_function(int key);
  // std::hash?

  void rehash();

public:
  HashTable() {
    cout << "ht cstructed, intitial_capacity is (default:) " << CAPACITY << endl;
  }
  HashTable(int initial_capacity) {
    cout << "ht cstructed, intitial_capacity is " << initial_capacity << endl;
    CAPACITY = initial_capacity;
  }

  //// RULE OF THREE
  //// copy ctor
  //HashTable(HashTable& const ht);
  //// destructor
  //~HashTable();
  //// (copy) assignment operator
  //HashTable& operator=(HashTable& const ht);

  //// RULE OF FIVE
  //// move ctor
  //HashTable(HashTable&& ht); // && -> rvalue
  //// move assignment operator
  //HashTable& operator=(HashTable&& ht);

  //// Hash Table operations
  void put(Key key, Value value) {
    // allocate memory with first put
    if (current_total == 0)
      table = new list<HashItem<key, value>>[CAPACITY];

    HashItem<key, value>* hi = new HashItem(key, value);
    int hash = hash_function(key);

    if (find(table[hash].begin(), table[hash].end(), *hi) == table[hash].end()) {
      // only put if not already in list
      table[hash].push_back(*hi);
    }

    current_total++;
    //cout << "current total is " << current_total << " of " << FILL_LEVEL * CAPACITY << endl;

    // rehash check
    if (current_total > (FILL_LEVEL * CAPACITY)) {
      rehash();
      //cout << "fill level reached: rehashed" << endl;
    }
  }
  //void remove(int key, string value);
  //string get(int key);

  //// for part b)
  //HashItem& get_item(int key) {
  //  int list_index = hash_function(key); // list_index = hash_code
  //  if (!table[list_index].empty()) {
  //    for (auto &list_item : table[list_index]) {
  //      if (key == list_item.key) {
  //        return list_item;
  //      }
  //    }
  //  }
  //  HashItem hi(key, "");
  //  return hi;
  //}

  //friend ostream& operator<<(ostream& os, const HashTable& ht);
  //void clear();
  //bool contains(int key);
  //bool contains_value(string value);

  //// fill levels
  //void set_fill_level(float new_level);
  //float get_fill_level();

  //// b)
  //// Overloading [] operator to access elements in array style
  //HashItem& operator[] (int key) {
  //  if (this != nullptr)
  //    return this->get_item(key);
  //  HashItem hi(key, "");
  //  // stand-in hash item in case not in hash table
  //  return hi;
  //}
};

</code>```

Call in my main.cpp:

```<code>#include <iostream>

#include "HashTable.h"

using namespace std;

#define DEBUG(X) cout << (#X) << " = " << (X) << endl

HashTable<int, string> ht;

void put_test() {
  cout << "--------------- put test ----------------------------------" << endl;
  ht.put(10, "test");
}

int main() {

  put_test();
}
</code>```

Title: c++ Template Class Syntax for Methods

Body:
I am learning templates and am struggling to set up my put method without compiler errors. Can someone point me in the right direction? The commented sections are not implemented yet, but based on an Integer-key, String-value implementation.

The concrete error I am having: Severity    Code    Description Project File    Line    Suppression State
Error   C2923   'HashTable<int,std::string>::HashItem': 'key' is not a valid template type argument for parameter 'Key'

#pragma once

#include <cmath>
#include <iostream>
#include <list>

using namespace std;

template<typename Key, typename Value>
class HashTable
{
  template<typename Key, typename Value>
  class HashItem {
  public:
    Key key;
    Value value = nullptr;
    bool operator==(const HashItem& hi) const { return key == hi.key && value == hi.value; }
    HashItem(const Key& k, const Value& v)
      : key(k), value(v) {}
    // for part b)
    HashItem& operator=(const Value& v) {
      this->value = v;
      return *this;
    }
    operator string() { return this->value; }
  };

  list<HashItem<Key, Value>>* table;
  int current_total = 0;

  float FILL_LEVEL = 0.8; // Füllgrad, between 0 and 1

  // not const:
  int CAPACITY = 100; // default value

  // for hash functions/preparing for use with strings:
  const int PRIME_CONST = 31;

  int hash_function(string key);
  int hash_function(int key);
  // std::hash?

  void rehash();

public:
  HashTable() {
    cout << "ht cstructed, intitial_capacity is (default:) " << CAPACITY << endl;
  }
  HashTable(int initial_capacity) {
    cout << "ht cstructed, intitial_capacity is " << initial_capacity << endl;
    CAPACITY = initial_capacity;
  }

  //// RULE OF THREE
  //// copy ctor
  //HashTable(HashTable& const ht);
  //// destructor
  //~HashTable();
  //// (copy) assignment operator
  //HashTable& operator=(HashTable& const ht);

  //// RULE OF FIVE
  //// move ctor
  //HashTable(HashTable&& ht); // && -> rvalue
  //// move assignment operator
  //HashTable& operator=(HashTable&& ht);

  //// Hash Table operations
  void put(Key key, Value value) {
    // allocate memory with first put
    if (current_total == 0)
      table = new list<HashItem<key, value>>[CAPACITY];

    HashItem<key, value>* hi = new HashItem(key, value);
    int hash = hash_function(key);

    if (find(table[hash].begin(), table[hash].end(), *hi) == table[hash].end()) {
      // only put if not already in list
      table[hash].push_back(*hi);
    }

    current_total++;
    //cout << "current total is " << current_total << " of " << FILL_LEVEL * CAPACITY << endl;

    // rehash check
    if (current_total > (FILL_LEVEL * CAPACITY)) {
      rehash();
      //cout << "fill level reached: rehashed" << endl;
    }
  }
  //void remove(int key, string value);
  //string get(int key);

  //// for part b)
  //HashItem& get_item(int key) {
  //  int list_index = hash_function(key); // list_index = hash_code
  //  if (!table[list_index].empty()) {
  //    for (auto &list_item : table[list_index]) {
  //      if (key == list_item.key) {
  //        return list_item;
  //      }
  //    }
  //  }
  //  HashItem hi(key, "");
  //  return hi;
  //}

  //friend ostream& operator<<(ostream& os, const HashTable& ht);
  //void clear();
  //bool contains(int key);
  //bool contains_value(string value);

  //// fill levels
  //void set_fill_level(float new_level);
  //float get_fill_level();

  //// b)
  //// Overloading [] operator to access elements in array style
  //HashItem& operator[] (int key) {
  //  if (this != nullptr)
  //    return this->get_item(key);
  //  HashItem hi(key, "");
  //  // stand-in hash item in case not in hash table
  //  return hi;
  //}
};

Call in my main.cpp:

#include <iostream>

#include "HashTable.h"

using namespace std;

#define DEBUG(X) cout << (#X) << " = " << (X) << endl

HashTable<int, string> ht;

void put_test() {
  cout << "--------------- put test ----------------------------------" << endl;
  ht.put(10, "test");
}

int main() {

  put_test();
}


问:
How would I make these clock hands rotate in javascript?
I'm a newbie and decided to start learning by writing short programs, but I'm getting a weird result right at the finish line There seems to be no issue in the javascript up until the last part where I type

```<code>    hoursel.style.transform="rotate(${hoursdeg}deg)";
    minutesel.style.transform="rotate(${minutesdeg}deg)";
    secondsel.style.transform="rotate(${secondsdeg}deg)";
</code>```

Then I get no movement on the hands of the clock.

When I replace "rotate(${hoursdeg}deg)" with "rotate(80deg)" for example the code works.

console.log(hoursdeg, minutesdeg, hoursdeg) also works

console.log(secondsel) returns

```<code><div class="seconds" id="seconds"></div>
</code>```

Body:
I'm a newbie and decided to start learning by writing short programs, but I'm getting a weird result right at the finish line There seems to be no issue in the javascript up until the last part where I type

    hoursel.style.transform="rotate(${hoursdeg}deg)";
    minutesel.style.transform="rotate(${minutesdeg}deg)";
    secondsel.style.transform="rotate(${secondsdeg}deg)";

Then I get no movement on the hands of the clock.

When I replace "rotate(${hoursdeg}deg)" with "rotate(80deg)" for example the code works.

console.log(hoursdeg, minutesdeg, hoursdeg) also works

console.log(secondsel) returns


问:
How to force typescript to load .d.ts file containing [declare module ".someExtension"] from npm package (from node_modules directory)
i'm developing a vite plugin which transforms imported modules with custom extensions and turns them into javascript code which export some data (objects specifically).
everything is working fine when i test the plugin. but the problem is that when i use this plugin in a project (trying to simulate the developer experience with the plugin), the files with this custom extension is not recognized by typescript, which is expected of course, so i get this error Cannot find module './filename.someExtension' or its corresponding type declarations.

to keep things simple, i will put here some simple (and fake) examples of what i did, so that the question be clear.

say i have a file with json-like format containing a list of users, and the file has .users extension.
as an example say this is the contents of the file:

[
    {
        name: "john",
        age: 35,
        job: "software engineer",
    },
    // other users
]
```
<p>and the plugin code looks like this:</p>
```import { promises as fs } from "fs";
import type { Plugin } from "vite";

const UsersPlugin: () => Plugin = () => {

  return {
    name: "users-plugin",
    enforce: "pre",
    async load(id) {
      if (id.endsWith(".users")) {
        const src = await fs.readFile(id, "utf-8");
        return { code: src };
      }
      return null;
    },
    async transform(src, id) {
      if (id.endsWith(".users")) {
        const users = JSON.parse(src)
        const code = `
        export users = ${users}
        `
        return {code};
      }
      return null;
    },
  };
};

export default UsersPlugin
```
<p>and the developer (user of the plugin) would import the <code>.users</code> file as follows</p>
```import {users} from '/path/to/file.users'
```
<p>and here where the problem shows up.
the developer will see squiggly line under the <code>'/path/to/file.users'</code> saying <code>Cannot find module '/path/to/file.users' or its corresponding type declarations.ts(2307)</code></p>
<p>what i have tried is to create a <code>users.d.ts</code> file in the root directory of my package so when the plugin is installed the <code>users.d.ts</code> file will be located at <code>node_modules/users.d.ts</code></p>
<p>the content of <code>users.d.ts</code>:</p>
```declare module "*.users" {
  interface User {
    name: string;
    age: number;
    job: string;
  }
  const users: User[];
  export { users };
}
```
<p>this didn't work but if the developer (user of the plugin) puts this file somewhere in his project where it gets detected by typescript it works, or if he/she adds the path to the file in <code>tsconfig.json</code> (<code>"include": ["node_modules/users-plugin/users.d.ts"]</code>) it also works.</p>
<p>i have also tried to add the file in <code>package.json</code> of the package like this:</p>
```"types": "./lib/index.d.ts",
"exports": {
    ...
    "./users": {
      "types": "./users.d.ts"
    },
    ...
},
"files": [
    "lib/**/*",
    "modules.d.ts"
],
```

(i saw something similar in the vite's code base itself for the client.d.ts file)
but it didn't work.
i tried also puting the users.d.ts file under the lib directory and add the /// <reference types="./users" /> tag at the top of index.d.ts file, but none of these works.

what i want is, simply, when the user of my plugin installs the plugin from npm registry and adds it to his vite.config.ts's plugins list, the imports of files with .users extension gets typed properly without the need of adding any extra config from the developer.
how can i achieve this ?

Body:
i'm developing a vite plugin which transforms imported modules with custom extensions and turns them into javascript code which export some data (objects specifically).
everything is working fine when i test the plugin. but the problem is that when i use this plugin in a project (trying to simulate the developer experience with the plugin), the files with this custom extension is not recognized by typescript, which is expected of course, so i get this error Cannot find module './filename.someExtension' or its corresponding type declarations.

to keep things simple, i will put here some simple (and fake) examples of what i did, so that the question be clear.

say i have a file with json-like format containing a list of users, and the file has .users extension.
as an example say this is the contents of the file:

[
    {
        name: "john",
        age: 35,
        job: "software engineer",
    },
    // other users
]

and the plugin code looks like this:

import { promises as fs } from "fs";
import type { Plugin } from "vite";

const UsersPlugin: () => Plugin = () => {

  return {
    name: "users-plugin",
    enforce: "pre",
    async load(id) {
      if (id.endsWith(".users")) {
        const src = await fs.readFile(id, "utf-8");
        return { code: src };
      }
      return null;
    },
    async transform(src, id) {
      if (id.endsWith(".users")) {
        const users = JSON.parse(src)
        const code = `
        export users = ${users}
        `
        return {code};
      }
      return null;
    },
  };
};

export default UsersPlugin

and the developer (user of the plugin) would import the .users file as follows

import {users} from '/path/to/file.users'

and here where the problem shows up.
the developer will see squiggly line under the '/path/to/file.users' saying Cannot find module '/path/to/file.users' or its corresponding type declarations.ts(2307)

what i have tried is to create a users.d.ts file in the root directory of my package so when the plugin is installed the users.d.ts file will be located at node_modules/users.d.ts

the content of users.d.ts:

declare module "*.users" {
  interface User {
    name: string;
    age: number;
    job: string;
  }
  const users: User[];
  export { users };
}

this didn't work but if the developer (user of the plugin) puts this file somewhere in his project where it gets detected by typescript it works, or if he/she adds the path to the file in tsconfig.json ("include": ["node_modules/users-plugin/users.d.ts"]) it also works.

i have also tried to add the file in package.json of the package like this:

"types": "./lib/index.d.ts",
"exports": {
    ...
    "./users": {
      "types": "./users.d.ts"
    },
    ...
},
"files": [
    "lib/**/*",
    "modules.d.ts"
],

(i saw something similar in the vite's code base itself for the client.d.ts file)
but it didn't work.
i tried also puting the users.d.ts file under the lib directory and add the /// <reference types="./users" /> tag at the top of index.d.ts file, but none of these works.

what i want is, simply, when the user of my plugin installs the plugin from npm registry and adds it to his vite.config.ts's plugins list, the imports of files with .users extension gets typed properly without the need of adding any extra config from the developer.
how can i achieve this ?


问:
What problem causes exit code -1073741819 (0xC0000005) while pyqtSignal.emit()?
I use pyqt5 and python 3.9 in PyCharm.

This is my minimal code

```<code>import sys
from PyQt5.QtCore import QObject, QRunnable, pyqtSignal, QThreadPool
from PyQt5.QtWidgets import QMainWindow, QApplication

class Launcher(QRunnable, QObject):
    test_signal = pyqtSignal()

    def __init__(self):
        super().__init__()

    def run(self):
        print("This will be printed!")
        self.test_signal.emit()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        launcher = Launcher()
        launcher.test_signal.connect(self.sayHi)
        self.threadpool = QThreadPool()
        self.threadpool.start(launcher)

    def sayHi(self):
        print("Hi")  # This won't be printed

def main():
    app = QApplication(sys.argv)
    window = MainWindow()

    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

</code>```

And I get an error

Process finished with exit code -1073741819 (0xC0000005)

What should I do to avoid it?
I dont get this error if my test_signal is independent class nested from QObject. But I dont understand the difference between this pyqtSignal instances.

Body:
I use pyqt5 and python 3.9 in PyCharm.

This is my minimal code

import sys
from PyQt5.QtCore import QObject, QRunnable, pyqtSignal, QThreadPool
from PyQt5.QtWidgets import QMainWindow, QApplication

class Launcher(QRunnable, QObject):
    test_signal = pyqtSignal()

    def __init__(self):
        super().__init__()

    def run(self):
        print("This will be printed!")
        self.test_signal.emit()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        launcher = Launcher()
        launcher.test_signal.connect(self.sayHi)
        self.threadpool = QThreadPool()
        self.threadpool.start(launcher)

    def sayHi(self):
        print("Hi")  # This won't be printed

def main():
    app = QApplication(sys.argv)
    window = MainWindow()

    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

And I get an error

Process finished with exit code -1073741819 (0xC0000005)

What should I do to avoid it?
I dont get this error if my test_signal is independent class nested from QObject. But I dont understand the difference between this pyqtSignal instances.


问:
Formatting Plotly Express Null Values Heatmap
I am hoping to get some help with a Plotly Express Null Values Heatmap formatting question.

I am trying to visualize null values using Plotly express because it's interactive for 106 columns that have null values in my dataset. I was hoping to keep all 106 values in the same heatmap if possible. The problem is, all of the 106 values are not displaying, and they are not lined up properly. I would also like to get rid of the legend or even update it so that yellow = null values and blue = non-null values. Any help would be much appreciated!

Here's a screenshot for reference. Thank you!

Here's the code:
`

```<code>fig = px.imshow(df.isnull())
fig.update_layout(
    title = "Numerical Variables Heatmap")
#fig.update_xaxes(tickangle=45)
fig.update_layout(barmode='group', bargap=0.30,bargroupgap=0.0)
fig.show()
</code>```

`

I have tried updating/formatting the axes, layout, unfortunately to no avail. I have also tried making the chart area larger, flipping the axes, but unfortunately to no avail.

Body:
I am hoping to get some help with a Plotly Express Null Values Heatmap formatting question.

I am trying to visualize null values using Plotly express because it's interactive for 106 columns that have null values in my dataset. I was hoping to keep all 106 values in the same heatmap if possible. The problem is, all of the 106 values are not displaying, and they are not lined up properly. I would also like to get rid of the legend or even update it so that yellow = null values and blue = non-null values. Any help would be much appreciated!

Here's a screenshot for reference. Thank you!

Here's the code:
`

fig = px.imshow(df.isnull())
fig.update_layout(
    title = "Numerical Variables Heatmap")
#fig.update_xaxes(tickangle=45)
fig.update_layout(barmode='group', bargap=0.30,bargroupgap=0.0)
fig.show()

`

I have tried updating/formatting the axes, layout, unfortunately to no avail. I have also tried making the chart area larger, flipping the axes, but unfortunately to no avail.


问:
BigCommerce: Change My Orders to display orders by Order Date desc instead of Order ID
We're thinking about loading in some prior order data from another system to allow our customers to see them in one place under My Orders section of My Account. We can back date the order when creating via API, they are assigned a new BC order ID which is OK.

The problem is by default orders-list.html in theme lists the orders based on order number descending, putting all our "old" orders at the top of the list.

Is there a way to change this template to be based on the order date instead?

I'm thinking maybe the change needs to happen at the entry of the loop  {{#each orders}}


问:
Django detail view not rendering static files
Hello my I have a Django project which works fine but the problem I usually get is from my Detail View, it does not render statics files. And when I check the output from my terminal I see that my Detail View url name is joined to my static/assets link.

My static settings

```<code># Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(CORE_DIR, 'apps/static/'),
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(CORE_DIR, 'media')
# Default user model
AUTH_USER_MODEL = 'accounts.CustomUser'

# My urls.py file

from django.urls import path
from .views import *

app_name = 'base'

urlpatterns = [
   path("", HomePage.as_view(), name="home"),
   path("jobs", Jobs.as_view(), name="jobs"),
   path('jobs-short', Jobs_List.as_view(), name="jobs-short-list"),
   path('job-detail/<int:pk>', Job_Detail.as_view(), name='job-detail'),
   path("company", Company.as_view(), name="companies"),
   path('candidate', Candidate.as_view(), name="candidates"),
   path('candidate-detail/<int:pk>', CandidateDetail.as_view(), name="candidate-detail"),
   path("about-us", about_us, name="about"),
   path("candidates", candidates, name="candidate"),

]

[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/plugins.css HTTP/1.1" 404 4068
Not Found: /job-detail/static/assets/css/style.css
[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/style.css HTTP/1.1" 404 4062
Not Found: /job-detail/static/assets/css/templete.css
[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/templete.css HTTP/1.1" 404 4071
Not Found: /job-detail/static/assets/css/skin/skin-1.css
[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/skin/skin-1.css HTTP/1.1" 404 4080
Not Found: /job-detail/static/assets/plugins/datepicker/css/bootstrap-datetimepicker.min.cs
</code>```

Body:
Hello my I have a Django project which works fine but the problem I usually get is from my Detail View, it does not render statics files. And when I check the output from my terminal I see that my Detail View url name is joined to my static/assets link.

My static settings

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(CORE_DIR, 'apps/static/'),
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(CORE_DIR, 'media')
# Default user model
AUTH_USER_MODEL = 'accounts.CustomUser'

# My urls.py file

from django.urls import path
from .views import *

app_name = 'base'

urlpatterns = [
   path("", HomePage.as_view(), name="home"),
   path("jobs", Jobs.as_view(), name="jobs"),
   path('jobs-short', Jobs_List.as_view(), name="jobs-short-list"),
   path('job-detail/<int:pk>', Job_Detail.as_view(), name='job-detail'),
   path("company", Company.as_view(), name="companies"),
   path('candidate', Candidate.as_view(), name="candidates"),
   path('candidate-detail/<int:pk>', CandidateDetail.as_view(), name="candidate-detail"),
   path("about-us", about_us, name="about"),
   path("candidates", candidates, name="candidate"),

]

[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/plugins.css HTTP/1.1" 404 4068
Not Found: /job-detail/static/assets/css/style.css
[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/style.css HTTP/1.1" 404 4062
Not Found: /job-detail/static/assets/css/templete.css
[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/templete.css HTTP/1.1" 404 4071
Not Found: /job-detail/static/assets/css/skin/skin-1.css
[28/Dec/2022 21:32:03] "GET /job-detail/static/assets/css/skin/skin-1.css HTTP/1.1" 404 4080
Not Found: /job-detail/static/assets/plugins/datepicker/css/bootstrap-datetimepicker.min.cs


问:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')' ERROR
```<code>private void btnSave_Click(object sender, EventArgs e)
        {
           if (txtQuantity.Text == "" || Convert.ToInt32(txtQuantity.Text) > Stock)
               // if (txtQuantity.Text == "")
            {
                MessageBox.Show("Enter Correct Quantity");
            }
            else
            {
                int total = Convert.ToInt32(txtQuantity.Text) * Convert.ToInt32(txtPrice.Text);
                DataGridViewRow newRow = new DataGridViewRow();

                newRow.CreateCells(DGVBill);
                newRow.Cells[0].Value = n + 1;
                newRow.Cells[1].Value = txtMedicine.Text;
                newRow.Cells[2].Value = txtQuantity.Text;
                newRow.Cells[3].Value = txtPrice.Text;
                newRow.Cells[4].Value = total;
                DGVBill.Rows.Add(newRow);
                GrdTotal = GrdTotal + total;
                LblTotal.Text = "EGP " + GrdTotal;
                n++;
                UpdateQnty();
            }
        }
    }
}
</code>```

It always shows this error:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')' " on this line "newRow.Cells[0].Value = n + 1;

I tried to re-write and delete this line and when I deleted this line to see what would happen; it shows the same error but on the next line and so on

Body:
private void btnSave_Click(object sender, EventArgs e)
        {
           if (txtQuantity.Text == "" || Convert.ToInt32(txtQuantity.Text) > Stock)
               // if (txtQuantity.Text == "")
            {
                MessageBox.Show("Enter Correct Quantity");
            }
            else
            {
                int total = Convert.ToInt32(txtQuantity.Text) * Convert.ToInt32(txtPrice.Text);
                DataGridViewRow newRow = new DataGridViewRow();

                newRow.CreateCells(DGVBill);
                newRow.Cells[0].Value = n + 1;
                newRow.Cells[1].Value = txtMedicine.Text;
                newRow.Cells[2].Value = txtQuantity.Text;
                newRow.Cells[3].Value = txtPrice.Text;
                newRow.Cells[4].Value = total;
                DGVBill.Rows.Add(newRow);
                GrdTotal = GrdTotal + total;
                LblTotal.Text = "EGP " + GrdTotal;
                n++;
                UpdateQnty();
            }
        }
    }
}

It always shows this error:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')' " on this line "newRow.Cells[0].Value = n + 1;

I tried to re-write and delete this line and when I deleted this line to see what would happen; it shows the same error but on the next line and so on


问:
wfastcgi 500 error in flask app when trying to plot
Edit: Originally thought this was IIS issue, but looks like it's FastCgiModule causing the issue.

To be clear, the WebApp itself works, it only fails when I choose "Image Test" from the dropdown (see code below) menu on the site. Specifically, it fails on the df.plot line, and I can't figure out why.

```<code>from flask import Flask, request
import pandas as pd

app = Flask(__name__)

html = '''
<h1>Discovery Capital</h1>
<h2>Report Generator</h2>
<p>
<form action="/submitted" method="post">
  <label for="reports">Choose a Report:</label>
  <select id="reports" name="reports">
    <option value="img_test">Image Test</option>
  </select>
  <input type="submit">
</form>
'''

@app.route("/")
def index():
    return html

@app.route("/submitted", methods=['POST'])
def show():
    select = request.form.get("reports")

    if select == 'img_test':
        df = pd.DataFrame([1,2,3,4,5])
        df.plot()
        plt.close()
        result = "Success"

    else:
        result = "Not Available"

    return result

if __name__ == "__main__":
    app.run()
</code>```

Appreciate the help!

Edit: Here's the log from failed request tracing:

Body:
Edit: Originally thought this was IIS issue, but looks like it's FastCgiModule causing the issue.

To be clear, the WebApp itself works, it only fails when I choose "Image Test" from the dropdown (see code below) menu on the site. Specifically, it fails on the df.plot line, and I can't figure out why.

from flask import Flask, request
import pandas as pd

app = Flask(__name__)

html = '''

Discovery Capital

Report Generator

<form action="/submitted" method="post">
  Choose a Report:
  <select id="reports" name="reports">
    <option value="img_test">Image Test</option>
  </select>
  <input type="submit">
</form>
'''

@app.route("/")
def index():
    return html

@app.route("/submitted", methods=['POST'])
def show():
    select = request.form.get("reports")

    if select == 'img_test':
        df = pd.DataFrame([1,2,3,4,5])
        df.plot()
        plt.close()
        result = "Success"

    else:
        result = "Not Available"

    return result

if __name__ == "__main__":
    app.run()

Appreciate the help!

Edit: Here's the log from failed request tracing:


问:
How can I get this photo back to directory?
I know a cliche but I am trying to make a kanye quote app where it shows new Kanye quotes as shown below:

```<code>
from tkinter import *
import requests

def get_quote():
    response = requests.get(url="https://api.kanye.rest")
    response.raise_for_status()
    data = response.json()
    quote = data["quote"]
    canvas.itemconfig(quote_text, text=quote)

window = Tk()
window.title("Kanye Says...")
window.config(padx=50, pady=50)

canvas = Canvas(width=300, height=414)
background_img = PhotoImage(file="background.png")
canvas.create_image(150, 207, image=background_img)
quote_text = canvas.create_text(150, 207, text="Kanye Quote Goes HERE", width=250, font=("Arial", 30, "bold"),
                                fill="black")
canvas.grid(row=0, column=0)

kanye_img = PhotoImage(file="kanye.png")
kanye_button = Button(image=kanye_img, highlightthickness=0, command=get_quote)
kanye_button.grid(row=1, column=0)

window.mainloop()

</code>```

Every time I click but I am being told that the photo is not in my directiory even though it is in the same folder. I don't believe it's to do with the code but I've moved them out and then back in but it still won't work.
Anyone else ever faced the issue and can help?
Files
It may be because the photos corrupted but I can open it on desktop.

Moved into different folders then back.
Re-named it then tried again.
I can't find the original photo online so I can't re download

Body:
I know a cliche but I am trying to make a kanye quote app where it shows new Kanye quotes as shown below:

from tkinter import *
import requests

def get_quote():
    response = requests.get(url="https://api.kanye.rest")
    response.raise_for_status()
    data = response.json()
    quote = data["quote"]
    canvas.itemconfig(quote_text, text=quote)

window = Tk()
window.title("Kanye Says...")
window.config(padx=50, pady=50)

canvas = Canvas(width=300, height=414)
background_img = PhotoImage(file="background.png")
canvas.create_image(150, 207, image=background_img)
quote_text = canvas.create_text(150, 207, text="Kanye Quote Goes HERE", width=250, font=("Arial", 30, "bold"),
                                fill="black")
canvas.grid(row=0, column=0)

kanye_img = PhotoImage(file="kanye.png")
kanye_button = Button(image=kanye_img, highlightthickness=0, command=get_quote)
kanye_button.grid(row=1, column=0)

window.mainloop()

Every time I click but I am being told that the photo is not in my directiory even though it is in the same folder. I don't believe it's to do with the code but I've moved them out and then back in but it still won't work.
Anyone else ever faced the issue and can help?
Files
It may be because the photos corrupted but I can open it on desktop.

Moved into different folders then back.
Re-named it then tried again.
I can't find the original photo online so I can't re download


问:
FastAPI avoid multiple connections to Database pymongo
I decided to give FastAPI go today. My understanding is that I should only have one connection to the database so I can easily close it on shutdown (maybe someone can shed light on this).

Originally I had a get_db() function and in my routes (multiple files) I was calling this function. My question is how correct is my implementation now (code shown below).

database.py

```<code># Make a database class the only connects once
class Database:
    def __init__(self):
        self.db = None

    def connect(self) -> Database:
        if self.db is None:
            uri = os.environ.get("TEST_MONGO_URI")
            client = MongoClient(uri, tls=True)
            self.db = client.get_database("development")
        return self.db

    def disconnect(self):
        if self.db is not None:
            self.db.client.close()
            self.db = None

# Import this instance into router files
database_instance = Database()
</code>```

user_router.py

```<code>@user_router.get("/api/users")
async def get_users(db: Database=Depends(database.connect)):
    """
    Returns all users found in users collection
    """
    collection = db.get_collection("users")
    users = [UserOut(**user) for user in collection.find({})]
    return {"data": users}
</code>```

Closing the connection in main.py

```<code>app.include_router(user_router)

@app.on_event("shutdown")
def shutdown_event():
    db.disconnect()
</code>```

Am I totally wrong, what's the best way to handle this? Should I avoid multiple connections or is it ok? Thanks in advance.

Body:
I decided to give FastAPI go today. My understanding is that I should only have one connection to the database so I can easily close it on shutdown (maybe someone can shed light on this).

Originally I had a get_db() function and in my routes (multiple files) I was calling this function. My question is how correct is my implementation now (code shown below).

database.py

# Make a database class the only connects once
class Database:
    def __init__(self):
        self.db = None

    def connect(self) -> Database:
        if self.db is None:
            uri = os.environ.get("TEST_MONGO_URI")
            client = MongoClient(uri, tls=True)
            self.db = client.get_database("development")
        return self.db

    def disconnect(self):
        if self.db is not None:
            self.db.client.close()
            self.db = None

# Import this instance into router files
database_instance = Database()

user_router.py

@user_router.get("/api/users")
async def get_users(db: Database=Depends(database.connect)):
    """
    Returns all users found in users collection
    """
    collection = db.get_collection("users")
    users = [UserOut(**user) for user in collection.find({})]
    return {"data": users}

Closing the connection in main.py

app.include_router(user_router)

@app.on_event("shutdown")
def shutdown_event():
    db.disconnect()

Am I totally wrong, what's the best way to handle this? Should I avoid multiple connections or is it ok? Thanks in advance.


问:
Not able to get a file directory path in Electron JS
I am making an Electron JS application, and trying to update some code to fall in line with current Electron standards, such as not using remote.

One of the things I am having trouble with is getting a file path to return after opening a dialog.

In the image below, I get the 'test' in my console, but I get neither of my other console logs. I tried both ' and ", but I can't get a reply for some reason. This ("dir") is used later and is read through by dir.length and a loop, but it gives me an undefined error, so I am assuming I am not returning any data regardless.

Main.JS select folder code

Return Call Function

One of the errors I am receiving

I can provide any additional information as necessary, I don't post on here often so not sure If I'm doing something wrong.

I am able to click the button, which opens a folder dialog. When I close it, nothing happens. I am getting the TypeError when the application loads, as my application also loads the last used directory path stored in a JSON, but it is empty.


问:
Protoc can not be built when CMAKE_BUILD_WITH_INSTALL_RPATH is TRUE
In my project the variable is set to True. This causes the problem that protoc can not be built as a shared library.

```<code>cmake_minimum_required(VERSION 3.20)
project(untitled4)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
option(BUILD_SHARED_LIBS "build shared libraries" ON)
option(BUILD_STATIC_LIBS "Build the static library" OFF)
include(FetchContent)
FetchContent_Declare(
        proto
        GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
        GIT_TAG        v21.6)
FetchContent_MakeAvailable(proto)

add_executable(untitled4 main.cpp)
</code>```

The error:

```<code>../../bin/protoc: error while loading shared libraries: libprotocd.so.32: cannot open shared object file: No such file or directory
</code>```

Body:
In my project the variable is set to True. This causes the problem that protoc can not be built as a shared library.

cmake_minimum_required(VERSION 3.20)
project(untitled4)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
option(BUILD_SHARED_LIBS "build shared libraries" ON)
option(BUILD_STATIC_LIBS "Build the static library" OFF)
include(FetchContent)
FetchContent_Declare(
        proto
        GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
        GIT_TAG        v21.6)
FetchContent_MakeAvailable(proto)

add_executable(untitled4 main.cpp)

The error:

../../bin/protoc: error while loading shared libraries: libprotocd.so.32: cannot open shared object file: No such file or directory


问:
How can I solve this NullReferenceException error?
I'm creating a 3D endless runner in unity, and I have created an UI that displays the number of coins collected, but if I try to run the script I get this error :
NullReferenceException: Object reference not set to an instance of an object
CollectableControl.Update () (at Assets/Scripts/Collectables/CollectableControl.cs:18)

This is the script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CollectableControl : MonoBehaviour
{
    public static int coinCount;
    public GameObject coinCountDisplay;

    /*void Start()
    {
        coinCountDisplay = GameObject.Find("CoinCount");
    }*/

    void Update()
    {
        coinCountDisplay.GetComponent<Text>().text = "" + coinCount;
    }
</code>```

I also placed the GameObject that needs to be accessed by the script where it should be

I tried to assign the coinCountDisplay field to the GameObject with the name "CoinCount" in void Start() but that didn't solve the issue, neither restarting the Unity Editor, deleting and recreating the script and adding the GameObject like in the attached picture.

Body:
I'm creating a 3D endless runner in unity, and I have created an UI that displays the number of coins collected, but if I try to run the script I get this error :
NullReferenceException: Object reference not set to an instance of an object
CollectableControl.Update () (at Assets/Scripts/Collectables/CollectableControl.cs:18)

This is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CollectableControl : MonoBehaviour
{
    public static int coinCount;
    public GameObject coinCountDisplay;

    /*void Start()
    {
        coinCountDisplay = GameObject.Find("CoinCount");
    }*/

    void Update()
    {
        coinCountDisplay.GetComponent<Text>().text = "" + coinCount;
    }

I also placed the GameObject that needs to be accessed by the script where it should be

I tried to assign the coinCountDisplay field to the GameObject with the name "CoinCount" in void Start() but that didn't solve the issue, neither restarting the Unity Editor, deleting and recreating the script and adding the GameObject like in the attached picture.


问:
Uninstall Package with PowerShell not working using Variable
I am trying to uninstall a software package, eset, in powershell by passing the product identifying number using a variable.  The script works when using the productID, but not when using a variable holding the product ID.

$product = Get-WmiObject -Class Win32_Product | Where-Object Name -EQ "ESET Endpoint Antivirus"
Write-Host "Product found:$product"

$productID = $product.IdentifyingNumber
Write-Host "Product Identifying Number:$productID"

The following code does not work:
Start-Process MSIEXEC '/qn /x "$productID" PASSWORD="password" REBOOT="ReallySuppress"'

The following code will work:
Start-Process MSIEXEC '/qn /x "{915B4D63-9489-4550-88E8-384CC134A747}" PASSWORD="password" REBOOT="ReallySuppress"'

Error: This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.

Any help appreciated.

Thanks!

Tried using a variable and tried using the real value.  Expected both ways to work, only using the real value without a variable in place worked.


问:
Python Selenium - no select item for dropdown - something "MuiInputBase-input"
I am stuck at one point, I am trying to select a item in a dropdown. looks like this dropdown is somewhat made in "MuiInputBase-input"[ could be react JS- not sure]...see screenshot1
screenshot 1

I know selenium works with 'Select', where by value we could choose the dropdown item. This one seems bit challenging. Could someone please assist. i want to select let's say '25 Years' in the dropdown.

a very similar issue is here for someone else:
Select DropDown value using Python Selenium

I've already used selenium 'Select' but there doesn't seem to be any Options listed in HTML (searched the whole document)

Also, there is no iframe [searched and 0 iframe are involved]

I am expecting to select a choices in the drop down like in screenshot 2
screenshot 2