问:
NullException with INotifyPropertyChanged?
I am trying to make a battleship game in WPF C# and whenever I click on a cell within the Border to fire at the enemy ship I get a nullreferenceexception within my INotifyPropertyChanged.

```<code>    class BattleshipVM : ViewModelBase
    {
        string time = "";
        public CellModel[][] OurMap {get; private set;}
        public CellModel[][] EnemyMap { get; private set; }

        public string Time
        {
            get => time;
private set => Set(ref time, value);
        }
        DispatcherTimer timer;
        DateTime startTime;
        string ourMap =
            @"**********
              XXXX**X**X
              ******X***
              X*******X*
              X*********
              X****XX***
              ***X******
              ******X***
              *******X**
              ***X****X*
              **********

";

        string enemyMap =
            @"*X******X*
              *******X**
              **XX******
              X*****X***
              **********
              *XXX***X**
              **********
              *X***XXX**
              **X*******
              ***X***XX*
              ****X*****

";
        public BattleshipVM()
        {

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(10);
            timer.Tick += Timer_Tick;
            OurMap = MapFabric(ourMap);
            EnemyMap = MapFabric(enemyMap);

        }
        CellModel[][] MapFabric(string str)
        {
            var mp = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var map = new CellModel[10][];
            for (int i = 0; i < 10; i++)
            {
                map[i] = new CellModel[10];
                for (int j = 0; j < 10; j++)
                {
                    map[i][j] = new CellModel(mp[i][j]);
                }
            }
            return map;
        }

        internal void ShotToOurMap(int X, int Y)
        {
            OurMap[X][Y].SetState();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            var now = DateTime.Now;
            var dt = now - startTime;
            Time = dt.ToString(@"mm\:ss");
        }
        public void Start()
        {
            startTime = DateTime.Now;
            timer.Start();
        }
        public void Stop()
        {
            timer.Stop();
        }
    }

    public class CellModel : ViewModelBase
    {
        Visibility visibility = Visibility.Collapsed;
        bool ship;

        public CellModel(char state)
        {
            ship = state == 'X';
        }

        public Visibility Miss { get => visibility; private set => Set(ref visibility, value); }
        public void SetMiss()
        {
            Miss = Visibility.Visible;
        }

        public Visibility Shot { get => visibility; private set => Set(ref visibility, value); }
        public void SetState()
        {
            if (ship)

                Shot = Visibility.Visible;
            else
                Miss = Visibility.Visible;

        }
    }
}

</code>```

and this is the mainwindow xaml

```<code><Window.Resources>

        <DataTemplate DataType="{x:Type local:CellModel}">
        <Border BorderBrush="DarkSalmon"
                                        Width="30" Height="30"
                                        BorderThickness="1"
                                        Margin="0,0,-1,-1"
                                        MouseDown="Border_MouseDown"
                                        Background="NavajoWhite">
            <Grid>
                <Ellipse Width="7" Height="7"
                                                 Fill="Tomato"
                                                 HorizontalAlignment="Center"
                                                 VerticalAlignment="Center"
                                                 Visibility="{Binding Miss}">
                </Ellipse>
                <Path
                                              Stroke="#8F00" Data="M4,4L25,25M25,4L4, 25" StrokeThickness="3"
                                              Visibility="{Binding Shot}"></Path>
            </Grid>
        </Border>
    </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="3*"></ColumnDefinition>
            <ColumnDefinition Width="3*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <StackPanel Margin="20">
            <TextBlock  Text="{Binding Time}" FontSize="36"
                       HorizontalAlignment="Center" Margin="0,0,0,10"
                      x:Name="TimeShow">
            0:00 </TextBlock>
            <TextBlock Text="{Binding Steps}"  HorizontalAlignment="Center" > Step: 5:
            </TextBlock>
            <TextBlock Text="{Binding Goal}"  HorizontalAlignment="Center" > Goal 3:
            </TextBlock>
        </StackPanel>
        <Button Content=" Start " Grid.Column="1" Click="btnStart"/>
        <Button Content=" Stop " Grid.Column="2" Click="btnStop"/>
        <ItemsControl
          Grid.Column="1"  ItemsSource="{Binding OurMap}" HorizontalAlignment="Center"
                      VerticalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal">

                                </StackPanel>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>

                    </ItemsControl>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <ItemsControl
          Grid.Column="2"  ItemsSource="{Binding EnemyMap}" HorizontalAlignment="Center"
                      VerticalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal">

                                </StackPanel>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>

                    </ItemsControl>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</code>```

This is the INotifyPropertyChanged interface

```<code>using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Battleship
{
    internal class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void Set<T>(ref T field, T value, [CallerMemberName] string propName = "")
        {
            if (!field.Equals(value))
            {
                field = value;
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }

        }
        protected void Fire(params string[] names)
        {
            foreach (var name in names)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}
</code>```

and the main window cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Battleship
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BattleshipVM bs = new BattleshipVM();
        Random rnd = new Random();
        public MainWindow()
        {
            DataContext = bs;
            bs = new BattleshipVM();
            InitializeComponent();
        }

        private void btnStart(object sender, RoutedEventArgs e)
        {

            bs.Start();
        }

        private void btnStop(object sender, RoutedEventArgs e)
        {
            bs.Stop();
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {

            var bor = sender as Border;
            var cellModel = bor.DataContext as CellModel;

            cellModel.SetState();
            var X = rnd.Next(10);
            var Y = rnd.Next(10);

            bs.ShotToOurMap(X, Y);

        }
    }
}
</code>```

I've tried putting the Data Template into Windows.Resources so it would be available to the entire program and made the DataTemplates DataType as the local class CellModel that is the one that makes the hits and misses visible when the player hit but this is all to not avail. Been at it for three days with this error and still cannot figure it out.

Body:
I am trying to make a battleship game in WPF C# and whenever I click on a cell within the Border to fire at the enemy ship I get a nullreferenceexception within my INotifyPropertyChanged.

    class BattleshipVM : ViewModelBase
    {
        string time = "";
        public CellModel[][] OurMap {get; private set;}
        public CellModel[][] EnemyMap { get; private set; }

        public string Time
        {
            get => time;
private set => Set(ref time, value);
        }
        DispatcherTimer timer;
        DateTime startTime;
        string ourMap =
            @"**********
              XXXX**X**X
              ******X***
              X*******X*
              X*********
              X****XX***
              ***X******
              ******X***
              *******X**
              ***X****X*
              **********

";

        string enemyMap =
            @"*X******X*
              *******X**
              **XX******
              X*****X***
              **********
              *XXX***X**
              **********
              *X***XXX**
              **X*******
              ***X***XX*
              ****X*****

";
        public BattleshipVM()
        {

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(10);
            timer.Tick += Timer_Tick;
            OurMap = MapFabric(ourMap);
            EnemyMap = MapFabric(enemyMap);

        }
        CellModel[][] MapFabric(string str)
        {
            var mp = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var map = new CellModel[10][];
            for (int i = 0; i < 10; i++)
            {
                map[i] = new CellModel[10];
                for (int j = 0; j < 10; j++)
                {
                    map[i][j] = new CellModel(mp[i][j]);
                }
            }
            return map;
        }

        internal void ShotToOurMap(int X, int Y)
        {
            OurMap[X][Y].SetState();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            var now = DateTime.Now;
            var dt = now - startTime;
            Time = dt.ToString(@"mm\:ss");
        }
        public void Start()
        {
            startTime = DateTime.Now;
            timer.Start();
        }
        public void Stop()
        {
            timer.Stop();
        }
    }

    public class CellModel : ViewModelBase
    {
        Visibility visibility = Visibility.Collapsed;
        bool ship;

        public CellModel(char state)
        {
            ship = state == 'X';
        }

        public Visibility Miss { get => visibility; private set => Set(ref visibility, value); }
        public void SetMiss()
        {
            Miss = Visibility.Visible;
        }

        public Visibility Shot { get => visibility; private set => Set(ref visibility, value); }
        public void SetState()
        {
            if (ship)

                Shot = Visibility.Visible;
            else
                Miss = Visibility.Visible;

        }
    }
}

and this is the mainwindow xaml

<Window.Resources>

        <DataTemplate DataType="{x:Type local:CellModel}">
        <Border BorderBrush="DarkSalmon"
                                        Width="30" Height="30"
                                        BorderThickness="1"
                                        Margin="0,0,-1,-1"
                                        MouseDown="Border_MouseDown"
                                        Background="NavajoWhite">
            <Grid>
                <Ellipse Width="7" Height="7"
                                                 Fill="Tomato"
                                                 HorizontalAlignment="Center"
                                                 VerticalAlignment="Center"
                                                 Visibility="{Binding Miss}">
                </Ellipse>
                <Path
                                              Stroke="#8F00" Data="M4,4L25,25M25,4L4, 25" StrokeThickness="3"
                                              Visibility="{Binding Shot}"></Path>
            </Grid>
        </Border>
    </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="3*"></ColumnDefinition>
            <ColumnDefinition Width="3*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <StackPanel Margin="20">
            <TextBlock  Text="{Binding Time}" FontSize="36"
                       HorizontalAlignment="Center" Margin="0,0,0,10"
                      x:Name="TimeShow">
            0:00 </TextBlock>
            <TextBlock Text="{Binding Steps}"  HorizontalAlignment="Center" > Step: 5:
            </TextBlock>
            <TextBlock Text="{Binding Goal}"  HorizontalAlignment="Center" > Goal 3:
            </TextBlock>
        </StackPanel>
        <Button Content=" Start " Grid.Column="1" Click="btnStart"/>
        <Button Content=" Stop " Grid.Column="2" Click="btnStop"/>
        <ItemsControl
          Grid.Column="1"  ItemsSource="{Binding OurMap}" HorizontalAlignment="Center"
                      VerticalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal">

                                </StackPanel>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>

                    </ItemsControl>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <ItemsControl
          Grid.Column="2"  ItemsSource="{Binding EnemyMap}" HorizontalAlignment="Center"
                      VerticalAlignment="Center">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal">

                                </StackPanel>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>

                    </ItemsControl>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>

This is the INotifyPropertyChanged interface

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Battleship
{
    internal class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void Set<T>(ref T field, T value, [CallerMemberName] string propName = "")
        {
            if (!field.Equals(value))
            {
                field = value;
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }

        }
        protected void Fire(params string[] names)
        {
            foreach (var name in names)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}

and the main window cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Battleship
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        BattleshipVM bs = new BattleshipVM();
        Random rnd = new Random();
        public MainWindow()
        {
            DataContext = bs;
            bs = new BattleshipVM();
            InitializeComponent();
        }

        private void btnStart(object sender, RoutedEventArgs e)
        {

            bs.Start();
        }

        private void btnStop(object sender, RoutedEventArgs e)
        {
            bs.Stop();
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {

            var bor = sender as Border;
            var cellModel = bor.DataContext as CellModel;

            cellModel.SetState();
            var X = rnd.Next(10);
            var Y = rnd.Next(10);

            bs.ShotToOurMap(X, Y);

        }
    }
}

I've tried putting the Data Template into Windows.Resources so it would be available to the entire program and made the DataTemplates DataType as the local class CellModel that is the one that makes the hits and misses visible when the player hit but this is all to not avail. Been at it for three days with this error and still cannot figure it out.


来源: stackexchange

问:
Reuse build phase from Github action in order to run tests in parallel actions
I have a github action that has a build phase that installs some libraries, then builds the project, then runs some tests. Concretely it looks like:

```<code>jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # install deps.
      - name: install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libsystemd-dev

      # cache libsodium
      - name: cache libsodium-1.0.18
        id: libsodium
        uses: actions/cache@v2
        with:
          path: ~/libsodium-stable
          key: ${{ runner.os }}-libsodium-1.0.18

      # install libsodium with cache
      - name: Install cache libsodium-1.0.18
        if: steps.libsodium.outputs.cache-hit == 'true'
        run: cd ~/libsodium-stable && ./configure && make -j2 && sudo make install

