问:
JSON Stringify ignores nested objects on Redis publish
I am using Redis in my backend to scale subscriptions. I am using this library to implement redis on top of my javascript code. And using mongoose for the models.

During a redis publish, I have to stringify the objects that I get from mongoose. I parse them on the subscribing end and it all works well until there's a nested object in the object that needs to be stringify-ed.

So if my object is this:

```<code>{ subtitle: '',
   description: '',
   checklists:
    [ { _id: 5cee450c0fa29d0b54275da0, items: [] },
      { _id: 5cee455c0c31785b0875e09d, items: [] },
      { _id: 5cee47dc6d32e72c6411ce2d, items: [] } ],
   attachments: [],
   labels: [],
   _id: 5ced1af26547233798f943f6,
   title: 'asfasf',
   box: 5cece1c3e6c3c13ff098658d,
   workflow: 5cece1cbe6c3c13ff0986591,
}
</code>```

I receive:

```<code>{ cardUpdated:
    {
      subtitle: '',
      description: '',
      checklists: [ [Object], [Object], [Object] ],
      attachments: [],
      labels: [],
      _id: '5ced1af26547233798f943f6',
      title: 'asfasf',
      box: '5cece1c3e6c3c13ff098658d',
      workflow: '5cece1cbe6c3c13ff0986591',
    }
}
</code>```

When I publish I use the following line:

```<code>pub.publish(types.CARD_UPDATED,
          JSON.stringify(
            { cardUpdated: await getUpdatedCardStats(checklist.card) },
          ));
</code>```

Note: I know that I am wrapping the argument for stringify in {} and without it the nested objects would not be ignored, but I need to do that because I need the key property name on the subscription end i.e. I am using this publish command with different key names at several places.

Is there a way to about this to get the nested objects stringify-ed?

EDIT: Turns out, I was getting the proper full object as a string on the subscribing end of Redis, but it was actually JSON.parse() that was the culprit. After parsing, it completely ignores the nested objects. Is there anyway to avoid this?

答:
This is not a valid JS object:

{ _id: 5cee450c0fa29d0b54275da0, items: [] }```

I think it's the output of .toString() of an object of type {_id: ObjectId, items: any[], with ObjectId defined here. In any case, the JSONification of this object is not trivial and that is why JSON.stringify simply outputs [Object].

To bypass this limitation, you might implement a custom function to transform your object into one that can be trivially JSONified, possibly with the help of ObjectId.toString().

Body:
I am using Redis in my backend to scale subscriptions. I am using this library to implement redis on top of my javascript code. And using mongoose for the models.

During a redis publish, I have to stringify the objects that I get from mongoose. I parse them on the subscribing end and it all works well until there's a nested object in the object that needs to be stringify-ed.

So if my object is this:

{ subtitle: '',
   description: '',
   checklists:
    [ { _id: 5cee450c0fa29d0b54275da0, items: [] },
      { _id: 5cee455c0c31785b0875e09d, items: [] },
      { _id: 5cee47dc6d32e72c6411ce2d, items: [] } ],
   attachments: [],
   labels: [],
   _id: 5ced1af26547233798f943f6,
   title: 'asfasf',
   box: 5cece1c3e6c3c13ff098658d,
   workflow: 5cece1cbe6c3c13ff0986591,
}

I receive:

{ cardUpdated:
    {
      subtitle: '',
      description: '',
      checklists: [ [Object], [Object], [Object] ],
      attachments: [],
      labels: [],
      _id: '5ced1af26547233798f943f6',
      title: 'asfasf',
      box: '5cece1c3e6c3c13ff098658d',
      workflow: '5cece1cbe6c3c13ff0986591',
    }
}

When I publish I use the following line:

pub.publish(types.CARD_UPDATED,
          JSON.stringify(
            { cardUpdated: await getUpdatedCardStats(checklist.card) },
          ));

Note: I know that I am wrapping the argument for stringify in {} and without it the nested objects would not be ignored, but I need to do that because I need the key property name on the subscription end i.e. I am using this publish command with different key names at several places.

Is there a way to about this to get the nested objects stringify-ed?

EDIT: Turns out, I was getting the proper full object as a string on the subscribing end of Redis, but it was actually JSON.parse() that was the culprit. After parsing, it completely ignores the nested objects. Is there anyway to avoid this?

Body:
This is not a valid JS object:

{ _id: 5cee450c0fa29d0b54275da0, items: [] }

I think it's the output of .toString() of an object of type {_id: ObjectId, items: any[], with ObjectId defined here. In any case, the JSONification of this object is not trivial and that is why JSON.stringify simply outputs [Object].

To bypass this limitation, you might implement a custom function to transform your object into one that can be trivially JSONified, possibly with the help of ObjectId.toString().


来源: stackexchange

问:
Lotus notes email in multiple folders
Is it possible to place an email into multiple lotus notes folders without creating a copy of the email? Essitiantly, I am looking for a way to create a shortcut to the same email in a different folder. For example, I have many emails relating to expenses. I would like to place the email in a folder I created called 'Airport Expenses', as well as in a folder I created called 'Business Travel DD/MM/YYYY', without duplicating the physical storage of the file. </p>

答: Be default, dragging between folders moves the email.  If you hold the control key while you drag an email, you can add it to a new folder without removing it from the original folder (i.e. copy it to a folder).  </p>

ContentLicense: CC BY-SA 3.0

Title: Lotus notes email in multiple folders


问:
With laravel mix in a laravel vue project how can I include scss files across all components?
I have been able to get this to work on just a basic vue application but I am having trouble bringing it across to laravel vue. I was able to add module in vue.config.js in the vue application that would import any scss files i added. Using the same code in the laravel vue app in the webpack.mix.js file it is not compiling correctly. This is my webpack.mis.js file:

```<code>let mix = require('laravel-mix');

module.exports = {
    css: {
        loaderOptions: {
            sass: {
                data: `@import "./resources/assets/sass/variables.scss";`
            }
        }
    }
};

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');
</code>```

I have also attempted the other configurations suggested from the docs but I haven't succeeded. I have also seen a lot of answers suggesting to just include the relative path to the files I wish to include in every component but this is inefficient and error prone as the application develops. There must be a way to achieve this and I have just got the configuration incorrect.

Any advice is appreciated, thanks.

答:
Laravel Mix has an option exactly for this. It's globalVueStyles.

Check out the documentation: https://github.com/JeffreyWay/laravel-mix/blob/master/docs/options.md.

It will only work with extractVueStyles active:

```<code>mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .options({
     extractVueStyles: true,
     globalVueStyles: 'resources/sass/_variables.scss',
   })
   .version();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been able to get this to work on just a basic vue application but I am having trouble bringing it across to laravel vue. I was able to add module in vue.config.js in the vue application that would import any scss files i added. Using the same code in the laravel vue app in the webpack.mix.js file it is not compiling correctly. This is my webpack.mis.js file:

let mix = require('laravel-mix');

module.exports = {
    css: {
        loaderOptions: {
            sass: {
                data: `@import "./resources/assets/sass/variables.scss";`
            }
        }
    }
};

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

I have also attempted the other configurations suggested from the docs but I haven't succeeded. I have also seen a lot of answers suggesting to just include the relative path to the files I wish to include in every component but this is inefficient and error prone as the application develops. There must be a way to achieve this and I have just got the configuration incorrect.

Any advice is appreciated, thanks.

Body:
Laravel Mix has an option exactly for this. It's globalVueStyles.

Check out the documentation: https://github.com/JeffreyWay/laravel-mix/blob/master/docs/options.md.

It will only work with extractVueStyles active:

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .options({
     extractVueStyles: true,
     globalVueStyles: 'resources/sass/_variables.scss',
   })
   .version();


问:
How to stop programme from reading if -1 is entered, and calculate average accordingly
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

```<code>int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);
</code>```

答:
The warning part of your code does not work correctly. The while looks completely misplaced and an if would have made sense instead of the while. In order to count actual number of inputs given, another counter would be preferred.

```<code>int n = 0; // Will count the actual number of inputs provided
for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);

    while (ages[i]<-2 || ages[i]>150){
        // This will loop until a valid number is entered
        // The logic here is subtle as age[i], which is checked by the while loop,
        // is changed on every iteration of the warning
        printf("Invalid number, enter again: ");
        scanf("%d",&ages[i]);
    }

    if (ages[i] == -1) {
        break;
    }

    n += 1;
}
</code>```

Use the n to calculate the average instead of 10. Moreover, while calculating the sum and the minimum, limit the index range i.e

Change

```<code>for (int i = 0; i < 10; i++)
</code>```

to

```<code>for (int i = 0; i < n; i++)
</code>```

Body:
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);

Body:
The warning part of your code does not work correctly. The while looks completely misplaced and an if would have made sense instead of the while. In order to count actual number of inputs given, another counter would be preferred.

int n = 0; // Will count the actual number of inputs provided
for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);

    while (ages[i]<-2 || ages[i]>150){
        // This will loop until a valid number is entered
        // The logic here is subtle as age[i], which is checked by the while loop,
        // is changed on every iteration of the warning
        printf("Invalid number, enter again: ");
        scanf("%d",&ages[i]);
    }

    if (ages[i] == -1) {
        break;
    }

    n += 1;
}

Use the n to calculate the average instead of 10. Moreover, while calculating the sum and the minimum, limit the index range i.e

Change

for (int i = 0; i < 10; i++)

to

for (int i = 0; i < n; i++)


问:
Ive got a problem with updating my ComboBox, as soon as I recall the fill ComboBox I get all duplicates
Im trying to update my ComboBox as soon as ive made a new Capture file with data in it. If I close the form and reopen it, its obviously updated but that seems like a cheap way to program it. (To quickly close the form and open a new one) So far when i recall the method to refill the ComboBox it seems to include existing data and hardcopies everything.

My code as for now:

As soon as the form load this is executed:

```<code>    private void FormCapSave_Load(object sender, EventArgs e)
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
</code>```

Followed by the button to add a new Cap file:

```<code>    private void buttonFormSaveAdd_Click(object sender, EventArgs e)
    {
        Form1.AfterNamingCapFile();
        if (Program.MainForm.boolSave == false)
        {
            labelFormSaveException.ForeColor = Color.Tomato;
            labelFormSaveException.Text = "Cap exists";
        }
        else
        {
            labelFormSaveException.ForeColor = Color.Green;
            labelFormSaveException.Text = "Cap file added";
            ResetForm();
        }
    }
</code>```

My ResetForm(); is basically a copy from the first on load method:

```<code>    private void ResetForm()
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
    }
</code>```

答:
You should clear the Items collection, but you can also remove the whole loop required to add items one by one if you use the DataSource property. This has the side advantage to allow you to get back a full FileInfo when you look at the SelectedItem property</p>

```<code>private void ResetForm()
{
    string path = @"C:\Users\pc\Documents\textfolder";
    comboBoxSaveCap.DataSource = null; // Clear the previous content
    comboBoxSaveCap.DataSource = new DirectoryInfo(path).GetFiles("*.cap");
}

void comboBoxSaveCap_SelectedIndexChanged(object sender, EventArgs e)
{
    var f = comboBoxSaveCap.SelectedItem as FileInfo;
    if(f != null)
    {
        Console.WriteLine(f.FullName);
    }
}
</code>```

Body:
Im trying to update my ComboBox as soon as ive made a new Capture file with data in it. If I close the form and reopen it, its obviously updated but that seems like a cheap way to program it. (To quickly close the form and open a new one) So far when i recall the method to refill the ComboBox it seems to include existing data and hardcopies everything.

My code as for now:

As soon as the form load this is executed:

    private void FormCapSave_Load(object sender, EventArgs e)
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }

Followed by the button to add a new Cap file:

    private void buttonFormSaveAdd_Click(object sender, EventArgs e)
    {
        Form1.AfterNamingCapFile();
        if (Program.MainForm.boolSave == false)
        {
            labelFormSaveException.ForeColor = Color.Tomato;
            labelFormSaveException.Text = "Cap exists";
        }
        else
        {
            labelFormSaveException.ForeColor = Color.Green;
            labelFormSaveException.Text = "Cap file added";
            ResetForm();
        }
    }

My ResetForm(); is basically a copy from the first on load method:

    private void ResetForm()
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
    }

Body:
You should clear the Items collection, but you can also remove the whole loop required to add items one by one if you use the DataSource property. This has the side advantage to allow you to get back a full FileInfo when you look at the SelectedItem property

private void ResetForm()
{
    string path = @"C:\Users\pc\Documents\textfolder";
    comboBoxSaveCap.DataSource = null; // Clear the previous content
    comboBoxSaveCap.DataSource = new DirectoryInfo(path).GetFiles("*.cap");
}

void comboBoxSaveCap_SelectedIndexChanged(object sender, EventArgs e)
{
    var f = comboBoxSaveCap.SelectedItem as FileInfo;
    if(f != null)
    {
        Console.WriteLine(f.FullName);
    }
}


问:
Strange behavior of GridSplitter

can say that I am a beginner in WPF.

I have a strange behavior of GridSplitter; the grid is divided into 5 roww.

tabbar

horizontal grid

splitter

another tabbar

a textbox (txtLog)

like code below, but when I moving the separator the txtLog moves down instead of following the previous tabbar.

XAML:

```<code><Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MSCSimulator"
    mc:Ignorable="d"
    FontSize="14"
    Title="Simulator"
    Height="500" Width="800"
    WindowStartupLocation="CenterScreen"
    WindowStyle="ThreeDBorderWindow">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" MinHeight="50" />
        <RowDefinition Height="*" MinHeight="120" />
        <RowDefinition Height="10" />
        <RowDefinition Height="50" MinHeight="50" />
        <RowDefinition Height="*" MinHeight="120" />
    </Grid.RowDefinitions>
    <!-- TOOLBAR -->
    <ToolBarTray Margin="10,10,10,10" Width="Auto" Height="30">
        <ToolBar Width="Auto" Height="30">
            <Button Click="Send_Click">
                <StackPanel Orientation="Horizontal">
                    <Image Source="/Simulator;component/Images/play.png" Width="12" Height="12" />
                    <Label Padding="5,0,0,0">Invia</Label>
                </StackPanel>
            </Button>
        </ToolBar>
    </ToolBarTray>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="220" MinWidth="150" MaxWidth="220" />
            <ColumnDefinition Width="10" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TreeView Width="Auto" Margin="10,0,0,0">
            <TreeViewItem Header="Commands" IsExpanded="True">
                <!-- APPLICATION -->
                <TreeViewItem Header="Application">
                    <TreeViewItem Header="Simulate" MouseDoubleClick="Application_Simulate_MouseDoubleClick" />
                    <TreeViewItem Header="Update" MouseDoubleClick="Application_Update_MouseDoubleClick" />
                </TreeViewItem>
            </TreeViewItem>
            <TreeView.Resources>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="FontWeight" Value="Bold"/>
                        </Trigger>
                        <Trigger Property="IsSelected" Value="False">
                            <Setter Property="FontWeight" Value="Normal"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TreeView.Resources>
        </TreeView>
        <GridSplitter Width="10"
                      Background="White"
                      VerticalAlignment="Stretch"
                      ResizeBehavior="BasedOnAlignment" />
        <!-- JSON -->
        <TextBox Name="txtJSON"
                 Grid.Column="2"
                 Background="White"
                 TextWrapping="Wrap"
                 AcceptsReturn="True"
                 Margin="-10,0,10,0"
                 VerticalScrollBarVisibility="Visible"
                 Width="Auto" Height="Auto" />
    </Grid>
    <GridSplitter Grid.Row="2"
                  Height="10"
                  ResizeDirection="Rows"
                  HorizontalAlignment="Stretch"
                  ResizeBehavior="PreviousAndNext"
                  Background="White"/>
    <!-- TOOLBAR -->
    <ToolBarTray Grid.Row="3" Margin="10,0,10,0" Width="Auto" Height="30" VerticalAlignment="Top">
        <ToolBar Width="Auto" Height="30">
            <Button Click="Clear_Click">
                <StackPanel Orientation="Horizontal">
                    <Image Source="/Simulator;component/Images/clear.png" Width="16" Height="16" />
                    <Label Padding="5,0,0,0">Cancella</Label>
                </StackPanel>
            </Button>
        </ToolBar>
    </ToolBarTray>
    <!-- LOGGER-->
    <TextBox Name="txtLog"
             Grid.Row="4"
             TextWrapping="Wrap"
             Margin="10,-10,10,10"
             AcceptsReturn="True"
             VerticalScrollBarVisibility="Auto"
             Width="Auto" Height="Auto"
             IsReadOnly="True">
        <TextBox.Background>
            <SolidColorBrush Color="#282828"></SolidColorBrush>
        </TextBox.Background>
        <TextBox.Foreground>
            <SolidColorBrush Color="White"></SolidColorBrush>
        </TextBox.Foreground>
    </TextBox>
</Grid>
</code>```

thanks advance

答:
In your outer Grid, try to put the Height from * to Auto in the second RowDefinition</p>

```<code>...
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" MinHeight="50" />
        <RowDefinition Height="Auto" MinHeight="120" />
        <RowDefinition Height="10" />
        <RowDefinition Height="50" MinHeight="50"/>
        <RowDefinition Height="*" MinHeight="120" />
    </Grid.RowDefinitions>
    <!-- TOOLBAR -->
...
</code>```

Title: Strange behavior of GridSplitter

Body:
can say that I am a beginner in WPF.

I have a strange behavior of GridSplitter; the grid is divided into 5 roww.

tabbar

horizontal grid

splitter

another tabbar

a textbox (txtLog)

like code below, but when I moving the separator the txtLog moves down instead of following the previous tabbar.

XAML:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MSCSimulator"
    mc:Ignorable="d"
    FontSize="14"
    Title="Simulator"
    Height="500" Width="800"
    WindowStartupLocation="CenterScreen"
    WindowStyle="ThreeDBorderWindow">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" MinHeight="50" />
        <RowDefinition Height="*" MinHeight="120" />
        <RowDefinition Height="10" />
        <RowDefinition Height="50" MinHeight="50" />
        <RowDefinition Height="*" MinHeight="120" />
    </Grid.RowDefinitions>

    <ToolBarTray Margin="10,10,10,10" Width="Auto" Height="30">
        <ToolBar Width="Auto" Height="30">
            <Button Click="Send_Click">
                <StackPanel Orientation="Horizontal">
                    <Image Source="/Simulator;component/Images/play.png" Width="12" Height="12" />
                    Invia
                </StackPanel>
            </Button>
        </ToolBar>
    </ToolBarTray>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="220" MinWidth="150" MaxWidth="220" />
            <ColumnDefinition Width="10" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TreeView Width="Auto" Margin="10,0,0,0">
            <TreeViewItem Header="Commands" IsExpanded="True">

                <TreeViewItem Header="Application">
                    <TreeViewItem Header="Simulate" MouseDoubleClick="Application_Simulate_MouseDoubleClick" />
                    <TreeViewItem Header="Update" MouseDoubleClick="Application_Update_MouseDoubleClick" />
                </TreeViewItem>
            </TreeViewItem>
            <TreeView.Resources>

                </Style>
            </TreeView.Resources>
        </TreeView>
        <GridSplitter Width="10"
                      Background="White"
                      VerticalAlignment="Stretch"
                      ResizeBehavior="BasedOnAlignment" />

        <TextBox Name="txtJSON"
                 Grid.Column="2"
                 Background="White"
                 TextWrapping="Wrap"
                 AcceptsReturn="True"
                 Margin="-10,0,10,0"
                 VerticalScrollBarVisibility="Visible"
                 Width="Auto" Height="Auto" />
    </Grid>
    <GridSplitter Grid.Row="2"
                  Height="10"
                  ResizeDirection="Rows"
                  HorizontalAlignment="Stretch"
                  ResizeBehavior="PreviousAndNext"
                  Background="White"/>

    <ToolBarTray Grid.Row="3" Margin="10,0,10,0" Width="Auto" Height="30" VerticalAlignment="Top">
        <ToolBar Width="Auto" Height="30">
            <Button Click="Clear_Click">
                <StackPanel Orientation="Horizontal">
                    <Image Source="/Simulator;component/Images/clear.png" Width="16" Height="16" />
                    Cancella
                </StackPanel>
            </Button>
        </ToolBar>
    </ToolBarTray>

    <TextBox Name="txtLog"
             Grid.Row="4"
             TextWrapping="Wrap"
             Margin="10,-10,10,10"
             AcceptsReturn="True"
             VerticalScrollBarVisibility="Auto"
             Width="Auto" Height="Auto"
             IsReadOnly="True">
        <TextBox.Background>
            <SolidColorBrush Color="#282828"></SolidColorBrush>
        </TextBox.Background>
        <TextBox.Foreground>
            <SolidColorBrush Color="White"></SolidColorBrush>
        </TextBox.Foreground>
    </TextBox>