... etc
      - name: build project
        run: <build the project>
      - name: test1
        run: <run test1>
      - name: test2
        run: <run test2>
</code>```

I would like to know the simplest way to run test1 and test2 as parallel actions given that they need to make use of the build environment created from all of the previous steps. I have seen some mention or reusable/composable actions but I didn't see anything that fit my situation exactly.

I tried the dumbest thing possible

```<code>
  test1:
    needs: [build]
    steps:
      - name: test1
        run: <run test1>

  test2:
    needs: [build]
    steps:
      - name: test2
        run: <run test2>
</code>```

but this didn't work, probably because it's missing a runs-on statement

ContentLicense: CC BY-SA 4.0

Body:
I have a github action that has a build phase that installs some libraries, then builds the project, then runs some tests. Concretely it looks like:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # install deps.
      - name: install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libsystemd-dev

      # cache libsodium
      - name: cache libsodium-1.0.18
        id: libsodium
        uses: actions/cache@v2
        with:
          path: ~/libsodium-stable
          key: ${{ runner.os }}-libsodium-1.0.18

      # install libsodium with cache
      - name: Install cache libsodium-1.0.18
        if: steps.libsodium.outputs.cache-hit == 'true'
        run: cd ~/libsodium-stable && ./configure && make -j2 && sudo make install

... etc
      - name: build project
        run: <build the project>
      - name: test1
        run: <run test1>
      - name: test2
        run: <run test2>

I would like to know the simplest way to run test1 and test2 as parallel actions given that they need to make use of the build environment created from all of the previous steps. I have seen some mention or reusable/composable actions but I didn't see anything that fit my situation exactly.

I tried the dumbest thing possible

  test1:
    needs: [build]
    steps:
      - name: test1
        run: <run test1>

  test2:
    needs: [build]
    steps:
      - name: test2
        run: <run test2>

but this didn't work, probably because it's missing a runs-on statement


问:
Why JSON lists are not showing up on front end after API .net upgrade
So I have a api that I have upgraded from .net2.1 to .net6, and changed a few things in the startup.cs so it was compatible with .net6 (images show changes). The front end makes a call to the api for some information, but for some reason now, the front end doesn't receive all the information in the object. It seems the list part is no longer included? I checked what the api is returning and its the same as before so im assuming its something not quite right with the json options.

Differences in startup.cs (right is the old version)
Also has "

```<code>options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
</code>```

"
in the .AddJsonOptions as was having issue where the enums were returning the int index not value.

enter image description here

Differences in front end json

enter image description here

What the API is returning when called
enter image description here

Iv tried messing around with the JsonOptions but haven't gotten anything to work

Body:
So I have a api that I have upgraded from .net2.1 to .net6, and changed a few things in the startup.cs so it was compatible with .net6 (images show changes). The front end makes a call to the api for some information, but for some reason now, the front end doesn't receive all the information in the object. It seems the list part is no longer included? I checked what the api is returning and its the same as before so im assuming its something not quite right with the json options.

Differences in startup.cs (right is the old version)
Also has "

options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

"
in the .AddJsonOptions as was having issue where the enums were returning the int index not value.

enter image description here

Differences in front end json

enter image description here

What the API is returning when called
enter image description here

Iv tried messing around with the JsonOptions but haven't gotten anything to work


问:
How can I iterate through substrings to find if it matches any entries in my Dataframes without ignoring spaces?
I have two Dataframes. The first Dataframe,df_globe, looks like this:

```<code>                  Country                Region
0                 Andorra                Europe
1                Andorran                Europe
2               Andorrano                Europe
3    United Arab Emirates                 MENA
4            Saudi Arabia                 MENA
5                    u.a.e                MENA
6 Democratic People's Republic of Korea,  East Asia
6               Puerto Rico,              Americas
..                    ...                 ...
539              Americas            Americas
540                  MENA               MENA
541            South Asia          South Asia
542    Sub-Saharan Africa  Sub-Saharan Africa
543               Pacific             Pacific

</code>```

The second Dataframe df_tweets looks like this:

```<code>   sentiment                   id                       date                                               text
0          0  1598814115664994307  2022-12-02 22:59:24+00:00  I think it is in South Asia
1          0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico
</code>```
```<code>df_globe = pd.read_csv('fuzzyCountriesAndRegions.csv')
df_tweets = pd.read_csv('tweets.csv')
df_result= pd.DataFrame(columns=['sentiment', 'id', 'date', 'text'])

print(df_globe)
print(df_tweets)

word_list = []
for tweetIndex in range(len(df_tweets['text'])):
    word_tokens = word_tokenize(df_tweets['text'][tweetIndex])
    for token in word_tokens:
        for name in df_globe['Country']:
            ratio = fuzz.token_set_ratio(token, name)
            if ratio >= 90:
                df_result = df_result.append(df_tweets.iloc[[tweetIndex]])
                word_list.append(token)

df_result['word'] = word_list

print(df_result)
</code>```

df_result looks like this when I run my code:

```<code>  sentiment                   id                       date                                   text    word
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia    Asia
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia    Asia
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia    Asia
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico    Rico
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico    Rico
</code>```

But it df_result should look like (example of desired output):

```<code>   sentiment                   id                       date           text                              word
0          0  1598814115664994307  2022-12-02 22:59:24+00:00  I think it is in South Asia             South Asia
1          0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto Rico

</code>```

I've thought of possibly trying to take out all spaces, perform the matching, and then retokenizing the tweets, but I haven't been able to find a way to retokenize them if they don't have spaces anymore. I don't think doing that would be possible.

Another thought would be to make a copy of the tweet called tweet_copy, take the spaces and punctuation out of that, search all of its substrings for matches with df_globe[Country], then if it matched, put the original tweet in df_result along with the matched word.

These are some links I have looked at, but none have been helpful:
ignore spaces in a substring
,
tokenize without whitespace
,
tokenize continuous words with no whitespace

Body:
I have two Dataframes. The first Dataframe,df_globe, looks like this:

                  Country                Region
0                 Andorra                Europe
1                Andorran                Europe
2               Andorrano                Europe
3    United Arab Emirates                 MENA
4            Saudi Arabia                 MENA
5                    u.a.e                MENA
6 Democratic People's Republic of Korea,  East Asia
6               Puerto Rico,              Americas
..                    ...                 ...
539              Americas            Americas
540                  MENA               MENA
541            South Asia          South Asia
542    Sub-Saharan Africa  Sub-Saharan Africa
543               Pacific             Pacific

The second Dataframe df_tweets looks like this:

   sentiment                   id                       date                                               text
0          0  1598814115664994307  2022-12-02 22:59:24+00:00  I think it is in South Asia
1          0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico

df_globe = pd.read_csv('fuzzyCountriesAndRegions.csv')
df_tweets = pd.read_csv('tweets.csv')
df_result= pd.DataFrame(columns=['sentiment', 'id', 'date', 'text'])

print(df_globe)
print(df_tweets)

word_list = []
for tweetIndex in range(len(df_tweets['text'])):
    word_tokens = word_tokenize(df_tweets['text'][tweetIndex])
    for token in word_tokens:
        for name in df_globe['Country']:
            ratio = fuzz.token_set_ratio(token, name)
            if ratio >= 90:
                df_result = df_result.append(df_tweets.iloc[[tweetIndex]])
                word_list.append(token)

df_result['word'] = word_list

print(df_result)

df_result looks like this when I run my code:

  sentiment                   id                       date                                   text    word
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia   South
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia    Asia
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia    Asia
0         0  1598814115664994307  2022-12-02 22:59:24+00:00            I think it is in South Asia    Asia
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico    Rico
1         0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico    Rico

But it df_result should look like (example of desired output):

   sentiment                   id                       date           text                              word
0          0  1598814115664994307  2022-12-02 22:59:24+00:00  I think it is in South Asia             South Asia
1          0  1598814115664994307  2022-12-02 22:59:24+00:00  Say hello to my friend in Puerto Rico  Puerto Rico

I've thought of possibly trying to take out all spaces, perform the matching, and then retokenizing the tweets, but I haven't been able to find a way to retokenize them if they don't have spaces anymore. I don't think doing that would be possible.

Another thought would be to make a copy of the tweet called tweet_copy, take the spaces and punctuation out of that, search all of its substrings for matches with df_globe[Country], then if it matched, put the original tweet in df_result along with the matched word.

These are some links I have looked at, but none have been helpful:
ignore spaces in a substring
,
tokenize without whitespace
,
tokenize continuous words with no whitespace


问:
How can I do plt.show(fig1,fig2)?
I defined two figures (each with plots inside) such as:

```<code>    fig1 = plt.figure()
    fig2 = plt.figure()
</code>```

and later on I want to combine them on one figure (same axis) the same way Mathemtica can do it. However, (show) does nothing. How can I do this?

```<code>    fig1 = plt.figure()
    plt.plot(np.sin(10*np.linspace(0,1,100)))
    fig2 = plt.figure()
    plt.plot(np.sin(20*np.linspace(0,1,100)))
    plt.show(fig1,fig2)
</code>```

I am expecting the same output as I would `

```<code>figcombined = plt.figure()
    plt.plot(np.sin(10*np.linspace(0,1,100)))
    plt.plot(np.sin(20*np.linspace(0,1,100)))
    plt.show()
</code>```

`

Title: How can I do plt.show(fig1,fig2)?

Body:
I defined two figures (each with plots inside) such as:

    fig1 = plt.figure()
    fig2 = plt.figure()

and later on I want to combine them on one figure (same axis) the same way Mathemtica can do it. However, (show) does nothing. How can I do this?

    fig1 = plt.figure()
    plt.plot(np.sin(10*np.linspace(0,1,100)))
    fig2 = plt.figure()
    plt.plot(np.sin(20*np.linspace(0,1,100)))
    plt.show(fig1,fig2)

I am expecting the same output as I would `

figcombined = plt.figure()
    plt.plot(np.sin(10*np.linspace(0,1,100)))
    plt.plot(np.sin(20*np.linspace(0,1,100)))
    plt.show()

`


问:
iCloud Drive never syncs with Xcode 14.1/14.2 simulator on M1 Mac (OK on Intel)
Testing an iOS app using iCloud Drive on iOS16.1, iOS15.5 and iOS14.5 - these all work fine on Intel (Monterey or Ventura) but not on an M1 Mac running Monterey or Ventura.

The iOS16.1 simulator throws an exception with bird, which could have some bearing on it - but this isn't seen with the other simulators, and none of them sync iCloud Drive after leaving it running for over an hour (and manually triggering iCloud Sync).

Has anyone else this problem? How about on Ventura on an M1?


问:
Laravel Sanctum 401 error after on reloading
I am using Laravel Sanctum's API Tokens to authenticate requests from a React application. I don't use SPA Authentication and cookies.

For now, the Laravel sessions are managed with files.

After you login, you get a token, and with the given token, you can call APIs successfully. But if you refresh a page, even with the same token, API calls fail with 401 status code and the following message:

```<code>{
  "message": "Given authorization token is not valid. Please try to login again."
}
</code>```

It works fine on my localhost. It only happens on a live site, and after you refresh a page.

The Laravel backend serves only APIs, so it defines routes in api.php only. All these routes are using auth:sanctum middleware (of course, with an exception of /login route).

The following line is disabled in Kernel.php for the api middleware group:

```<code>\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class
</code>```

Any thoughts on how to fix this?

Body:
I am using Laravel Sanctum's API Tokens to authenticate requests from a React application. I don't use SPA Authentication and cookies.

For now, the Laravel sessions are managed with files.

After you login, you get a token, and with the given token, you can call APIs successfully. But if you refresh a page, even with the same token, API calls fail with 401 status code and the following message:

{
  "message": "Given authorization token is not valid. Please try to login again."
}

It works fine on my localhost. It only happens on a live site, and after you refresh a page.

The Laravel backend serves only APIs, so it defines routes in api.php only. All these routes are using auth:sanctum middleware (of course, with an exception of /login route).

The following line is disabled in Kernel.php for the api middleware group:

\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class

Any thoughts on how to fix this?


问:
Onblur event fires when clicking on the scrollbar
I have a onblur event on included in the HTML of LWC:

```<code>onblur={closeDropdown}
</code>```

and here is the closeDropdown in the js file:

```<code>closeDropdown(event) {
setTimeout( handler: () => {
this.validate()
this.toggleOpenDropDown( toggleState: false)
}, timeout: 200)
}
</code>```

It is supposed to close the dropdown when a user clicks outside the field. The problem is that it also closes the dropdown when you click on the scrollbar to scroll down the list. The onblur event somehow treats the scrollbar as not being part of the field. Is there a way to prevent this from happening?

Body:
I have a onblur event on included in the HTML of LWC:

onblur={closeDropdown}

and here is the closeDropdown in the js file:

closeDropdown(event) {
setTimeout( handler: () => {
this.validate()
this.toggleOpenDropDown( toggleState: false)
}, timeout: 200)
}

It is supposed to close the dropdown when a user clicks outside the field. The problem is that it also closes the dropdown when you click on the scrollbar to scroll down the list. The onblur event somehow treats the scrollbar as not being part of the field. Is there a way to prevent this from happening?


问:
How to src image from a list in React
I am trying to use images from a list as a source from a react component

```<code>import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';

const ProductComponent = ({ category, idx }) =>{
  const images = [
    './unisex-heavy-blend-hoodie-black-zoomed-in-2-638cce72d61d2.png',
    './unisex-staple-t-shirt-silver-front-638ca71569cc4.png',
    './unisex-staple-t-shirt-black-heather-zoomed-in-638ca1af35d94.png'
  ]
  return (
    <Card style={{ width: '25rem' }}>
      <Card.Img variant="top"  src={require(images[idx])} />
      <Card.Body>
        <Card.Title>{category}</Card.Title>
        <Button variant="primary">{images[idx]}</Button>
      </Card.Body>
    </Card>
  );
}

export default ProductComponent;
</code>```

The src in  doesn't work.  The {images[idx]}  in  is for testing purposes, and it shows the link as it should. If i replace {images[idx]}   in src with one of the link in the images list it works. I don't understand why. Could someone explain it? Thanks

I tried to put the link directly in src, and i printed out the {images[idx]} as a button to see its the right one

Title: How to src image from a list in React

Body:
I am trying to use images from a list as a source from a react component

import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';

const ProductComponent = ({ category, idx }) =>{
  const images = [
    './unisex-heavy-blend-hoodie-black-zoomed-in-2-638cce72d61d2.png',
    './unisex-staple-t-shirt-silver-front-638ca71569cc4.png',
    './unisex-staple-t-shirt-black-heather-zoomed-in-638ca1af35d94.png'
  ]
  return (
    <Card style={{ width: '25rem' }}>
      <Card.Img variant="top"  src={require(images[idx])} />
      <Card.Body>
        <Card.Title>{category}</Card.Title>
        <Button variant="primary">{images[idx]}</Button>
      </Card.Body>
    </Card>
  );
}

export default ProductComponent;

The src in  doesn't work.  The {images[idx]}  in  is for testing purposes, and it shows the link as it should. If i replace {images[idx]}   in src with one of the link in the images list it works. I don't understand why. Could someone explain it? Thanks

I tried to put the link directly in src, and i printed out the {images[idx]} as a button to see its the right one


问:
How Implement EmguCV (or any other framework) in CleanArchitecture Solution
I need to use EmguCV NuGet package in my solution.

As i read in the Uncle Bob's books, to pursue the goal of leaving in the external part of the solution any dependency related to the library, I created a new Interface named IImageProcessor in the core project, then I created a new project as a place where to install the NuGet Package and I implemented there a new concrete class called EmguImageProcessor extending the IImageProcessor Interface. In this class I wrote functions to wrap some emgu library functions.

I registered by dependency injection the IImageProcessor with EmguImageProcessor and it has been very cool..But now.. if i wish to use any Emgu Library method I have to wrap them in the interface and implement them in the class..that is a lot of work.. maybe am I missing something?

I need to know what is the best method to use Third-party libraries in my solution.


问:
Decrypt a 8 byte byte array in c#
I'm using the below code to try to decrypt a 8 byte byte array..

```<code>public class AesGenericEncryptionService
{
    private readonly byte[] m_Key;
    private readonly byte[] m_IV;

    public AesGenericEncryptionService(byte[] key, byte[] iv)
    {
        if (key == null)
        {
            throw new ArgumentNullException(nameof(key));
        }
        else if (key.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(key));
        }

        if (iv == null || iv.Length <= 0)
        {
            throw new ArgumentNullException(nameof(iv));
        }
        else if (iv.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(iv));
        }

        m_Key = key;
        m_IV = iv;
    }

    public byte[] Encrypt(byte[] data)
    {
        if (data == null)
        {
            throw new ArgumentNullException(nameof(data));
        }

        using (var rijndaelManaged = new RijndaelManaged())
        {
            rijndaelManaged.KeySize = m_Key.Length * 8;
            rijndaelManaged.Key = m_Key;
            rijndaelManaged.BlockSize = m_IV.Length * 8;
            rijndaelManaged.IV = m_IV;

            using (var encryptor = rijndaelManaged.CreateEncryptor())
            using (var ms = new MemoryStream())
            using (var cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(data, 0, data.Length);
                cryptoStream.FlushFinalBlock();

                return ms.ToArray();
            }
        }
    }
    public byte[] Decrypt(byte[] cipher)
    {
        // Check arguments.
        if (cipher == null)
        {
            throw new ArgumentNullException(nameof(cipher));
        }
        else if (cipher.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(cipher));
        }

        using (var rijndaelManaged = new RijndaelManaged())
        {
            rijndaelManaged.KeySize = m_Key.Length * 8;
            rijndaelManaged.Key = m_Key;
            rijndaelManaged.BlockSize = m_IV.Length * 8;
            rijndaelManaged.IV = m_IV;

            using (var decryptor = rijndaelManaged.CreateDecryptor())
            using (var ms = new MemoryStream(cipher))
            using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            {

                var dycrypted = new byte[cipher.Length];
                var bytesRead = cryptoStream.Read(dycrypted, 0, cipher.Length);

                return dycrypted.Take(bytesRead).ToArray();
            }
        }
    }
}
</code>```

I then try to run the code like so..

```<code>byte[] challenge = new byte[] { 0x93, 0x9d, 0x2c, 0x2e, 0xa1, 0x65, 0x75, 0xd5 };