</Grid>

thanks advance

Body:
In your outer Grid, try to put the Height from * to Auto in the second RowDefinition

...
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" MinHeight="50" />
        <RowDefinition Height="Auto" MinHeight="120" />
        <RowDefinition Height="10" />
        <RowDefinition Height="50" MinHeight="50"/>
        <RowDefinition Height="*" MinHeight="120" />
    </Grid.RowDefinitions>
    <!-- TOOLBAR -->
...


问:
Why am I not able to use promise in my basic react app?
I am fairly new to react and I was experimenting on axios get requests . So What I am trying to do is that I have a json file in my public folder and I am making a get axios request to the location of that file and then I am printing the result in an array .

The first method worked pretty smoothly . A demo of the function is given below

The output is given below:

And as evident , this approach worked pretty fine.

However I also made a class named Fetch inside a service.js file . This class had a method named fetch which used axios to make a get request.

The demo of this class is given below:

import React from 'react';
import axios from "axios";

class Fetch extends React.Component
{
    constructor()
    {
        super();
    }
    fetch()
    {
        console.log("Hi i am in fetch of service....");
        axios.get('./config.json').then(response=>{
            var x=response.data;
            console.log("----------------------------------------->"+JSON.stringify(x));

            return x;
        },(err)=>{
            return err;

        })

    }
}

export default Fetch;```

I imported this class in another js file and made an object of this class to call the fetch method.A demo of my usage is given below:

However when I tried to do this , I got the following error:

What am I doing wrong ? If it worked for the first time , then why is this not working now?

答:
You are receiving that error because nothing is returned from Fetch.fetch(), let alone a promise.

You are trying to call .then() on a void function, so you will not be able to access the response.

In your Fetch class, return the axios request from the fetch() function:

fetch() {
    return axios.get('/config.json').then(response => {
        // your code
    })
}
```

Body:
I am fairly new to react and I was experimenting on axios get requests . So What I am trying to do is that I have a json file in my public folder and I am making a get axios request to the location of that file and then I am printing the result in an array .

The first method worked pretty smoothly . A demo of the function is given below

The output is given below:

And as evident , this approach worked pretty fine.

However I also made a class named Fetch inside a service.js file . This class had a method named fetch which used axios to make a get request.

The demo of this class is given below:

import React from 'react';
import axios from "axios";

class Fetch extends React.Component
{
    constructor()
    {
        super();
    }
    fetch()
    {
        console.log("Hi i am in fetch of service....");
        axios.get('./config.json').then(response=>{
            var x=response.data;
            console.log("----------------------------------------->"+JSON.stringify(x));

            return x;
        },(err)=>{
            return err;

        })

    }
}

export default Fetch;

I imported this class in another js file and made an object of this class to call the fetch method.A demo of my usage is given below:

However when I tried to do this , I got the following error:

What am I doing wrong ? If it worked for the first time , then why is this not working now?


问:
Update XML data for multiple nodes
I want to update the Isselected plan data based on the selected plan

```<code>            SET @DataXml.modify(' replace value of (/*/Plans/Plan[sql:variable("@PlanID")]/Details/IsSelected/text())[1] with sql:variable("IsSelectedValue")')
</code>```

but the above query always update the first one.

```<code><Plans>
        <Plan>
          <Details>
               <IsSelected>true</IsSelected>
         </Details>
        </plan>
        <Plan>
          <Details>
                 <IsSelected>false</IsSelected>
         </Details>
        </plan>
        <Plan>
          <Details>
                <IsSelected>false</IsSelected>
         </Details>
        </plan>
  </Plans>

if((SELECT count(Col.value('(Details)[1]', 'nvarchar(max)')) AS Selected FROM @DataXml.nodes('Options/Option') AS Tbl(Col)) > 1)
                                BEGIN

                                    SET @DataXml.modify(' replace value of (/*/Options/Option[sql:variable("@OptionID")]/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")')
                                END
                            ELSE
                            BEGIN

                                    SET @DataXml.modify(' replace value of (/*/Options/Option/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")')
                            END
</code>```

if I can get the node count like say for the above data It should return count 3 I can manage to fix this.

答:
This answer is probably to late... But it might still be helpfull...

I must admit, that I did not understand your issue completely. Try this out:

A mockup-XML

```<code>DECLARE @xml XML=
N'<Plans>
        <Plan>
          <Details>
               <IsSelected>true</IsSelected>
         </Details>
        </Plan>
        <Plan>
          <Details>
                 <IsSelected>false</IsSelected>
         </Details>
        </Plan>
        <Plan>
          <Details>
                <IsSelected>false</IsSelected>
         </Details>
        </Plan>
  </Plans>';
</code>```

--This query will answer your question

if I can get the node count like say for the above data It should return count 3 I can manage to fix this

```<code>SELECT @xml.value('count(/Plans/Plan)','int') AS CountOfPlans;
</code>```

--And this query will change the second <IsSelected> to a new value

```<code>DECLARE @position INT=2;
DECLARE @newValue VARCHAR(100)='blah';

SET @xml.modify('replace value of (/Plans/Plan[sql:variable("@position")]/Details/IsSelected/text())[1] with sql:variable("@newValue")');

SELECT @xml;
</code>```

The first returns a "3" and the second this XML

```<code><Plans>
  <Plan>
    <Details>
      <IsSelected>true</IsSelected>
    </Details>
  </Plan>
  <Plan>
    <Details>
      <IsSelected>blah</IsSelected>
    </Details>
  </Plan>
  <Plan>
    <Details>
      <IsSelected>false</IsSelected>
    </Details>
  </Plan>
</Plans>
</code>```

Title: Update XML data for multiple nodes

Body:
I want to update the Isselected plan data based on the selected plan

            SET @DataXml.modify(' replace value of (/*/Plans/Plan[sql:variable("@PlanID")]/Details/IsSelected/text())[1] with sql:variable("IsSelectedValue")')

but the above query always update the first one.

<Plans>
        <Plan>

               <IsSelected>true</IsSelected>

        </plan>
        <Plan>

                 <IsSelected>false</IsSelected>

        </plan>
        <Plan>

                <IsSelected>false</IsSelected>

        </plan>
  </Plans>

if((SELECT count(Col.value('(Details)[1]', 'nvarchar(max)')) AS Selected FROM @DataXml.nodes('Options/Option') AS Tbl(Col)) > 1)
                                BEGIN

                                    SET @DataXml.modify(' replace value of (/*/Options/Option[sql:variable("@OptionID")]/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")')
                                END
                            ELSE
                            BEGIN

                                    SET @DataXml.modify(' replace value of (/*/Options/Option/Details/IsSelectedValue/text())[1] with sql:variable("@IsSelectedValue")')
                            END

if I can get the node count like say for the above data It should return count 3 I can manage to fix this.

Body:
This answer is probably to late... But it might still be helpfull...

I must admit, that I did not understand your issue completely. Try this out:

A mockup-XML

DECLARE @xml XML=
N'<Plans>
        <Plan>
          <Details>
               <IsSelected>true</IsSelected>
         </Details>
        </Plan>
        <Plan>
          <Details>
                 <IsSelected>false</IsSelected>
         </Details>
        </Plan>
        <Plan>
          <Details>
                <IsSelected>false</IsSelected>
         </Details>
        </Plan>
  </Plans>';

--This query will answer your question

if I can get the node count like say for the above data It should return count 3 I can manage to fix this

SELECT @xml.value('count(/Plans/Plan)','int') AS CountOfPlans;

--And this query will change the second <IsSelected> to a new value

DECLARE @position INT=2;
DECLARE @newValue VARCHAR(100)='blah';

SET @xml.modify('replace value of (/Plans/Plan[sql:variable("@position")]/Details/IsSelected/text())[1] with sql:variable("@newValue")');

SELECT @xml;

The first returns a "3" and the second this XML

<Plans>
  <Plan>
    <Details>
      <IsSelected>true</IsSelected>
    </Details>
  </Plan>
  <Plan>
    <Details>
      <IsSelected>blah</IsSelected>
    </Details>
  </Plan>
  <Plan>
    <Details>
      <IsSelected>false</IsSelected>
    </Details>
  </Plan>
</Plans>


问:
Access Google Trends Data without a wrapper, or with the API: Python
I am trying to write a Python program to gather data from Google Trends (GT)- specifically, I want to automatically open URLs and access the specific values that are displayed in the line graphs:

I would be happy with downloading the CSV files, or with web-scraping the values (based on my reading of Inspect Element, cleaning the data would only require a simple split or two). I have many searches I want to conduct (many different keywords)

I am creating many URLs to gather data from Google Trends. I used the actual URL from a test search. Example of a URL: https://trends.google.com/trends/explore?q=sports%20cars&geo=US
Physically searching this URL on a browser shows the relevant GT page. The problem comes when I try to access it through a program.