byte[] rndA = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

byte[] defaultKey = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var crypto = new AesGenericEncryptionService(defaultKey,iv);

var decrypted= crypto.Decrypt(challenge);
Console.WriteLine(BitConverter.ToString(decrypted));
var str = BitConverter.ToString(decrypted).Replace("-", "");
Console.WriteLine(str);
Console.ReadLine();
</code>```

which then fails on this line:

```<code> rijndaelManaged.KeySize = m_Key.Length * 8;
</code>```

with the error being:

```<code>Specified key is not a valid size for this algorithm.
</code>```

I'm trying to convert this code from this article into c#:
https://www.linkedin.com/pulse/mifare-desfire-introduction-david-coelho

Particularly this psudo code:

What am I doing wrong as I don't think I can change the size to a 16 byte array.. as what gets returned to me is a 8 byte array..

Title: Decrypt a 8 byte byte array in c#

Body:
I'm using the below code to try to decrypt a 8 byte byte array..

public class AesGenericEncryptionService
{
    private readonly byte[] m_Key;
    private readonly byte[] m_IV;

    public AesGenericEncryptionService(byte[] key, byte[] iv)
    {
        if (key == null)
        {
            throw new ArgumentNullException(nameof(key));
        }
        else if (key.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(key));
        }

        if (iv == null || iv.Length <= 0)
        {
            throw new ArgumentNullException(nameof(iv));
        }
        else if (iv.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(iv));
        }

        m_Key = key;
        m_IV = iv;
    }

    public byte[] Encrypt(byte[] data)
    {
        if (data == null)
        {
            throw new ArgumentNullException(nameof(data));
        }

        using (var rijndaelManaged = new RijndaelManaged())
        {
            rijndaelManaged.KeySize = m_Key.Length * 8;
            rijndaelManaged.Key = m_Key;
            rijndaelManaged.BlockSize = m_IV.Length * 8;
            rijndaelManaged.IV = m_IV;

            using (var encryptor = rijndaelManaged.CreateEncryptor())
            using (var ms = new MemoryStream())
            using (var cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(data, 0, data.Length);
                cryptoStream.FlushFinalBlock();

                return ms.ToArray();
            }
        }
    }
    public byte[] Decrypt(byte[] cipher)
    {
        // Check arguments.
        if (cipher == null)
        {
            throw new ArgumentNullException(nameof(cipher));
        }
        else if (cipher.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(cipher));
        }

        using (var rijndaelManaged = new RijndaelManaged())
        {
            rijndaelManaged.KeySize = m_Key.Length * 8;
            rijndaelManaged.Key = m_Key;
            rijndaelManaged.BlockSize = m_IV.Length * 8;
            rijndaelManaged.IV = m_IV;

            using (var decryptor = rijndaelManaged.CreateDecryptor())
            using (var ms = new MemoryStream(cipher))
            using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            {

                var dycrypted = new byte[cipher.Length];
                var bytesRead = cryptoStream.Read(dycrypted, 0, cipher.Length);

                return dycrypted.Take(bytesRead).ToArray();
            }
        }
    }
}

I then try to run the code like so..

byte[] challenge = new byte[] { 0x93, 0x9d, 0x2c, 0x2e, 0xa1, 0x65, 0x75, 0xd5 };

byte[] rndA = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

byte[] defaultKey = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

var crypto = new AesGenericEncryptionService(defaultKey,iv);

var decrypted= crypto.Decrypt(challenge);
Console.WriteLine(BitConverter.ToString(decrypted));
var str = BitConverter.ToString(decrypted).Replace("-", "");
Console.WriteLine(str);
Console.ReadLine();

which then fails on this line:

 rijndaelManaged.KeySize = m_Key.Length * 8;

with the error being:

Specified key is not a valid size for this algorithm.

I'm trying to convert this code from this article into c#:
https://www.linkedin.com/pulse/mifare-desfire-introduction-david-coelho

Particularly this psudo code:

What am I doing wrong as I don't think I can change the size to a 16 byte array.. as what gets returned to me is a 8 byte array..


问:
Deno Deploy --cert flag
How can I add --cert flag when my project run on deno deploy?

I am using deno fresh and supabase postgres. When in local environment I use --cert flag to set certificate, but in deno deploy I didn't know how to set --cert flag

Title: Deno Deploy --cert flag


问:
Streaming not working in Delta Live table pipeline (Databricks)?
I am working on a pipeline in Databricks > Workflows > Delta Live Tables and having an issue with the streaming part.

Expectations:

One bronze table reads the json files with AutoLoader (cloudFiles), in a streaming mode (spark.readStream)

One silver table reads and flattens the bronze table in streaming (dlt.read_stream)

Result:

When taking the root location as the source (load /*, several hundreds of files): the pipelines starts, but the number of rows/files appended is not updated in the graph until the bronze part be completed. Then, the silver part starts, the number of files/rows never updates either and the pipeline terminates with a memory error.

When taking a very small number of files (/specific_folder among hundreds) : the pipeline runs well and terminates with no error, but again, the number of rows/files appended is not updated in the graph until each part is completed.

This led me to the conclusion that the pipeline seems not to run in a streaming mode.
Maybe I am missing something about the config or how to run properly a DLT pipeline, and would need your help on this please.

Here is the configuration of the pipeline:

```<code>{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"clusters": [
    {
        "label": "default",
        "aws_attributes": {
            "instance_profile_arn": "arn:aws:iam::xxxxxxxxxxxx:instance-profile/iam_role_example"
        },
        "autoscale": {
            "min_workers": 1,
            "max_workers": 10,
            "mode": "LEGACY"
        }
    }
],
"development": true,
"continuous": false,
"channel": "CURRENT",
"edition": "PRO",
"photon": false,
"libraries": [
    {
        "notebook": {
            "path": "/Repos/user_example@xxxxxx.xx/dms/bronze_job"
        }
    }
],
"name": "01-landing-task-1",
"storage": "dbfs:/pipelines/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"configuration": {
    "SCHEMA": "example_schema",
    "RAW_MOUNT_NAME": "xxxx",
    "DELTA_MOUNT_NAME": "xxxx",
    "spark.sql.parquet.enableVectorizedReader": "false"
},
"target": "landing"}
</code>```

Here is the code of the pipeline (the query in the silver table contains many more columns with a get_json_object, ~30 actually):

```<code>import dlt
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.sql.window import Window

RAW_MOUNT_NAME = spark.conf.get("RAW_MOUNT_NAME")
SCHEMA = spark.conf.get("SCHEMA")
SOURCE = spark.conf.get("SOURCE")
TABLE_NAME = spark.conf.get("TABLE_NAME")
PRIMARY_KEY_PATH = spark.conf.get("PRIMARY_KEY_PATH")

@dlt.table(
    name=f"{SCHEMA}_{TABLE_NAME}_bronze",
    table_properties={
        "quality": "bronze"
    }
)
def bronze_job():
    load_path = f"/mnt/{RAW_MOUNT_NAME}/{SOURCE}/5e*"

    return spark \
            .readStream \
            .format("text") \
            .option("encoding", "UTF-8") \
            .load(load_path) \
            .select("value", "_metadata") \
            .withColumnRenamed("value", "json") \
            .withColumn("id", F.expr(f"get_json_object(json, '$.{PRIMARY_KEY_PATH}')")) \
            .withColumn("_etl_timestamp", F.col("_metadata.file_modification_time")) \
            .withColumn("_metadata", F.col("_metadata").cast(T.StringType())) \
            .withColumn("_etl_operation", F.lit("U")) \
            .withColumn("_etl_to_delete", F.lit(False)) \
            .withColumn("_etl_file_name", F.input_file_name()) \
            .withColumn("_etl_job_processing_timestamp", F.current_timestamp()) \
            .withColumn("_etl_table", F.lit(f"{TABLE_NAME}")) \
            .withColumn("_etl_partition_date", F.to_date(F.col("_etl_timestamp"), "yyyy-MM-dd")) \
            .select("_etl_operation", "_etl_timestamp", "id", "json", "_etl_file_name", "_etl_job_processing_timestamp", "_etl_table", "_etl_partition_date", "_etl_to_delete", "_metadata")