Most responses I have seen suggest using public modules from Pip (e.g. PyTrends and the "Unofficial Google Trends API")- my project manager has insisted I do not use modules that are not directly created by the site (i.e.: APIs are acceptable but only an official Google API). Only BeautifulSoup has been sanctioned as a plugin (don't ask why).

Below is an example of the code I have tried. I know it is basic, but on the very first request I got:

HTTPError: HTTP Error 429: unknown": too many requests.

Some responses to other questions mention Google Trends API - is this real? I could not find any documentation on an official API.

Here is another post which outlined a solution that I have tried that did not work for me:

https://codereview.stackexchange.com/questions/208277/web-scraping-google-trends-in-python

```<code>url = 'https://trends.google.com/trends/explore?q=sports%20cars&geo=US'

html = urlopen(url).read()

soup = bs(html, 'html.parser')

divs = soup.find_all('div')

return divs
</code>```

答:
It's using an API you can find in the network tab

```<code>import requests
import json

r = requests.get('https://trends.google.com/trends/api/widgetdata/multiline?hl=en-GB&tz=-60&req=%7B%22time%22:%222018-05-29+2019-05-29%22,%22resolution%22:%22WEEK%22,%22locale%22:%22en-GB%22,%22comparisonItem%22:%5B%7B%22geo%22:%7B%22country%22:%22US%22%7D,%22complexKeywordsRestriction%22:%7B%22keyword%22:%5B%7B%22type%22:%22BROAD%22,%22value%22:%22sports+cars%22%7D%5D%7D%7D%5D,%22requestOptions%22:%7B%22property%22:%22%22,%22backend%22:%22IZG%22,%22category%22:0%7D%7D&token=APP6_UEAAAAAXO-yaYekqJ7Tf2nuoLBAigMSW7axoLTL&tz=-60')
data = json.loads(r.text.lstrip(")]}\',\n"))

for item in data['default']['timelineData']:
    print(item['formattedAxisTime'], item['value'])
</code>```

We can unquote the url to have a better idea of what is going on:

```<code>import urllib.parse

url = 'https://trends.google.com/trends/api/widgetdata/multiline?hl=en-GB&tz=-60&req=%7B%22time%22:%222018-05-29+2019-05-29%22,%22resolution%22:%22WEEK%22,%22locale%22:%22en-GB%22,%22comparisonItem%22:%5B%7B%22geo%22:%7B%22country%22:%22US%22%7D,%22complexKeywordsRestriction%22:%7B%22keyword%22:%5B%7B%22type%22:%22BROAD%22,%22value%22:%22sports+cars%22%7D%5D%7D%7D%5D,%22requestOptions%22:%7B%22property%22:%22%22,%22backend%22:%22IZG%22,%22category%22:0%7D%7D&token=APP6_UEAAAAAXO-yaYekqJ7Tf2nuoLBAigMSW7axoLTL&tz=-60'
print(urllib.parse.unquote(url))
</code>```

This yields:

```<code>'https://trends.google.com/trends/api/widgetdata/multiline?hl=en-GB&tz=-60&req={"time":"2018-05-29+2019-05-29","resolution":"WEEK","locale":"en-GB","comparisonItem":[{"geo":{"country":"US"},"complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"sports+cars"}]}}],"requestOptions":{"property":"","backend":"IZG","category":0}}&token=APP6_UEAAAAAXO-yaYekqJ7Tf2nuoLBAigMSW7axoLTL&tz=-60'
</code>```

You'll need to explore how transferable elements from this are.

For example,  I looked at search term banana and this was the result:

unquoted:

```<code>'https://trends.google.com/trends/api/explore?hl=en-GB&tz=-60&req={"comparisonItem":[{"keyword":"banana","geo":"US","time":"today+12-m"}],"category":0,"property":""}&tz=-60'
</code>```

quoted:

```<code>'https://trends.google.com/trends/api/explore?hl=en-GB&tz=-60&req=%7B%22comparisonItem%22:%5B%7B%22keyword%22:%22banana%22,%22geo%22:%22US%22,%22time%22:%22today+12-m%22%7D%5D,%22category%22:0,%22property%22:%22%22%7D&tz=-60'
</code>```

Body:
I am trying to write a Python program to gather data from Google Trends (GT)- specifically, I want to automatically open URLs and access the specific values that are displayed in the line graphs:

I would be happy with downloading the CSV files, or with web-scraping the values (based on my reading of Inspect Element, cleaning the data would only require a simple split or two). I have many searches I want to conduct (many different keywords)

I am creating many URLs to gather data from Google Trends. I used the actual URL from a test search. Example of a URL: https://trends.google.com/trends/explore?q=sports%20cars&geo=US
Physically searching this URL on a browser shows the relevant GT page. The problem comes when I try to access it through a program.

Most responses I have seen suggest using public modules from Pip (e.g. PyTrends and the "Unofficial Google Trends API")- my project manager has insisted I do not use modules that are not directly created by the site (i.e.: APIs are acceptable but only an official Google API). Only BeautifulSoup has been sanctioned as a plugin (don't ask why).

Below is an example of the code I have tried. I know it is basic, but on the very first request I got:

HTTPError: HTTP Error 429: unknown": too many requests.

Some responses to other questions mention Google Trends API - is this real? I could not find any documentation on an official API.

Here is another post which outlined a solution that I have tried that did not work for me:

https://codereview.stackexchange.com/questions/208277/web-scraping-google-trends-in-python

url = 'https://trends.google.com/trends/explore?q=sports%20cars&geo=US'

html = urlopen(url).read()

soup = bs(html, 'html.parser')

divs = soup.find_all('div')

return divs

Body:
It's using an API you can find in the network tab

import requests
import json

r = requests.get('https://trends.google.com/trends/api/widgetdata/multiline?hl=en-GB&tz=-60&req=%7B%22time%22:%222018-05-29+2019-05-29%22,%22resolution%22:%22WEEK%22,%22locale%22:%22en-GB%22,%22comparisonItem%22:%5B%7B%22geo%22:%7B%22country%22:%22US%22%7D,%22complexKeywordsRestriction%22:%7B%22keyword%22:%5B%7B%22type%22:%22BROAD%22,%22value%22:%22sports+cars%22%7D%5D%7D%7D%5D,%22requestOptions%22:%7B%22property%22:%22%22,%22backend%22:%22IZG%22,%22category%22:0%7D%7D&token=APP6_UEAAAAAXO-yaYekqJ7Tf2nuoLBAigMSW7axoLTL&tz=-60')
data = json.loads(r.text.lstrip(")]}\',\n"))

for item in data['default']['timelineData']:
    print(item['formattedAxisTime'], item['value'])

We can unquote the url to have a better idea of what is going on:

import urllib.parse

url = 'https://trends.google.com/trends/api/widgetdata/multiline?hl=en-GB&tz=-60&req=%7B%22time%22:%222018-05-29+2019-05-29%22,%22resolution%22:%22WEEK%22,%22locale%22:%22en-GB%22,%22comparisonItem%22:%5B%7B%22geo%22:%7B%22country%22:%22US%22%7D,%22complexKeywordsRestriction%22:%7B%22keyword%22:%5B%7B%22type%22:%22BROAD%22,%22value%22:%22sports+cars%22%7D%5D%7D%7D%5D,%22requestOptions%22:%7B%22property%22:%22%22,%22backend%22:%22IZG%22,%22category%22:0%7D%7D&token=APP6_UEAAAAAXO-yaYekqJ7Tf2nuoLBAigMSW7axoLTL&tz=-60'
print(urllib.parse.unquote(url))

This yields:

'https://trends.google.com/trends/api/widgetdata/multiline?hl=en-GB&tz=-60&req={"time":"2018-05-29+2019-05-29","resolution":"WEEK","locale":"en-GB","comparisonItem":[{"geo":{"country":"US"},"complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"sports+cars"}]}}],"requestOptions":{"property":"","backend":"IZG","category":0}}&token=APP6_UEAAAAAXO-yaYekqJ7Tf2nuoLBAigMSW7axoLTL&tz=-60'

You'll need to explore how transferable elements from this are.

For example,  I looked at search term banana and this was the result:

unquoted:

'https://trends.google.com/trends/api/explore?hl=en-GB&tz=-60&req={"comparisonItem":[{"keyword":"banana","geo":"US","time":"today+12-m"}],"category":0,"property":""}&tz=-60'

quoted:

'https://trends.google.com/trends/api/explore?hl=en-GB&tz=-60&req=%7B%22comparisonItem%22:%5B%7B%22keyword%22:%22banana%22,%22geo%22:%22US%22,%22time%22:%22today+12-m%22%7D%5D,%22category%22:0,%22property%22:%22%22%7D&tz=-60'


问:
Use Of patchValue in Reactive Forms with parent child routing
I have a form with parent child routing .Once user has saved info ,the code will save that data to some db. On my home page ; I will be getting data from db in the grid form and on clicking EDIT ,my form should route user to edit the already saved form-data and update it. I have created home-page and respective routes . On clicking edit my code is navigating me to my form component but getting error on clicking child component (as I have not provided route for the same). Can some help me achieve this?

I want, once user clicked on edit it should directly route user to person-info with pre-filled data and if he wishes to go to person-job ; he should be able to see data in job as well.

Existing Stackblitz

答:
you can do this if you want info & job route under edit too,</p>

```<code>const routes: Routes = [
  {path: 'home' , component:HomePageComponent},
  {
    path: 'edit/:age' , component: PersonFormComponent,
    children: [
      { path: 'info', component: PersonInfoComponent },
      { path: 'job', component: PersonJobComponent }]
  },
  {
    path: 'person',
    component: PersonFormComponent,
    children: [
      { path: 'info', component: PersonInfoComponent },
      { path: 'job', component: PersonJobComponent }]
  },
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];
</code>```

Body:
you can do this if you want info & job route under edit too,

const routes: Routes = [
  {path: 'home' , component:HomePageComponent},
  {
    path: 'edit/:age' , component: PersonFormComponent,
    children: [
      { path: 'info', component: PersonInfoComponent },
      { path: 'job', component: PersonJobComponent }]
  },
  {
    path: 'person',
    component: PersonFormComponent,
    children: [
      { path: 'info', component: PersonInfoComponent },
      { path: 'job', component: PersonJobComponent }]
  },
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];


问:
How to fix web components not showing in Microsoft Edge
I'm trying out lit-element and everything was going well with browsers such as Chrome and Firefox. But I faced a problem when I tried Microsoft Edge and IE11. The web component that shows in Chrome and Firefox doesn't show in Microsoft Edge and IE11.

I did some search on the internet and also read the documentation of Lit Element and it says I will need to load the polyfills in order for the web components to work in Edge and IE11, however I have encountered problems while trying to do so.

The code that I'm using to load my polyfills are as follow,

```<code><script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js"></script>
  <script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-loader.js"></script>

<script type="module">
  window.WebComponents = window.WebComponents || {
    waitFor(cb){ addEventListener('WebComponentReady', cb) }
  }
  WebComponents.waitFor(async () => {
    import('mypath/somecomponent.js');
  });
</script>
</code>```

I used the developer tools in Microsoft Edge and the following are showing.

SCRIPT5022: SCRIPT5022: Syntax error

When i click into the debugger it also shows the following message

Could not locate https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/ [synthetic:util/global] specified in source map https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js.map.

Any help will be greatly appreciated!!

答:
You need either webcomponents-bundle.js or webcomponents-loader.js but not both. Also, since you are targetting IE11, you will need module bundler like Webpack to use features like async functions, ES imports.

To solve your problem without using async and imports, all you need is:

```<code><script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js"></script>
<script src="mypath/somecomponent.js"></script>
</code>```

Add these scripts to your HTML page and it should work. Again, if you wish to use async and imports then you will need appropriate polyfills and bundler to package the code.

Body:
I'm trying out lit-element and everything was going well with browsers such as Chrome and Firefox. But I faced a problem when I tried Microsoft Edge and IE11. The web component that shows in Chrome and Firefox doesn't show in Microsoft Edge and IE11.

I did some search on the internet and also read the documentation of Lit Element and it says I will need to load the polyfills in order for the web components to work in Edge and IE11, however I have encountered problems while trying to do so.

The code that I'm using to load my polyfills are as follow,

I used the developer tools in Microsoft Edge and the following are showing.

SCRIPT5022: SCRIPT5022: Syntax error

When i click into the debugger it also shows the following message

Could not locate https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/ [synthetic:util/global] specified in source map https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js.map.

Any help will be greatly appreciated!!

Body:
You need either webcomponents-bundle.js or webcomponents-loader.js but not both. Also, since you are targetting IE11, you will need module bundler like Webpack to use features like async functions, ES imports.

To solve your problem without using async and imports, all you need is:

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js"></script>
<script src="mypath/somecomponent.js"></script>

Add these scripts to your HTML page and it should work. Again, if you wish to use async and imports then you will need appropriate polyfills and bundler to package the code.


问:
TYPO3 - Howto restrict all pages by frontend user login but the login page itself
I would like to restrict all pages of a website by the frontend user login. Therefor I would like to add "Show at any login" in the page settings of the root page and tick the checkbox "Extend to Subpages". So all pages are only accessible, if the user is logged in.

But:
How can I show the login form now? Are there beste practices?

First idea for the page tree:

```<code>- root page (with login form)
  - Home page <-- Password protection starts here and cascades down to all subpages
    - Subpage
    - more pages...
</code>```

But how can I redirect to the homepage, if the user is already logged in?

答:
I did not restrict the pages itself, but added the following typoscript:

```<code>// redirect to login page
[loginUser = ] && [globalVar = TSFE:id != {$loginPage}]
    config.additionalHeaders.10 {
        header = Location: /index.php?id={$loginPage}
    }
[global]
</code>```

This typoscript checks, whether a frontend user is logged in and is not on the login page. If the user is not logged in and not on the login page, it will redirect to the login page.

Body:
I would like to restrict all pages of a website by the frontend user login. Therefor I would like to add "Show at any login" in the page settings of the root page and tick the checkbox "Extend to Subpages". So all pages are only accessible, if the user is logged in.

But:
How can I show the login form now? Are there beste practices?

First idea for the page tree:

- root page (with login form)
  - Home page <-- Password protection starts here and cascades down to all subpages
    - Subpage
    - more pages...

But how can I redirect to the homepage, if the user is already logged in?

Body:
I did not restrict the pages itself, but added the following typoscript:

// redirect to login page
[loginUser = ] && [globalVar = TSFE:id != {$loginPage}]
    config.additionalHeaders.10 {
        header = Location: /index.php?id={$loginPage}
    }
[global]

This typoscript checks, whether a frontend user is logged in and is not on the login page. If the user is not logged in and not on the login page, it will redirect to the login page.


问:
Why cant I use power on functions?
I wrote this code:

```<code>t=linspace(0,pi)
x = @(t)sin(t)
</code>```

then i tried this->

```<code>x = power(x,2)
</code>```

but it gives me an error, how can i use the power function on a function then?

答:
You can't.

You can however use the power function on the output of a function.

```<code>x = @(t)sin(t); %this is an anonymous function

t=linspace(0,pi); % this is an array

x2 = power(x(t),2); % this is an array
</code>```

Alternatively, you can create a second function that calls the first function

```<code>x2=@(t)power(x(t),2); % this is  an anonymous function
</code>```

Title: Why cant I use power on functions?

Body:
I wrote this code:

t=linspace(0,pi)
x = @(t)sin(t)

then i tried this->

x = power(x,2)

but it gives me an error, how can i use the power function on a function then?

Body:
You can't.

You can however use the power function on the output of a function.

x = @(t)sin(t); %this is an anonymous function

t=linspace(0,pi); % this is an array

x2 = power(x(t),2); % this is an array

Alternatively, you can create a second function that calls the first function

x2=@(t)power(x(t),2); % this is  an anonymous function


问:
Send variable value from server to client
On the server I created a counter that calculates and displays time on the server (from 180 seconds to 0). The current number of seconds is stored in the variable time and displayed in jLabel (name seconds) on the server.

On the client side, there is also JLabel (name seconds) in which I would like to display the current second displayed on the server. Is there a way to send jLabel (name seconds) (server) to jLabel (name seconds) (client)?

 try{
        Thread.sleep(1000);
        if(i<120 && i>=60){
            int time=i%60;
            String sekundy=Integer.toString(time);
            minutes.setText("01");
            seconds.setText(sekundy);
       }
    }

void uruchom() throws Exception
    {
        Socket socket = s.accept();
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        while(true)
        {
            String przekazSekundy=seconds.getText();
            String przekazMinuty=minutes.getText();
            try
                {

                   //I try doing something like this

                    out.seconds.setText(przekazSekundy);
                }catch(Exception e) {
                    System.out.println("error");
                    socket.close();
                    return;
                }
        }

    }

```

答:
try something like this

for the serverside:

```<code>PrintWriter writer;
writer = new PrintWriter(socket.getOutputStream();
writer.println(przekazSekundy);
writer.flush();
</code>```

on clientside :

```<code>in = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String newstring = "";
message = "";
while(!(newstring = reader.readLine()).equals("")){
    message+=newstring;
    if(!reader.ready())
        break;
}
if(message != "")
   //set your client label text
</code>```

Body:
try something like this

for the serverside:

PrintWriter writer;
writer = new PrintWriter(socket.getOutputStream();
writer.println(przekazSekundy);
writer.flush();

on clientside :

in = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String newstring = "";
message = "";
while(!(newstring = reader.readLine()).equals("")){
    message+=newstring;
    if(!reader.ready())
        break;
}
if(message != "")
   //set your client label text


问:
Python watchdog for files from two different directories
I am trying to listen to filesystem changes using the watchdog module of Python. I want to monitor the files from two different directories. For a single file watch, I used PatternMatchingEventHandler from watchdog.events. I want to use the same for multiple directories.

code:

```<code>import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

class EventHandler(PatternMatchingEventHandler):
    def on_modified(self, event):
        super(EventHandler, self).on_modified(event)
        print event

if __name__ == "__main__":
    dir_name = ["/home/user1/first", "/home/user1/second"]
    observer = Observer()
    patterns = ["/home/user1/first/first.log","/home/user1/second/second.log")]
    for i in xrange(len(dir_name)):
        event_handler = EventHandler(patterns = patterns[i])
        observer.schedule(event_handler, dir_name[i], recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(0.1)
    except KeyboardInterrupt:
        observer.stop()
</code>```

In the above code, I tried to do multiple directory observing format and create an event handler for each of the files. It's not working for me. Is there anything that I am missing here?? What is the way to do this??

Thanks.

答:
some wrong in here

```<code>EventHandler(patterns = patterns[i])
</code>```

arg patterns is a type of list, so you can use like this

```<code>patterns = [["/home/user1/first/first.log"], ["/home/user1/second/second.log"]]
EventHandler(patterns = patterns[i])
</code>```

Body:
I am trying to listen to filesystem changes using the watchdog module of Python. I want to monitor the files from two different directories. For a single file watch, I used PatternMatchingEventHandler from watchdog.events. I want to use the same for multiple directories.

code:

import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

class EventHandler(PatternMatchingEventHandler):
    def on_modified(self, event):
        super(EventHandler, self).on_modified(event)
        print event

if __name__ == "__main__":
    dir_name = ["/home/user1/first", "/home/user1/second"]
    observer = Observer()
    patterns = ["/home/user1/first/first.log","/home/user1/second/second.log")]
    for i in xrange(len(dir_name)):
        event_handler = EventHandler(patterns = patterns[i])
        observer.schedule(event_handler, dir_name[i], recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(0.1)
    except KeyboardInterrupt:
        observer.stop()

In the above code, I tried to do multiple directory observing format and create an event handler for each of the files. It's not working for me. Is there anything that I am missing here?? What is the way to do this??

Thanks.

Body:
some wrong in here

EventHandler(patterns = patterns[i])

arg patterns is a type of list, so you can use like this

patterns = [["/home/user1/first/first.log"], ["/home/user1/second/second.log"]]
EventHandler(patterns = patterns[i])


问:
Crystal Reports show field grey when date is null
Our user wants a date field to display as highlighted or with a grey background when the date is null.  How would I do something like this?  (At the very least, I suspect I'll first have to convert it to a string.)</p>

```<code>Completed Date
12/15/2010
03/07/2011
          <-- make that a grey block
05/01/2010
</code>```

答:
I hope that you don't think this too hacky but you can do what you want by adding a Formula field and calling it something like NullCheck. Then put the code below in the NullCheck formula field so that it places an X whenever the date field is null.

```<code>If IsNull({DeleteMe.DateField}) Then
"X"
</code>```

Next put that field (NullCheck) on your page so that the box covers the date field exactly. Then use the Highlighting Expert to set the background and the font to the same color when the X appears in the field (see image below).

When done it should "highlight" all null dates fields as shown.

ContentLicense: CC BY-SA 2.5

Body:
Our user wants a date field to display as highlighted or with a grey background when the date is null.  How would I do something like this?  (At the very least, I suspect I'll first have to convert it to a string.)

Completed Date
12/15/2010
03/07/2011
          <-- make that a grey block
05/01/2010

Body:
I hope that you don't think this too hacky but you can do what you want by adding a Formula field and calling it something like NullCheck. Then put the code below in the NullCheck formula field so that it places an X whenever the date field is null.

If IsNull({DeleteMe.DateField}) Then
"X"

Next put that field (NullCheck) on your page so that the box covers the date field exactly. Then use the Highlighting Expert to set the background and the font to the same color when the X appears in the field (see image below).

When done it should "highlight" all null dates fields as shown.


问:
Apache-POI not saving excel workbook even after doing fileoutputstream.close()
I am trying to generate new excel files based on a common template. I am opening the template excel file, editing it and saving it in a new location. To write the file I am using FileOutputStream and i am closing the stream after writing to save it. The entire process works correctly, but the newly created excel file is not saved properly. My template file is of 35kb and my newly created excel file shows 30kb only. When I open the newly created excel file, I can see the data written, and I need to save it and close it to reflect the correct size of 36kb.

The new excels are required to be uploaded to an external application which shows "no data found" when directly uploading the 30kb, unsaved excel whereas the 36kb saved file successfully uploads the file.

I tried various different ways suggested on internet to do the same thing and none of them are generating proper excel files. I am using java 1.7 and apache-poi version 3.17.

Following is a sample of my code:-

```<code>public void createExcelFiles() throws ParseException, IOException {

    File file = new File(ExcelTemplatePath);
    FileInputStream fip = new FileInputStream(file);
    FileOutputStream fos = new FileOutputStream(excelOutputFile);

    XSSFWorkbook workbookOld = new XSSFWorkbook(fip);
    try (SXSSFWorkbook workbook = new SXSSFWorkbook(workbookOld, rowAccessWindowSize)) {

        if (makeLargeFiles) {
            SXSSFSheet sheet = (SXSSFSheet) workbook.getSheetAt(0);
            makeExcelFile.makeLargeFile(sheet);
            workbook.write(fos);
        } else {
            Sheet sheet = workbookOld.getSheetAt(0);
            makeExcelFile.makeNormalFile(sheet);
            workbookOld.write(fos);

        }
        fos.close();
        fip.close();
        workbook.close();
    }
    workbookOld.close();

}
</code>```

答:
Wrapped I/O streams like XSSFWorkbook should close first, possibly still writing an epilogue to the wrapped OutputStream. And the the low-level stream may be closed.

Mind, that some wrapping classes will close the wrapped stream themselves inside their own close.

As try-with-resources is ideal, to also close in case of an exception, the final version would be:

```<code>public void createExcelFiles() throws ParseException, IOException {
    File file = new File(ExcelTemplatePath);
    try (FileInputStream fip = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(excelOutputFile);
            XSSFWorkbook workbookOld = new XSSFWorkbook(fip);
            SXSSFWorkbook workbook = new SXSSFWorkbook(workbookOld, rowAccessWindowSize)) {

        if (makeLargeFiles) {
            SXSSFSheet sheet = (SXSSFSheet) workbook.getSheetAt(0);
            makeExcelFile.makeLargeFile(sheet);
            workbook.write(fos);
        } else {
            Sheet sheet = workbookOld.getSheetAt(0);
            makeExcelFile.makeNormalFile(sheet);
            workbookOld.write(fos);

        }
    }
    // Doing in reverse order of declaration:
    // 1. workbook.close();
    // 2. workbookOld.close();
    // 3. fos.close();
    // 4. fip.close();
}
</code>```

In your code there was a reversal, and close happened explicit and via try-with-resources.

Body:
I am trying to generate new excel files based on a common template. I am opening the template excel file, editing it and saving it in a new location. To write the file I am using FileOutputStream and i am closing the stream after writing to save it. The entire process works correctly, but the newly created excel file is not saved properly. My template file is of 35kb and my newly created excel file shows 30kb only. When I open the newly created excel file, I can see the data written, and I need to save it and close it to reflect the correct size of 36kb.

The new excels are required to be uploaded to an external application which shows "no data found" when directly uploading the 30kb, unsaved excel whereas the 36kb saved file successfully uploads the file.

I tried various different ways suggested on internet to do the same thing and none of them are generating proper excel files. I am using java 1.7 and apache-poi version 3.17.

Following is a sample of my code:-

public void createExcelFiles() throws ParseException, IOException {

    File file = new File(ExcelTemplatePath);
    FileInputStream fip = new FileInputStream(file);
    FileOutputStream fos = new FileOutputStream(excelOutputFile);

    XSSFWorkbook workbookOld = new XSSFWorkbook(fip);
    try (SXSSFWorkbook workbook = new SXSSFWorkbook(workbookOld, rowAccessWindowSize)) {

        if (makeLargeFiles) {
            SXSSFSheet sheet = (SXSSFSheet) workbook.getSheetAt(0);
            makeExcelFile.makeLargeFile(sheet);
            workbook.write(fos);
        } else {
            Sheet sheet = workbookOld.getSheetAt(0);
            makeExcelFile.makeNormalFile(sheet);
            workbookOld.write(fos);

        }
        fos.close();
        fip.close();
        workbook.close();
    }
    workbookOld.close();

}

Body:
Wrapped I/O streams like XSSFWorkbook should close first, possibly still writing an epilogue to the wrapped OutputStream. And the the low-level stream may be closed.

Mind, that some wrapping classes will close the wrapped stream themselves inside their own close.

As try-with-resources is ideal, to also close in case of an exception, the final version would be:

public void createExcelFiles() throws ParseException, IOException {
    File file = new File(ExcelTemplatePath);
    try (FileInputStream fip = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(excelOutputFile);
            XSSFWorkbook workbookOld = new XSSFWorkbook(fip);
            SXSSFWorkbook workbook = new SXSSFWorkbook(workbookOld, rowAccessWindowSize)) {

        if (makeLargeFiles) {
            SXSSFSheet sheet = (SXSSFSheet) workbook.getSheetAt(0);
            makeExcelFile.makeLargeFile(sheet);
            workbook.write(fos);
        } else {
            Sheet sheet = workbookOld.getSheetAt(0);
            makeExcelFile.makeNormalFile(sheet);
            workbookOld.write(fos);

        }
    }
    // Doing in reverse order of declaration:
    // 1. workbook.close();
    // 2. workbookOld.close();
    // 3. fos.close();
    // 4. fip.close();
}

In your code there was a reversal, and close happened explicit and via try-with-resources.


问:
Get the average mean of entries per month with datetime in Pandas
I have a large df with many entries per month. I would like to see the average entries per month as to see as an example if there are any months that normally have more entries. (Ideally I'd like to plot this with a line of the over all mean to compare with but that is maybe a later question).
My df is something like this:

```<code>ufo=pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv')
ufo['Time']=pd.to_datetime(ufo.Time)
</code>```

Where the head looks like this:

So if I'd like to see if there are more ufo-sightings in the summer as an example, how would I go about?

I have tried:

```<code>ufo.groupby(ufo.Time.month).mean()
</code>```

But it does only work if I am calculating a numerical value. If I use count()instead I get the sum of all entries for all months.

EDIT: To clarify, I would like to have the mean of entries - ufo-sightings - per month.

答:
I think this what you are looking for, still please ask for clarification if i didn't reached what you are looking for.

```<code># Add a new column instance, this adds a value to each instance of ufo sighting
ufo['instance'] = 1

# set index to time, this makes df a time series df and then you can apply pandas time series functions.
ufo.set_index(ufo['Time'], drop=True, inplace=True)

# create another df by resampling the original df and counting the instance column by Month ('M' is resample by month)
ufo2 = pd.DataFrame(ufo['instance'].resample('M').count())

# just to find month of resampled observation
ufo2['Time'] = pd.to_datetime(ufo2.index.values)

ufo2['month'] = ufo2['Time'].apply(lambda x: x.month)
</code>```

and finally you can groupby month :)

```<code>ufo2.groupby(by='month').mean()
</code>```

and this is the output which looks like this:

```<code>month   mean_instance
1       12.314286
2       11.671429
3       15.657143
4       14.928571
5       16.685714
6       43.084507
7       33.028169
8       27.436620
9       23.028169
10      24.267606
11      21.253521
12      14.563380
</code>```

Body:
I have a large df with many entries per month. I would like to see the average entries per month as to see as an example if there are any months that normally have more entries. (Ideally I'd like to plot this with a line of the over all mean to compare with but that is maybe a later question).
My df is something like this:

ufo=pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv')
ufo['Time']=pd.to_datetime(ufo.Time)

Where the head looks like this:

So if I'd like to see if there are more ufo-sightings in the summer as an example, how would I go about?

I have tried:

ufo.groupby(ufo.Time.month).mean()

But it does only work if I am calculating a numerical value. If I use count()instead I get the sum of all entries for all months.

EDIT: To clarify, I would like to have the mean of entries - ufo-sightings - per month.

Body:
I think this what you are looking for, still please ask for clarification if i didn't reached what you are looking for.

# Add a new column instance, this adds a value to each instance of ufo sighting
ufo['instance'] = 1

# set index to time, this makes df a time series df and then you can apply pandas time series functions.
ufo.set_index(ufo['Time'], drop=True, inplace=True)

# create another df by resampling the original df and counting the instance column by Month ('M' is resample by month)
ufo2 = pd.DataFrame(ufo['instance'].resample('M').count())

# just to find month of resampled observation
ufo2['Time'] = pd.to_datetime(ufo2.index.values)

ufo2['month'] = ufo2['Time'].apply(lambda x: x.month)

and finally you can groupby month :)

ufo2.groupby(by='month').mean()

and this is the output which looks like this:

month   mean_instance
1       12.314286
2       11.671429
3       15.657143
4       14.928571
5       16.685714
6       43.084507
7       33.028169
8       27.436620
9       23.028169
10      24.267606
11      21.253521
12      14.563380


问:
How to get all matching iterations for a capture group
I made this regular expression and use it with re.findall():

```<code>SELECT.*{(?:\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\][,]{0,1}){1,}}.*
</code>```

to match these lists of strings:

["dimSales","Product Title","All"],
  ["test","Product Title","All"]

in this haystack:

```<code>SELECT NON EMPTY Hierarchize({DrilldownLevel({[dimSales].[Product Title].[All],[test].[Product Title].[All]},,,INCLUDE_CALC_MEMBERS)}) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS FROM [Model] CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS
</code>```

my regex only matches the last iteration of the outer capturing group

["test","Product Title","All"]

what do I need to change, so re.findall() returns all iterations. Not just the last iteration of the outer capturing group?

答:
```<code>string = "SELECT NON EMPTY Hierarchize({DrilldownLevel({[dimSales].[Product Title].[All],[test].[Product Title].[All]},,,INCLUDE_CALC_MEMBERS)}) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS FROM [Model] CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"

print re.findall(r"(?:SELECT .+\({|,)\[([\w ]+)\]\.\[([\w ]+)\]\.\[([\w ]+)\](?=[^}]*})",  string)
</code>```

Output:

```<code>[('dimSales', 'Product Title', 'All'), ('test', 'Product Title', 'All')]
</code>```

Explanation:

```<code>(?:SELECT .+\({|,)      # non capture group, match SELECT folowed by 1 or more any character then ({ OR a comma
\[([\w ]+)\]            # group 1, 1 or more word character or space inside square brackets
\.                      # a dot
\[([\w ]+)\]            # group 2, 1 or more word character or space inside square brackets
\.                      # a dot
\[([\w ]+)\]            # group 3, 1 or more word character or space inside square brackets
(?=[^}]*})              # positive lookahead, make sure we have after a close curly bracket not preceeded by another curly bracket
</code>```

Body:
I made this regular expression and use it with re.findall():

SELECT.*{(?:\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\][,]{0,1}){1,}}.*

to match these lists of strings:

["dimSales","Product Title","All"],
  ["test","Product Title","All"]

in this haystack:

SELECT NON EMPTY Hierarchize({DrilldownLevel({[dimSales].[Product Title].[All],[test].[Product Title].[All]},,,INCLUDE_CALC_MEMBERS)}) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS FROM [Model] CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS

my regex only matches the last iteration of the outer capturing group

["test","Product Title","All"]

what do I need to change, so re.findall() returns all iterations. Not just the last iteration of the outer capturing group?

Body:
string = "SELECT NON EMPTY Hierarchize({DrilldownLevel({[dimSales].[Product Title].[All],[test].[Product Title].[All]},,,INCLUDE_CALC_MEMBERS)}) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS FROM [Model] CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS"

print re.findall(r"(?:SELECT .+\({|,)\[([\w ]+)\]\.\[([\w ]+)\]\.\[([\w ]+)\](?=[^}]*})",  string)

Output:

[('dimSales', 'Product Title', 'All'), ('test', 'Product Title', 'All')]

Explanation:

(?:SELECT .+\({|,)      # non capture group, match SELECT folowed by 1 or more any character then ({ OR a comma
\[([\w ]+)\]            # group 1, 1 or more word character or space inside square brackets
\.                      # a dot
\[([\w ]+)\]            # group 2, 1 or more word character or space inside square brackets
\.                      # a dot
\[([\w ]+)\]            # group 3, 1 or more word character or space inside square brackets
(?=[^}]*})              # positive lookahead, make sure we have after a close curly bracket not preceeded by another curly bracket


问:
How to input images to Azure IOT Hub?
I a new to Azure and I have an application where i have to send an image from a device to azure IOT which in turns goes to Azure cognitive services and processes the image for required result.

I have been looking around the internet for options and have seen that using raspberry pi i can achieve this , I want to know is this achievable using an API. Is it possible for me to upload an image into Azure IOT hub by using an .net API (simulating device), if so please suggest relative techniques or please let me know if my approach is wrong.

答:
Basically, the Azure IoT Hub supports the following techniques for your solution described in the following docs:

Upload files with IoT Hub

IoT Hub Device Streams (preview)

Title: How to input images to Azure IOT Hub?


问:
How to add labels into the bars in a bar graph using ggplot2 in R?
I can't put the label inside the bin, only on the top :(. How could I put them inside the bins? Also, I would like to have a white chart, but the chart behind the bins are grey, how could I change it for white?</p>

```<code>ggplot(region,
       aes(x=reorder(Field_Partner_Name,-amount), y=amount, fill=Field_Partner_Name)) +
  geom_bar(stat="identity")+
  ggtitle("Partners that invest more money") +
  labs(x="Partners",y="Amount")+
  geom_text(aes(label = Field_Partner_Name, hjust=0),
            position = position_dodge(width = 0.9), angle = 90) +
  scale_y_continuous(expand = c(0.15, 0))+
  theme(axis.text.x=element_blank(),
        legend.position = "none") +
  ylim(0,90000000)
</code>```

答:
Please provide some data next time. Since I have no data I will use data and example from this link.

```<code>library(ggplot2)

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5))

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=len), vjust=1.6, color="white", size=3.5)+
  theme_minimal()
</code>```

Inside geom_text() vjust sets how "high" the text is. It is a little weird, because positive values mean that the text is lower and for negative values the text is higher. See here:

```<code>ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=len), vjust=-1.5, color="black", size=3.5)+
  theme_minimal()
</code>```

The variable used for label inside of geom_text does not have to be the variable that contains the y axis values. See the following example:

```<code>df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5),
                label= c("a", "b", "a"))

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=label), vjust=1.6, color="white", size=3.5)+
 theme_minimal()
</code>```

Body:
I can't put the label inside the bin, only on the top :(. How could I put them inside the bins? Also, I would like to have a white chart, but the chart behind the bins are grey, how could I change it for white?

ggplot(region,
       aes(x=reorder(Field_Partner_Name,-amount), y=amount, fill=Field_Partner_Name)) +
  geom_bar(stat="identity")+
  ggtitle("Partners that invest more money") +
  labs(x="Partners",y="Amount")+
  geom_text(aes(label = Field_Partner_Name, hjust=0),
            position = position_dodge(width = 0.9), angle = 90) +
  scale_y_continuous(expand = c(0.15, 0))+
  theme(axis.text.x=element_blank(),
        legend.position = "none") +
  ylim(0,90000000)

Body:
Please provide some data next time. Since I have no data I will use data and example from this link.

library(ggplot2)

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5))

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=len), vjust=1.6, color="white", size=3.5)+
  theme_minimal()

Inside geom_text() vjust sets how "high" the text is. It is a little weird, because positive values mean that the text is lower and for negative values the text is higher. See here:

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=len), vjust=-1.5, color="black", size=3.5)+
  theme_minimal()

The variable used for label inside of geom_text does not have to be the variable that contains the y axis values. See the following example:

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5),
                label= c("a", "b", "a"))

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=label), vjust=1.6, color="white", size=3.5)+
 theme_minimal()


问:
How to properly unnest two arrays
I have two arrays: foo_array text[], bar_array text[] inside a function.
Each of them contain strings that will be split into array elements using 'string_to_array' function and type casted to bigint.

I want to return those arrays in a table(out1 bigint, out2 bigint).

For example, foo_array and bar_array each contain 10 elements and I expect the function to return 10 rows with those elements.
I am only able to produce output of 20 elements and don't really understand it.

```<code>CREATE OR REPLACE FUNCTION ___two_unnests()
RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    RETURN QUERY
    SELECT
      unnest(string_to_array(foo, ',')::bigint[]),
      unnest(string_to_array(bar, ',')::bigint[])
    FROM
      unnest(foo_array) as foo,
      unnest(bar_array) as bar;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();