@dlt.table(
name=f"{SCHEMA}_{TABLE_NAME}_silver",
table_properties = {
        "quality": "silver",
        "delta.autoOptimize.optimizeWrite": "true",
        "delta.autoOptimize.autoCompact": "true"
}
)
def silver_job():
    df = dlt.read_stream(f"{SCHEMA}_{TABLE_NAME}_bronze").where("_etl_table == 'extraction'")
    return df.select(
                    df.id.alias('medium_id'),
                    F.get_json_object(df.json, '$.request').alias('request_id'))
</code>```

Thank you very much for your help!

Body:
I am working on a pipeline in Databricks > Workflows > Delta Live Tables and having an issue with the streaming part.

Expectations:

One bronze table reads the json files with AutoLoader (cloudFiles), in a streaming mode (spark.readStream)

One silver table reads and flattens the bronze table in streaming (dlt.read_stream)

Result:

When taking the root location as the source (load /*, several hundreds of files): the pipelines starts, but the number of rows/files appended is not updated in the graph until the bronze part be completed. Then, the silver part starts, the number of files/rows never updates either and the pipeline terminates with a memory error.

When taking a very small number of files (/specific_folder among hundreds) : the pipeline runs well and terminates with no error, but again, the number of rows/files appended is not updated in the graph until each part is completed.

This led me to the conclusion that the pipeline seems not to run in a streaming mode.
Maybe I am missing something about the config or how to run properly a DLT pipeline, and would need your help on this please.

Here is the configuration of the pipeline:

{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"clusters": [
    {
        "label": "default",
        "aws_attributes": {
            "instance_profile_arn": "arn:aws:iam::xxxxxxxxxxxx:instance-profile/iam_role_example"
        },
        "autoscale": {
            "min_workers": 1,
            "max_workers": 10,
            "mode": "LEGACY"
        }
    }
],
"development": true,
"continuous": false,
"channel": "CURRENT",
"edition": "PRO",
"photon": false,
"libraries": [
    {
        "notebook": {
            "path": "/Repos/user_example@xxxxxx.xx/dms/bronze_job"
        }
    }
],
"name": "01-landing-task-1",
"storage": "dbfs:/pipelines/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"configuration": {
    "SCHEMA": "example_schema",
    "RAW_MOUNT_NAME": "xxxx",
    "DELTA_MOUNT_NAME": "xxxx",
    "spark.sql.parquet.enableVectorizedReader": "false"
},
"target": "landing"}

Here is the code of the pipeline (the query in the silver table contains many more columns with a get_json_object, ~30 actually):

import dlt
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.sql.window import Window

RAW_MOUNT_NAME = spark.conf.get("RAW_MOUNT_NAME")
SCHEMA = spark.conf.get("SCHEMA")
SOURCE = spark.conf.get("SOURCE")
TABLE_NAME = spark.conf.get("TABLE_NAME")
PRIMARY_KEY_PATH = spark.conf.get("PRIMARY_KEY_PATH")

@dlt.table(
    name=f"{SCHEMA}_{TABLE_NAME}_bronze",
    table_properties={
        "quality": "bronze"
    }
)
def bronze_job():
    load_path = f"/mnt/{RAW_MOUNT_NAME}/{SOURCE}/5e*"

    return spark \
            .readStream \
            .format("text") \
            .option("encoding", "UTF-8") \
            .load(load_path) \
            .select("value", "_metadata") \
            .withColumnRenamed("value", "json") \
            .withColumn("id", F.expr(f"get_json_object(json, '$.{PRIMARY_KEY_PATH}')")) \
            .withColumn("_etl_timestamp", F.col("_metadata.file_modification_time")) \
            .withColumn("_metadata", F.col("_metadata").cast(T.StringType())) \
            .withColumn("_etl_operation", F.lit("U")) \
            .withColumn("_etl_to_delete", F.lit(False)) \
            .withColumn("_etl_file_name", F.input_file_name()) \
            .withColumn("_etl_job_processing_timestamp", F.current_timestamp()) \
            .withColumn("_etl_table", F.lit(f"{TABLE_NAME}")) \
            .withColumn("_etl_partition_date", F.to_date(F.col("_etl_timestamp"), "yyyy-MM-dd")) \
            .select("_etl_operation", "_etl_timestamp", "id", "json", "_etl_file_name", "_etl_job_processing_timestamp", "_etl_table", "_etl_partition_date", "_etl_to_delete", "_metadata")

@dlt.table(
name=f"{SCHEMA}_{TABLE_NAME}_silver",
table_properties = {
        "quality": "silver",
        "delta.autoOptimize.optimizeWrite": "true",
        "delta.autoOptimize.autoCompact": "true"
}
)
def silver_job():
    df = dlt.read_stream(f"{SCHEMA}_{TABLE_NAME}_bronze").where("_etl_table == 'extraction'")
    return df.select(
                    df.id.alias('medium_id'),
                    F.get_json_object(df.json, '$.request').alias('request_id'))

Thank you very much for your help!


问:
KeyError: 'children' webscraping
I am trying to scrape data from this website but the code keeps returning the KeyError: 'children' error. The code I have right now is:

```<code>import re
import json
import requests
import pandas as pd
import os

r = requests.get('https://openbilanci.it/armonizzati/bilanci/grotte-comune-ag/spese/dettaglio?year=2021&type=preventivo')
p = re.compile("var bilancio_tree = (.*?);")
data = p.search(r.text).group(1)

data = json.loads(data)

all_data = []

for d in data:
    for v in d["values"]:
        for kk, vv in v.items():
            all_data.append([d["label"], "-", kk, vv.get("abs"), vv.get("pc")])

    for c in d["children"]:
        for v in c["values"]:
            for kk, vv in v.items():
                all_data.append(
                    [d["label"], c["label"], kk, vv.get("abs"), vv.get("pc")]
                    )

df = pd.DataFrame(all_data, columns=["label 1", "label 2", "year", "abs", "PC"])
</code>```

I am not sure why it's happening. print(data) returns the following:

```<code>[{'slug': 'pcox-quadro-4-26', 'label': 'TOTALE GENERALE DELLE SPESE', 'values': [{'2021': {'abs': 20284661.0, 'pc': 3790.10855754858}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}], 'composition': {'hash': '5f19812c', 'correnti_value': 6362017.319999999, 'correnti_perc': 31.36368569334237, 'investimenti_value': 5301441.209999999, 'investimenti_perc': 26.135222126709433, 'incremento_fin_value': 0.0, 'incremento_fin_perc': 0.0, 'altro_value': 8619152.469999999, 'altro_perc': 42.49098602140799, 'label': 'Spese per conto terzi e partite di giro'}}, {'slug': 'pcox-quadro-4-1', 'label': 'Disavanzo di Amministrazione', 'values': [{'2021': {'abs': 210404.27, 'pc': 39.3132044095665}}, {'2022': {'abs': 210404.27, 'pc': 39.3132044095665}}, {'2023': {'abs': 210404.27, 'pc': 39.3132044095665}}], 'children': [], 'composition': {'hash': 'bf7de1c6'}}, {'slug': 'pcox-quadro-4-2', 'label': 'Servizi istituzionali, generali e di gestione', 'values': [{'2021': {'abs': 5291002.99, 'pc': 988.602950298954}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}], 'children': [{'slug': 'pcox-quadro-4-2-1', 'label': 'Organi istituzionali', 'values': [{'2021': {'abs': 279001.21, 'pc': 52.1302709267564}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}], 'children': [{'slug': 'pcox-quadro-4-2-1-23', 'label': 'Titolo 1 - Spese correnti', 'values': [{'2021': {'abs': 279001.21, 'pc': 52.1302709267564}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}]}, {'slug': 'pcox-quadro-4-2-1-33', 'label': 'Titolo 2 - Spese in conto capitale', 'values': [{'2021': {'abs': 0.0, 'pc': 0.0}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, ............]
</code>```

Title: KeyError: 'children' webscraping

Body:
I am trying to scrape data from this website but the code keeps returning the KeyError: 'children' error. The code I have right now is:

import re
import json
import requests
import pandas as pd
import os

r = requests.get('https://openbilanci.it/armonizzati/bilanci/grotte-comune-ag/spese/dettaglio?year=2021&type=preventivo')
p = re.compile("var bilancio_tree = (.*?);")
data = p.search(r.text).group(1)

data = json.loads(data)

all_data = []

for d in data:
    for v in d["values"]:
        for kk, vv in v.items():
            all_data.append([d["label"], "-", kk, vv.get("abs"), vv.get("pc")])

    for c in d["children"]:
        for v in c["values"]:
            for kk, vv in v.items():
                all_data.append(
                    [d["label"], c["label"], kk, vv.get("abs"), vv.get("pc")]
                    )

df = pd.DataFrame(all_data, columns=["label 1", "label 2", "year", "abs", "PC"])

I am not sure why it's happening. print(data) returns the following:

[{'slug': 'pcox-quadro-4-26', 'label': 'TOTALE GENERALE DELLE SPESE', 'values': [{'2021': {'abs': 20284661.0, 'pc': 3790.10855754858}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}], 'composition': {'hash': '5f19812c', 'correnti_value': 6362017.319999999, 'correnti_perc': 31.36368569334237, 'investimenti_value': 5301441.209999999, 'investimenti_perc': 26.135222126709433, 'incremento_fin_value': 0.0, 'incremento_fin_perc': 0.0, 'altro_value': 8619152.469999999, 'altro_perc': 42.49098602140799, 'label': 'Spese per conto terzi e partite di giro'}}, {'slug': 'pcox-quadro-4-1', 'label': 'Disavanzo di Amministrazione', 'values': [{'2021': {'abs': 210404.27, 'pc': 39.3132044095665}}, {'2022': {'abs': 210404.27, 'pc': 39.3132044095665}}, {'2023': {'abs': 210404.27, 'pc': 39.3132044095665}}], 'children': [], 'composition': {'hash': 'bf7de1c6'}}, {'slug': 'pcox-quadro-4-2', 'label': 'Servizi istituzionali, generali e di gestione', 'values': [{'2021': {'abs': 5291002.99, 'pc': 988.602950298954}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}], 'children': [{'slug': 'pcox-quadro-4-2-1', 'label': 'Organi istituzionali', 'values': [{'2021': {'abs': 279001.21, 'pc': 52.1302709267564}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}], 'children': [{'slug': 'pcox-quadro-4-2-1-23', 'label': 'Titolo 1 - Spese correnti', 'values': [{'2021': {'abs': 279001.21, 'pc': 52.1302709267564}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, {'2023': {'abs': 0.0, 'pc': 0.0}}]}, {'slug': 'pcox-quadro-4-2-1-33', 'label': 'Titolo 2 - Spese in conto capitale', 'values': [{'2021': {'abs': 0.0, 'pc': 0.0}}, {'2022': {'abs': 0.0, 'pc': 0.0}}, ............]


问:
ValueError with Sklearn LinearRegression model.predict()
I am trying to do a simple linear regression model to estimate the sales price of an item for borrowers we don't have contract information on. I'm using data from borrowers we do have price and payment info on and using sklearn's LinearRegression model but getting an error when I call the predict() method on the model. The exact error:

ValueError: X has 844 features, but LinearRegression is expecting 2529 features as input.

Here is my code, I feel like it's fairly straightforward. The build_customer_df is a method call that returns the dataframe with some column formatting, nothing fancy:
`

```<code>fp = Path('master_borrower.xlsx')

df = build_customer_df(fp)

df = df[['payment', 'trailer_sales_price']]
df = df[df['payment']!= 0]

X = df['payment'].values
y = df['trailer_sales_price'].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)

X_test = X_test.reshape(1,-1)
X_train = X_train.reshape(1,-1)
y_train = y_train.reshape(1,-1)
y_test = y_test.reshape(1,-1)

model = linear_model.LinearRegression()

model.fit(X_train, y_train)

predictions = model.predict(X_test)
</code>```

Body:
I am trying to do a simple linear regression model to estimate the sales price of an item for borrowers we don't have contract information on. I'm using data from borrowers we do have price and payment info on and using sklearn's LinearRegression model but getting an error when I call the predict() method on the model. The exact error:

ValueError: X has 844 features, but LinearRegression is expecting 2529 features as input.

Here is my code, I feel like it's fairly straightforward. The build_customer_df is a method call that returns the dataframe with some column formatting, nothing fancy:
`

fp = Path('master_borrower.xlsx')

df = build_customer_df(fp)

df = df[['payment', 'trailer_sales_price']]
df = df[df['payment']!= 0]

X = df['payment'].values
y = df['trailer_sales_price'].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)

X_test = X_test.reshape(1,-1)
X_train = X_train.reshape(1,-1)
y_train = y_train.reshape(1,-1)
y_test = y_test.reshape(1,-1)

model = linear_model.LinearRegression()

model.fit(X_train, y_train)

predictions = model.predict(X_test)


问:
I want to download a file from sever through another server
I have 2 servers; I have a file saved on one let's call it server A. Server A is not accessible to the public, only other servers in the architecture can access it. I have another server, server B, server B is accessible to the public. Server A and B are communicating through network calls.

I exposed an endpoint on server B, to allow users download the file saved on server A. The implementation of all this(in SpringBoot) is the code below;

```<code>//on server B I have an endpoint that a user can call to get a file
@Controller
public class getFileController{

@Autowired
private FileClient fileClient

@GetMapping({"getFile/{fileName}"})
public ResponseEntity<InputStreamResource> downloadCSV(@PathVariable("fileName") String
fileName){

byte[] fileBytes= fileClient.getFile(fileName).getBody();
//i have to wait for file bytes to download from server A before i start uploading to the
//users browser
return ResponseEntity.ok().contentLength(filebytes.length)
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.headers(headers).body(new InputStreamResource(fileBytes));

}
}

//on server B i have a feign client that calls server A
@FeignClient(
name = "callServerA",
path = "/getFile"
)
public interface FileClient {

@GetMapping({"/{fileName}"})
ResponseEntity<byte[]> getFile(@PathVariable("fileName") String var1);

}

//there is an endpoint on server A that would return a  ResponseEntity<byte[]> object when
//the FileClient.getFile(String string) method is called in server B```
```

My problem:
How do i get server B to upload individual bytes to the user's browser as it gets it from server A? The behaviour now is that server B waits for the full byte array to download from server A before it starts uploading to the user's browser. Thank you.

Body:
I have 2 servers; I have a file saved on one let's call it server A. Server A is not accessible to the public, only other servers in the architecture can access it. I have another server, server B, server B is accessible to the public. Server A and B are communicating through network calls.

I exposed an endpoint on server B, to allow users download the file saved on server A. The implementation of all this(in SpringBoot) is the code below;

//on server B I have an endpoint that a user can call to get a file
@Controller
public class getFileController{

@Autowired
private FileClient fileClient

@GetMapping({"getFile/{fileName}"})
public ResponseEntity<InputStreamResource> downloadCSV(@PathVariable("fileName") String
fileName){

byte[] fileBytes= fileClient.getFile(fileName).getBody();
//i have to wait for file bytes to download from server A before i start uploading to the
//users browser
return ResponseEntity.ok().contentLength(filebytes.length)
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.headers(headers).body(new InputStreamResource(fileBytes));

}
}

//on server B i have a feign client that calls server A
@FeignClient(
name = "callServerA",
path = "/getFile"
)
public interface FileClient {

@GetMapping({"/{fileName}"})
ResponseEntity<byte[]> getFile(@PathVariable("fileName") String var1);

}

//there is an endpoint on server A that would return a  ResponseEntity<byte[]> object when
//the FileClient.getFile(String string) method is called in server B```

My problem:
How do i get server B to upload individual bytes to the user's browser as it gets it from server A? The behaviour now is that server B waits for the full byte array to download from server A before it starts uploading to the user's browser. Thank you.


问:
Trouble with GLMM in R: Error in gamma(link = "identity") : supplied argument name 'link' does not match 'x'
I am trying to fit a GLMM to my dataset and am having trouble finding a good family and link. My response variable is continuous, positive, and skewed to the left (see image).

I thought that gamma would be the best family. However, I've tried inverse, identity, and log as links, but for each of them, I am getting the error message below. Does anyone know what this means? My code is also below. I'm wondering if gamma is not the right family to be using?

Thanks in advance!

glmer(Cortisol.Metabolites ~ Time.Point+New.Time.Frame+Time.Point*New.Time.Frame+(1|Individual), data=data, family = gamma(link="identity"))

Error in gamma(link = "identity") : supplied argument name 'link' does not match 'x'


问:
How can I download a torrent file by URL in java?
Please tell me how can I download a torrent file by URL in java so that it will open in torrent later. This solution saves the file but the torrent doesn't accept it afterwards.


问:
NextJS on-demand revalidation for server layout component
I have just started working on a new application using NextJS 13 and MongoDB.

This application has a navigation menu whose elements depend on a configuration object stored in the DB. As it is set now, the navigation menu is part of a server layout component that fetches the configuration object from the DB and then it displays it. Since I want this navigation menu to be configurable, I implemented an admin page where an admin user can change the configuration object for the navigation menu stored in the DB.

In order to update the navigation menu when the configuration object changes, I first set the revalidate variable. Then, I discovered the on-demand revalidation feature and I immediately tried the example (since I see it more ideal for my use case). However, it seems to work only for pages (specifying the routes). Since my layout component is used on every page, I should specify the routes of all the pages to revalidate the layout.

Thus, is there a way to use on-demand revalidation to revalidate a layout component in NextJS 13? If possible, I would like to avoid the automatic revalidation.


问:
Tests stall for no obvious reason
I have been happily unit testing in Laravel 9 for the last few days and am gradually getting the hang of how to write tests for various circumstances. I ran many tests and was learning a lot when suddenly, for no obvious reason, the php artisan test command stopped working properly. Starting at about 11am today, the very first test in the very first test case executes successfully and then the whole thing just stalls: no other tests are attempted. There are no error messages and waiting prolonged periods doesn't result in the tests restarting on their own.

I've tried doing a CTRL-C to break out of the test and then started again. Same result. I've tried closing the terminal window, opening another and running php artisan test again. I've tried using a different terminal window outside of VS Code altogether. Same result. I've tried closing and re-opening VS Code. Same result. I've even rebooted the computer (I'm running Windows 10) but am getting exactly the same result. I just can't get beyond the first test in the first test case.

I can't think of anything else to try. The second test case has been run successfully many times so I can't believe it is the problem. Can anyone suggest what the problem might be and how I can get past it?

I'm using PHPUnit 9.x.

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

As per Matias' suggestion, I ran php artisan test -vvv on my test suite. (I also renamed all of the files in the Unit Test directory so that they wouldn't run, except for the two ExampleTest test cases that were generated by Laravel, one for feature testing and one for unit testing.) The very long stacktrace pointed to an inability of the tests to connect to my local MySQL database. That made sense because I hadn't restarted XAMPP after the reboot. (Then again, I didn't see the urgency because none of the code I was testing used the database; they dealt with strings, arrays and collections.) I restarted XAMPP, including Apache and MySQL. Now, all tests the ExampleTest test cases completed. I renamed my Helper2Txxx.php to Helper2Test.php and assumed it would run smoothly now. Unfortunately, that didn't happen. Helper2Text.php don't run at all: the testing stopped as soon as the ExampleTest had finished.

I commented out all but the most trivial test in Helper2Test and it ran successfully. I uncommented a few tests at a time until I found the one that made all of the test cycle stop and that (unsurprisingly) turned out to be the last one I had written. Further investigation revealed that a small function I'd written to help with the testing was running into a memory error:

```<code>Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 264257536 bytes) in C:\Laravel\laragigs\tests\Unit\Helper2Test.php on line 154
</code>```

It looks very much like I have to fix up my small function but I won't be able to do that to untilmorrow sometime. My working theory is that this memory error is the big problem that somehow breaks artisan test; somehow this kept the successful tests earlier in Helper2Test from displaying so that I had no idea where/why the test command was failing.

I'll update here as I learn more. I think I will be able to fix this problem myself but I'll leave the problem open in case I turn out to be wrong.

```<code>UPDATE 2
</code>```

Everything is working now. I reworked my small function to accomplish the same thing via explode() instead of strtok() and it now works perfectly with no memory issues.

Thank you, Matias, for reminding me that I can get diagnostics by using the -vvv subcommand! That was the critical step in figuring out what was wrong.

Title: Tests stall for no obvious reason

Body:
I have been happily unit testing in Laravel 9 for the last few days and am gradually getting the hang of how to write tests for various circumstances. I ran many tests and was learning a lot when suddenly, for no obvious reason, the php artisan test command stopped working properly. Starting at about 11am today, the very first test in the very first test case executes successfully and then the whole thing just stalls: no other tests are attempted. There are no error messages and waiting prolonged periods doesn't result in the tests restarting on their own.

I've tried doing a CTRL-C to break out of the test and then started again. Same result. I've tried closing the terminal window, opening another and running php artisan test again. I've tried using a different terminal window outside of VS Code altogether. Same result. I've tried closing and re-opening VS Code. Same result. I've even rebooted the computer (I'm running Windows 10) but am getting exactly the same result. I just can't get beyond the first test in the first test case.

I can't think of anything else to try. The second test case has been run successfully many times so I can't believe it is the problem. Can anyone suggest what the problem might be and how I can get past it?

I'm using PHPUnit 9.x.

UPDATE

As per Matias' suggestion, I ran php artisan test -vvv on my test suite. (I also renamed all of the files in the Unit Test directory so that they wouldn't run, except for the two ExampleTest test cases that were generated by Laravel, one for feature testing and one for unit testing.) The very long stacktrace pointed to an inability of the tests to connect to my local MySQL database. That made sense because I hadn't restarted XAMPP after the reboot. (Then again, I didn't see the urgency because none of the code I was testing used the database; they dealt with strings, arrays and collections.) I restarted XAMPP, including Apache and MySQL. Now, all tests the ExampleTest test cases completed. I renamed my Helper2Txxx.php to Helper2Test.php and assumed it would run smoothly now. Unfortunately, that didn't happen. Helper2Text.php don't run at all: the testing stopped as soon as the ExampleTest had finished.

I commented out all but the most trivial test in Helper2Test and it ran successfully. I uncommented a few tests at a time until I found the one that made all of the test cycle stop and that (unsurprisingly) turned out to be the last one I had written. Further investigation revealed that a small function I'd written to help with the testing was running into a memory error:

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 264257536 bytes) in C:\Laravel\laragigs\tests\Unit\Helper2Test.php on line 154