</code>```

Actual output of the function.

```<code>out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
1    |  11
2    |  22
3    |  33
4    |  44
5    |  55
11   |  6
22   |  7
33   |  8
44   |  9
55   |  10
11   |  11
22   |  22
33   |  33
44   |  44
55   |  55
</code>```

Output I want:

```<code>out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
11   |  66
22   |  77
33   |  88
44   |  99
55   |  1010
</code>```

SOLUTION Using sticky-bit's suggestion

```<code>CREATE OR REPLACE FUNCTION ___two_unnests() RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo_slice text;
    foo_text text := '';
    foo_firstiter boolean := true;

    bar_slice text;
    bar_text text := '';
    bar_firstiter boolean := true;

    out1_array bigint[];
    out2_array bigint[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    FOREACH foo_slice IN ARRAY foo_array LOOP
        IF foo_firstiter = true THEN
            foo_text := foo_text || foo_slice;
            foo_firstiter := false;
        ELSE
            foo_text := foo_text || ',' || foo_slice;
        END IF;
    END LOOP;

    FOREACH bar_slice IN ARRAY bar_array LOOP
        IF bar_firstiter = true THEN
            bar_text := bar_text || bar_slice;
            bar_firstiter := false;
        ELSE
            bar_text := bar_text || ',' || bar_slice;
        END IF;
    END LOOP;

    out1_array := (SELECT string_to_array(foo_text, ',')::bigint[]);
    out2_array := (SELECT string_to_array(bar_text, ',')::bigint[]);

    RAISE NOTICE 'out1_array: %', out1_array;
    RAISE NOTICE 'out2_array: %', out2_array;

    RETURN QUERY SELECT un1.val::bigint,
            un2.val::bigint
       FROM unnest(out1_array) WITH ORDINALITY un1 (val, ord)
            FULL JOIN unnest(out2_array) WITH ORDINALITY un2 (val, ord)
                      ON un2.ord = un1.ord;

END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();
</code>```

答:
You can unnest() WITH ORDINALITY, so that every element gets an index, and full join the results on that.

```<code>SELECT un1.val::bigint,
       un2.val::bigint
       FROM unnest(ARRAY[1, 2, 3, 4, 5, 11, 22, 33, 44, 55]) WITH ORDINALITY un1 (val, ord)
            FULL JOIN unnest(ARRAY[6, 7, 8, 9, 10, 66, 77, 88, 99, 1010]) WITH ORDINALITY un2 (val, ord)
                      ON un2.ord = un1.ord;
</code>```

db<>fiddle

Title: How to properly unnest two arrays

Body:
I have two arrays: foo_array text[], bar_array text[] inside a function.
Each of them contain strings that will be split into array elements using 'string_to_array' function and type casted to bigint.

I want to return those arrays in a table(out1 bigint, out2 bigint).

For example, foo_array and bar_array each contain 10 elements and I expect the function to return 10 rows with those elements.
I am only able to produce output of 20 elements and don't really understand it.

CREATE OR REPLACE FUNCTION ___two_unnests()
RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    RETURN QUERY
    SELECT
      unnest(string_to_array(foo, ',')::bigint[]),
      unnest(string_to_array(bar, ',')::bigint[])
    FROM
      unnest(foo_array) as foo,
      unnest(bar_array) as bar;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();

Actual output of the function.

out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
1    |  11
2    |  22
3    |  33
4    |  44
5    |  55
11   |  6
22   |  7
33   |  8
44   |  9
55   |  10
11   |  11
22   |  22
33   |  33
44   |  44
55   |  55

Output I want:

out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
11   |  66
22   |  77
33   |  88
44   |  99
55   |  1010

SOLUTION Using sticky-bit's suggestion

CREATE OR REPLACE FUNCTION ___two_unnests() RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo_slice text;
    foo_text text := '';
    foo_firstiter boolean := true;

    bar_slice text;
    bar_text text := '';
    bar_firstiter boolean := true;

    out1_array bigint[];
    out2_array bigint[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    FOREACH foo_slice IN ARRAY foo_array LOOP
        IF foo_firstiter = true THEN
            foo_text := foo_text || foo_slice;
            foo_firstiter := false;
        ELSE
            foo_text := foo_text || ',' || foo_slice;
        END IF;
    END LOOP;

    FOREACH bar_slice IN ARRAY bar_array LOOP
        IF bar_firstiter = true THEN
            bar_text := bar_text || bar_slice;
            bar_firstiter := false;
        ELSE
            bar_text := bar_text || ',' || bar_slice;
        END IF;
    END LOOP;

    out1_array := (SELECT string_to_array(foo_text, ',')::bigint[]);
    out2_array := (SELECT string_to_array(bar_text, ',')::bigint[]);

    RAISE NOTICE 'out1_array: %', out1_array;
    RAISE NOTICE 'out2_array: %', out2_array;

    RETURN QUERY SELECT un1.val::bigint,
            un2.val::bigint
       FROM unnest(out1_array) WITH ORDINALITY un1 (val, ord)
            FULL JOIN unnest(out2_array) WITH ORDINALITY un2 (val, ord)
                      ON un2.ord = un1.ord;

END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();

Body:
You can unnest() WITH ORDINALITY, so that every element gets an index, and full join the results on that.

SELECT un1.val::bigint,
       un2.val::bigint
       FROM unnest(ARRAY[1, 2, 3, 4, 5, 11, 22, 33, 44, 55]) WITH ORDINALITY un1 (val, ord)
            FULL JOIN unnest(ARRAY[6, 7, 8, 9, 10, 66, 77, 88, 99, 1010]) WITH ORDINALITY un2 (val, ord)
                      ON un2.ord = un1.ord;

db<>fiddle


问:
complex SQL query tuning
Hello I have a query that's taking a lot of time to execute and consuming so much resources, the query is similar to this:

```<code>WITH first_match AS (
        SELECT t1.name
               , t1.lastname
               , t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = t2.name
)
, second_match AS (
        SELECT t1.name
                , t1.lastname
                , t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = SUBSTR(t2.name,0,INSTR(t2.name,'-'))
        WHERE REGEXP_LIKE(t2.name,'[-]')
        AND (t1.name, t1.lastname) NOT IN (SELECT name, lastname FROM first_match)
)
, third_match AS (
        SELECT t1.name
                ,t1.lastname
                ,t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = REGEXP_REPLACE(t2.name, 'uselesssuffix', '')
        WHERE REGEXP_LIKE(t1.name, 'uselesssuffix')
        AND (t1.name, t1.lastname) NOT IN (
                                SELECT name, lastname FROM first_match
                                UNION
                                SELECT name, lastname FROM second_match
                                )
)
, fourth_match AS (
        SELECT t1.name
                ,t1.lastname
                ,t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = SUBSTR(t2.name, 0, 7)
        WHERE LENGTH(t2.name) > 6
        AND (t1.name, t1.lastname) NOT IN (
                                SELECT name, lastname FROM first_match
                                UNION
                                SELECT name, lastname FROM second_match
                                UNION
                                SELECT name, lastname FROM third_match
                                )
)
, final_result AS (
SELECT * FROM first_match
UNION
SELECT * FROM second_match
UNION
SELECT * FROM third_match
UNION
SELECT * FROM fourth_match
)
SELECT * FROM final_result;
</code>```

Where I have two tables and trying to join between them on let's say 4 possible conditions, the first CTE contains the result of the first condition, the second contains the entries not included in the first and comply to the second condition, the third contains the remaining that also comply to the third condition etc..
thus the use of
AND (t1.name, t1.lastname) NOT IN (SELECT name, lastname FROM first_match)..
condition,
and eventually I use UNION to generate the final result, now the relatively big number of CTEs (5 in this case) and the big number of UNION, and conditions is turning this query to a heavy one and takes so much resources and so much time to execute,
any ideas on whether there's a better way to implement the same scenario but with a different approach, maybe in one CTE

答:
You have multiple matches that you are trying to prioritize.  One thing to try is a series of LEFT JOINs:

```<code>SELECT t1.name, t1.lastname,
       COALESCE(t2_1.location, t2_2.location, , . . . )
FROM table1 t1 LEFT JOIN
     table2 t2_1
     ON t1.name = t2_1.name LEFT JOIN
     table2 t2_2
     ON t1.name = SUBSTR(t2_2.name, 1, INSTR(t2_2.name, '-')) AND
        t2_2.name LIKE '%-%' AND
        t2_1.name IS NULL LEFT JOIN
     table2 t2_3
     ON t1.name = REGEXP_REPLACE(t2_3.name, 'uselesssuffix', '') AND
        t1.name LIKE '%uselesssuffix%' AND
        t2_1.name IS NULL AND
        t2_2.name IS NULL LEFT JOIN
     . . .
WHERE t1.name IS NOT NULL OR
      t2_1.name IS NOT NULL OR
      . . .
</code>```

Note that each new condition checks that all the previous conditions do not match.

Title: complex SQL query tuning

Body:
Hello I have a query that's taking a lot of time to execute and consuming so much resources, the query is similar to this:

WITH first_match AS (
        SELECT t1.name
               , t1.lastname
               , t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = t2.name
)
, second_match AS (
        SELECT t1.name
                , t1.lastname
                , t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = SUBSTR(t2.name,0,INSTR(t2.name,'-'))
        WHERE REGEXP_LIKE(t2.name,'[-]')
        AND (t1.name, t1.lastname) NOT IN (SELECT name, lastname FROM first_match)
)
, third_match AS (
        SELECT t1.name
                ,t1.lastname
                ,t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = REGEXP_REPLACE(t2.name, 'uselesssuffix', '')
        WHERE REGEXP_LIKE(t1.name, 'uselesssuffix')
        AND (t1.name, t1.lastname) NOT IN (
                                SELECT name, lastname FROM first_match
                                UNION
                                SELECT name, lastname FROM second_match
                                )
)
, fourth_match AS (
        SELECT t1.name
                ,t1.lastname
                ,t2.location
        FROM table1 t1
        INNER JOIN
        table2 t2
        ON t1.name = SUBSTR(t2.name, 0, 7)
        WHERE LENGTH(t2.name) > 6
        AND (t1.name, t1.lastname) NOT IN (
                                SELECT name, lastname FROM first_match
                                UNION
                                SELECT name, lastname FROM second_match
                                UNION
                                SELECT name, lastname FROM third_match
                                )
)
, final_result AS (
SELECT * FROM first_match
UNION
SELECT * FROM second_match
UNION
SELECT * FROM third_match
UNION
SELECT * FROM fourth_match
)
SELECT * FROM final_result;

Where I have two tables and trying to join between them on let's say 4 possible conditions, the first CTE contains the result of the first condition, the second contains the entries not included in the first and comply to the second condition, the third contains the remaining that also comply to the third condition etc..
thus the use of
AND (t1.name, t1.lastname) NOT IN (SELECT name, lastname FROM first_match)..
condition,
and eventually I use UNION to generate the final result, now the relatively big number of CTEs (5 in this case) and the big number of UNION, and conditions is turning this query to a heavy one and takes so much resources and so much time to execute,
any ideas on whether there's a better way to implement the same scenario but with a different approach, maybe in one CTE

Body:
You have multiple matches that you are trying to prioritize.  One thing to try is a series of LEFT JOINs:

SELECT t1.name, t1.lastname,
       COALESCE(t2_1.location, t2_2.location, , . . . )
FROM table1 t1 LEFT JOIN
     table2 t2_1
     ON t1.name = t2_1.name LEFT JOIN
     table2 t2_2
     ON t1.name = SUBSTR(t2_2.name, 1, INSTR(t2_2.name, '-')) AND
        t2_2.name LIKE '%-%' AND
        t2_1.name IS NULL LEFT JOIN
     table2 t2_3
     ON t1.name = REGEXP_REPLACE(t2_3.name, 'uselesssuffix', '') AND
        t1.name LIKE '%uselesssuffix%' AND
        t2_1.name IS NULL AND
        t2_2.name IS NULL LEFT JOIN
     . . .
WHERE t1.name IS NOT NULL OR
      t2_1.name IS NOT NULL OR
      . . .

Note that each new condition checks that all the previous conditions do not match.