It looks very much like I have to fix up my small function but I won't be able to do that to untilmorrow sometime. My working theory is that this memory error is the big problem that somehow breaks artisan test; somehow this kept the successful tests earlier in Helper2Test from displaying so that I had no idea where/why the test command was failing.

I'll update here as I learn more. I think I will be able to fix this problem myself but I'll leave the problem open in case I turn out to be wrong.

UPDATE 2

Everything is working now. I reworked my small function to accomplish the same thing via explode() instead of strtok() and it now works perfectly with no memory issues.

Thank you, Matias, for reminding me that I can get diagnostics by using the -vvv subcommand! That was the critical step in figuring out what was wrong.


问:
HybridAuth 3.0 - fresh install - getting: Class 'Hybridauth\Hybridauth\Provider\Facebook' not found
all. I've installed HybridAuth 3.0 and went step-by-step through the Install instructions using composer. I've used the example code and am able to get an initial HybridAuth class instantiated. However, when I continue on to the example with using the Facebook provider class, I'm getting the error, "Class 'Hybridauth\Hybridauth\Provider\Facebook' not found".  I'm also using this in a Drupal 7 environment but have other classes like this that autoload just fine so I'm hopeful that little extra detail has no bearing on the problem.

I tried this both with the composer autoloader and the basic autoloader included with the library (as described in the Installation instructions). They both have the same error when attempting to find the Facebook class which is down in the /src/Provider directory. It does this for other classes as well.

That said, using the Hybridauth\Hybridauth "unified interface" works fine and is my current workaround as it allows one to work with multiple providers at one time. But I'm wondering what I'm doing wrong to not be able to load a specific provider as shown in their Introduction documentation.

This works:

```<code>// Include Composer's autoloader
include 'vendor/autoload.php';
// Import Hybridauth's namespace
use Hybridauth\Hybridauth;
// Now we may proceed and instantiate Hybridauth's classes
$instance = new Hybridauth([ /* ... */ ]);
</code>```

This gives an error:

```<code>// Include Composer's autoloader
include 'vendor/autoload.php';
// Import Hybridauth's namespace
use Hybridauth\Hybridauth;
$adapter = new Hybridauth\Provider\Facebook([ /* ... */ ]);
</code>```

Body:
all. I've installed HybridAuth 3.0 and went step-by-step through the Install instructions using composer. I've used the example code and am able to get an initial HybridAuth class instantiated. However, when I continue on to the example with using the Facebook provider class, I'm getting the error, "Class 'Hybridauth\Hybridauth\Provider\Facebook' not found".  I'm also using this in a Drupal 7 environment but have other classes like this that autoload just fine so I'm hopeful that little extra detail has no bearing on the problem.

I tried this both with the composer autoloader and the basic autoloader included with the library (as described in the Installation instructions). They both have the same error when attempting to find the Facebook class which is down in the /src/Provider directory. It does this for other classes as well.

That said, using the Hybridauth\Hybridauth "unified interface" works fine and is my current workaround as it allows one to work with multiple providers at one time. But I'm wondering what I'm doing wrong to not be able to load a specific provider as shown in their Introduction documentation.

This works:

// Include Composer's autoloader
include 'vendor/autoload.php';
// Import Hybridauth's namespace
use Hybridauth\Hybridauth;
// Now we may proceed and instantiate Hybridauth's classes
$instance = new Hybridauth([ /* ... */ ]);

This gives an error:

// Include Composer's autoloader
include 'vendor/autoload.php';
// Import Hybridauth's namespace
use Hybridauth\Hybridauth;
$adapter = new Hybridauth\Provider\Facebook([ /* ... */ ]);


问:
pdb file is not the pdb file that was used when this precompiled header was created, recreated the precompiled header
I am using JUCE to create an audio plugin, and on first build, I received several of the following error.

C2859   C:\Users\ksa10\Desktop\LUX\LUX\Builds\VisualStudio2022\x64\Debug\Shared Code\LUX.pdb is not the pdb file that was used when this precompiled header was created, recreate the precompiled header.

I believe this is an repetition error with improper conditional compilation in the files automatically created by JUCE, but I have not found any answers yet. If it helps, all of my header files start with #pragma once.

I am new to c++ and completely self-taught, so go easy on me.


问:
How do you find out if a site has mouse movement detection and/or recording installed?
I'm doing web scraping with Python on difficult sites such as Instagram, Facebook, and so on... Since it is likely that these sites do monitor your mouse movements in order to recognize scrapers vs real humans. What I do struggle find out it how to find out if a site has one of these mouse tracking, detecting, and/or movement recording, installed? And as browsers do state that even with their tracking option turned off it is still impossible to know how the scraped site would interpret this, are there reliable options to turn mouse movement monitor services off?


问:
Excel - convert cell from hex string to SHIFT-JIS characters
I need to convert space delineated hex values (ie. "B2 DD C0 B0 C8 AF C4 20 B9 DE B0 D1 81 48") in a column of cells to their SHIFT-JIS character equivalent in Excel. These strings may also include line breaks that need to be included in the translated cell value.

All of the functions and VBA code examples I've located so far appear to only work with western ascii values or unicode, which displays the incorrect characters. Converting by importing from CSV is not a viable solution, since the values are extracted from another hex dump in another worksheet (hex string extracted by using an offset table for length).

Tried using a sample VBA function to convert the hex characters, but it's not able to properly convert the SHIFT-JIS encoding.

=HexToString(SUBSTITUTE(I2,CHAR(32),"")) will result in "²ÝÀ°È¯Ä ¹Þ°ÑH" instead of "ｲﾝﾀｰﾈｯﾄ ｹﾞｰﾑ？"

```<code>Public Function HexToString(InitialString As String) As String
    Dim i As Long
    For i = 1 To Len(InitialString) Step 2
        HexToString = HexToString & Chr("&H" & (Mid(InitialString, i, 2)))
    Next i
End Function
</code>```

Body:
I need to convert space delineated hex values (ie. "B2 DD C0 B0 C8 AF C4 20 B9 DE B0 D1 81 48") in a column of cells to their SHIFT-JIS character equivalent in Excel. These strings may also include line breaks that need to be included in the translated cell value.

All of the functions and VBA code examples I've located so far appear to only work with western ascii values or unicode, which displays the incorrect characters. Converting by importing from CSV is not a viable solution, since the values are extracted from another hex dump in another worksheet (hex string extracted by using an offset table for length).

Tried using a sample VBA function to convert the hex characters, but it's not able to properly convert the SHIFT-JIS encoding.

=HexToString(SUBSTITUTE(I2,CHAR(32),"")) will result in "²ÝÀ°È¯Ä ¹Þ°ÑH" instead of "ｲﾝﾀｰﾈｯﾄ ｹﾞｰﾑ？"

Public Function HexToString(InitialString As String) As String
    Dim i As Long
    For i = 1 To Len(InitialString) Step 2
        HexToString = HexToString & Chr("&H" & (Mid(InitialString, i, 2)))
    Next i
End Function


问:
Problems jQueryUI latest version with tooltip widget
For the first here for posing a question. I've already learned a lot from the site.

My problem is that i can't get the jQuery UI widget tooltip working on my site.
I'm on joomla 4 with an RSJoomla template (RSJuno).

In my custom.js file i've added this code for diplaying images full size:

```<code>//Photos fullscreen
jQuery(document).ready(function(){
            jQuery("img").click(function(){
                this.requestFullscreen()})});
</code>```

Works well.

Now i'm trying this code:

```<code>//Tooltip on fotos
jQuery(document).ready(function(){
jQuery( "div" ).tooltip({
  content: "Awesome title!"
});
});
</code>```

Not working at all. Content is just a test text! If i use "img" it isn't working either. Nothing shows up.

This code (from internet) as a test is also working well.
(Div and img are both used to test so i'm aware of the difference in the code.

```<code>jQuery(document).ready(function () {
    // Detect when the mouse is over a div with the mouseover() method
    jQuery( "div" ).mouseover(function ( event ) {
        // Make the div under the mouse grey and taller
        jQuery( "div" ).tooltip({
        content: "Awesome title!"
//By the way the tooltip is NOT showing the content text//
});
        jQuery( "#" + event.target.id ).css({
           "background-color" : "lightgrey",
           "height" : "8em"
        });
    });

    // Detect when the mouse moves away with the mouseout() method
    jQuery( "div" ).mouseout(function ( event ) {
        // Return the size and color of the div to its original state
        jQuery( "#" + event.target.id ).css({
           "background-color" : "white",
            "height" : "4em"
        });
    });
});
</code>```

I would like to have a code which integrates this 2 codes into 1 simple one that does the following:

on mouseover displaying tooltip "Click for fullscreen" on  tag;

as mouse moves away, hide the tooltip.

Whatever i'm trying in no way i get the tooltip to display, no mather to what  i connect it: "img" "div"....etc. And thus combining the 2 leads to nothing.

The big code is working in so far that the css styled tooltip is shown, but at a fixed place (center of the div) and ONLY on a specially created div in the page. NOT on the "img" tag.

If a attach this long code with css to the special created div it's shows only the content of the tag title on the div and not the custom text.
If i delete the title tag from the div nothing shows.

Could it be a conflict with the template code?

I have a RSJoomla template and through custom  tags in the template i'm loading the necessary libraries as follows:

```<code><link href="/templates/rsjuno/js/jquery-ui/jquery-ui.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.structure.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.theme.css" rel="stylesheet" />
</code>```

From inspecting my page i see that this is well loaded:

```<code><link rel="stylesheet" href="/templates/rsjuno/css/custom.css" type="text/css" />
<script src="/templates/rsjuno/js//jquery-ui/jquery-ui.js"></script>
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.structure.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.theme.css" rel="stylesheet" /> </head>
<body class="site">
....
</code>```

After spending lots of hours i'm out of ideas. Lots of different codes i found on internet for the tooltip didn't work either.
For example (on the youtube video its working well):

```<code>    jQuery("img").tooltip({
    track:true,
    content:"Whow"
    });
    });
</code>```

I need to use jQuery instead of $ to avoid "$ is not a function" error.

So please help if you can.

Ps i cannot provide a link to the site because its developped on localhost.

Thanks

NEW INFO  I've used this working fiddle (https://jsfiddle.net/vinorodrigues/2vnt9a0h/32/) in exact copy on my website and still get a standard layout tooltip.  See this screenshot enter image description here

Body:
For the first here for posing a question. I've already learned a lot from the site.

My problem is that i can't get the jQuery UI widget tooltip working on my site.
I'm on joomla 4 with an RSJoomla template (RSJuno).

In my custom.js file i've added this code for diplaying images full size:

//Photos fullscreen
jQuery(document).ready(function(){
            jQuery("img").click(function(){
                this.requestFullscreen()})});

Works well.

Now i'm trying this code:

//Tooltip on fotos
jQuery(document).ready(function(){
jQuery( "div" ).tooltip({
  content: "Awesome title!"
});
});

Not working at all. Content is just a test text! If i use "img" it isn't working either. Nothing shows up.

This code (from internet) as a test is also working well.
(Div and img are both used to test so i'm aware of the difference in the code.

jQuery(document).ready(function () {
    // Detect when the mouse is over a div with the mouseover() method
    jQuery( "div" ).mouseover(function ( event ) {
        // Make the div under the mouse grey and taller
        jQuery( "div" ).tooltip({
        content: "Awesome title!"
//By the way the tooltip is NOT showing the content text//
});
        jQuery( "#" + event.target.id ).css({
           "background-color" : "lightgrey",
           "height" : "8em"
        });
    });

    // Detect when the mouse moves away with the mouseout() method
    jQuery( "div" ).mouseout(function ( event ) {
        // Return the size and color of the div to its original state
        jQuery( "#" + event.target.id ).css({
           "background-color" : "white",
            "height" : "4em"
        });
    });
});

I would like to have a code which integrates this 2 codes into 1 simple one that does the following:

on mouseover displaying tooltip "Click for fullscreen" on  tag;

as mouse moves away, hide the tooltip.

Whatever i'm trying in no way i get the tooltip to display, no mather to what  i connect it: "img" "div"....etc. And thus combining the 2 leads to nothing.

The big code is working in so far that the css styled tooltip is shown, but at a fixed place (center of the div) and ONLY on a specially created div in the page. NOT on the "img" tag.

If a attach this long code with css to the special created div it's shows only the content of the tag title on the div and not the custom text.
If i delete the title tag from the div nothing shows.

Could it be a conflict with the template code?

I have a RSJoomla template and through custom  tags in the template i'm loading the necessary libraries as follows:

<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.structure.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.theme.css" rel="stylesheet" />

From inspecting my page i see that this is well loaded:

<link rel="stylesheet" href="/templates/rsjuno/css/custom.css" type="text/css" />

<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.structure.css" rel="stylesheet" />
<link href="/templates/rsjuno/js/jquery-ui/jquery-ui.theme.css" rel="stylesheet" />

....

After spending lots of hours i'm out of ideas. Lots of different codes i found on internet for the tooltip didn't work either.
For example (on the youtube video its working well):

    jQuery("img").tooltip({
    track:true,
    content:"Whow"
    });
    });

I need to use jQuery instead of $ to avoid "$ is not a function" error.

So please help if you can.

Ps i cannot provide a link to the site because its developped on localhost.

Thanks

NEW INFO  I've used this working fiddle (https://jsfiddle.net/vinorodrigues/2vnt9a0h/32/) in exact copy on my website and still get a standard layout tooltip.  See this screenshot enter image description here


问:
Does deleting a lot of a rows in a transaction hurt with postgresql?
Say there are 3 tasks:

Insert rows to table_a.

Select rows in table_a, and select scope may cover the entire table.

Delete rows from table_a:

delete from table_a where timestamp < certain_time
```
<p>As the delete condition is based on timestamp, sometime it may delete huge amount of rows. And as other tables have foreign keys refer to <code>table_a</code> with <code>on delete cascade</code>, a delete transaction may take long time.</p>
<p>From Postgres Table lock on delete query, looks like <code>delete</code> won't impact <code>insert</code>. But will <code>delete</code> impact <code>select</code>? <code>delete</code> locks rows to be deleted, and <code>select</code> may search over those rows.</p>
<p>Will keeping delete transaction small be necessary and safer, such as:</p>
<pre class="lang-sql prettyprint-override"><code>delete from table_a where id in (
    select id from table_a timestamp < certain_time limit 1000
)
</code>```

NOTE: in my case, it's NOT super important to delete rows as early as possible.

Body:
Say there are 3 tasks:

Insert rows to table_a.

Select rows in table_a, and select scope may cover the entire table.

Delete rows from table_a:

delete from table_a where timestamp < certain_time

As the delete condition is based on timestamp, sometime it may delete huge amount of rows. And as other tables have foreign keys refer to table_a with on delete cascade, a delete transaction may take long time.

From Postgres Table lock on delete query, looks like delete won't impact insert. But will delete impact select? delete locks rows to be deleted, and select may search over those rows.

Will keeping delete transaction small be necessary and safer, such as:

delete from table_a where id in (
    select id from table_a timestamp < certain_time limit 1000
)

NOTE: in my case, it's NOT super important to delete rows as early as possible.