问:
Caliburn.Micro : How to bind a specific Item of Conductor.Collection.AllActive to a ContentControl
My goal is to have 4 different active ViewModels displayed in a grid on the ShellView. The issue is that I have not been able to figure out how to wire up a ContentControl to a specific Item in Items of the Conductor. How can his be done?

Here is a simplified version of what I and trying to do.

SolutionExplorer

ShellViewModel:

```<code>namespace ContentControlTest.ViewModels
{
    public class ShellViewModel : Conductor<object>.Collection.AllActive
    {
        public ShellViewModel()
        {
            ActivateItem(new UC1ViewModel());
            ActivateItem(new UC2ViewModel());
            ActivateItem(new UC3ViewModel());
            ActivateItem(new UC4ViewModel());
        }
    }
}
</code>```

ShellView:

```<code><Window x:Class="ContentControlTest.Views.ShellView"
        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:ContentControlTest.Views"
        xmlns:cal="http://www.caliburnproject.org"
        mc:Ignorable="d"
        Title="ShellView" Height="450" Width="800"
        >

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <ScrollViewer Grid.Row="0" Grid.Column="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC1ViewModel}" cal:View.Context="{Binding Items[0]}"/>
        </ScrollViewer>
        <ScrollViewer Grid.Row="0" Grid.Column="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC2ViewModel}" cal:View.Context="{Binding Items[1]}"/>
        </ScrollViewer>
        <ScrollViewer Grid.Row="1" Grid.Column="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC3ViewModel}" cal:View.Context="{Binding Items[2]}"/>
        </ScrollViewer>
        <ScrollViewer Grid.Row="1" Grid.Column="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC4ViewModel}" cal:View.Context="{Binding Items[3]}"/>
        </ScrollViewer>
    </Grid>
</Window>
</code>```

For simplification each UserControl ViewModel and View are Identical:

UC#ViewModel:

```<code>namespace ContentControlTest.ViewModels
{
    public class UC1ViewModel : Screen
    {
        private string id;
        public string ID
        {
            get { return id; }
            set
            {
                id = value;
                NotifyOfPropertyChange(() => ID);
            }
        }

        public UC1ViewModel()
        {
            ID = Guid.NewGuid().ToString();
        }

    }
}
</code>```

UC#View:

```<code><UserControl x:Class="ContentControlTest.Views.UC1View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:ContentControlTest.Views"
             xmlns:cal="http://www.caliburnproject.org"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800"
             >
    <Border BorderBrush="Black"  BorderThickness="1">
        <StackPanel >
            <TextBlock Text="{Binding DisplayName}"/>
            <TextBlock Text="{Binding ID}"/>
        </StackPanel>
    </Border>
</UserControl>
</code>```

For testing I have tried using an ItemControl and it works but doesn't give me exactly what I want.

```<code><ItemsControl x:Name="Items">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel></StackPanel>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
</code>```

答:
In case anyone is having an issue implementing the [perfectly fine] accepted answer, here is a more in depth answer:

Your main window that contain both (or even more than two) of your User Controls must be inherited from Caliburn.Micro.Conductor<Screen>.Collection.AllActive;

Your User Controls must be inherited from Caliburn.Micro.Screen;

You must also keep naming conventions in mind. If you use MenuUC as the name of a ContentControl in your View, also create a property named MenuUC in your ViewModel;

Initialize your UserControl as I do in Constructor;

Now you can use ActivateItem(MenuUC) and DeactivateItem(MenuUC) everywhere in your code. Caliburn.Micro automatically detects which one you want to work with.

Example XAML View code:

<Window x:Class="YourProject.Views.YourView"
        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"
        mc:Ignorable="d"
        Title="YourViewTitle" Width="900" Height="480">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="4*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ContentControl Grid.Row="0" Grid.Column="0" x:Name="MenuUC" />

        <Border Grid.Column="1" Grid.RowSpan="2" BorderThickness="1,0,0,0" BorderBrush="#FF707070" >
            <ContentControl x:Name="PanelUC" />
        </Border>
    </Grid>
</Window>
```

<blockquote>
  <p>Example C# ViewModel code:</p>
</blockquote>

<pre class="lang-cs prettyprint-override"><code>class YourViewModel : Conductor<Screen>.Collection.AllActive
{
    // Menu Side Bar
    private MenuUCViewModel _menuUC;
    public MenuUCViewModel MenuUC
    {
        get { return _menuUC; }
        set { _menuUC = value; NotifyOfPropertyChange(() => MenuUC); }
    }

    // Panel
    private Screen _panelUC;
    public Screen PanelUC
    {
        get { return _panelUC; }
        set { _panelUC = value; NotifyOfPropertyChange(() => PanelUC); }
    }

    // Constructor
    public YourViewModel()
    {
        MenuUC = new MenuUCViewModel();
        ActivateItem(MenuUC);

        PanelUC = new FirstPanelUCViewModel();
        ActivateItem(PanelUC);
    }

    // Some method that changes PanelUC (previously FirstPanelUCViewModel) to SecondPanelUCViewModel
    public void ChangePanels()
    {
        DeactivateItem(PanelUC);
        PanelUC = new SecondPanelUCViewModel();
        ActivateItem(PanelUC);
    }
}
</code>```

In the above example, ChangePanels() acts as a method to load new User Control into your ContentControl.

Also read this question, it might be help you further.

Body:
My goal is to have 4 different active ViewModels displayed in a grid on the ShellView. The issue is that I have not been able to figure out how to wire up a ContentControl to a specific Item in Items of the Conductor. How can his be done?

Here is a simplified version of what I and trying to do.

SolutionExplorer

ShellViewModel:

namespace ContentControlTest.ViewModels
{
    public class ShellViewModel : Conductor<object>.Collection.AllActive
    {
        public ShellViewModel()
        {
            ActivateItem(new UC1ViewModel());
            ActivateItem(new UC2ViewModel());
            ActivateItem(new UC3ViewModel());
            ActivateItem(new UC4ViewModel());
        }
    }
}

ShellView:

<Window x:Class="ContentControlTest.Views.ShellView"
        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:ContentControlTest.Views"
        xmlns:cal="http://www.caliburnproject.org"
        mc:Ignorable="d"
        Title="ShellView" Height="450" Width="800"
        >

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <ScrollViewer Grid.Row="0" Grid.Column="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC1ViewModel}" cal:View.Context="{Binding Items[0]}"/>
        </ScrollViewer>
        <ScrollViewer Grid.Row="0" Grid.Column="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC2ViewModel}" cal:View.Context="{Binding Items[1]}"/>
        </ScrollViewer>
        <ScrollViewer Grid.Row="1" Grid.Column="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC3ViewModel}" cal:View.Context="{Binding Items[2]}"/>
        </ScrollViewer>
        <ScrollViewer Grid.Row="1" Grid.Column="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <ContentControl cal:View.Model="{Binding UC4ViewModel}" cal:View.Context="{Binding Items[3]}"/>
        </ScrollViewer>
    </Grid>
</Window>

For simplification each UserControl ViewModel and View are Identical:

UC#ViewModel:

namespace ContentControlTest.ViewModels
{
    public class UC1ViewModel : Screen
    {
        private string id;
        public string ID
        {
            get { return id; }
            set
            {
                id = value;
                NotifyOfPropertyChange(() => ID);
            }
        }

        public UC1ViewModel()
        {
            ID = Guid.NewGuid().ToString();
        }

    }
}

UC#View:

<UserControl x:Class="ContentControlTest.Views.UC1View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:ContentControlTest.Views"
             xmlns:cal="http://www.caliburnproject.org"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800"
             >
    <Border BorderBrush="Black"  BorderThickness="1">
        <StackPanel >
            <TextBlock Text="{Binding DisplayName}"/>
            <TextBlock Text="{Binding ID}"/>
        </StackPanel>
    </Border>
</UserControl>

For testing I have tried using an ItemControl and it works but doesn't give me exactly what I want.

<ItemsControl x:Name="Items">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel></StackPanel>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>

Body:
In case anyone is having an issue implementing the [perfectly fine] accepted answer, here is a more in depth answer:

Your main window that contain both (or even more than two) of your User Controls must be inherited from Caliburn.Micro.Conductor<Screen>.Collection.AllActive;

Your User Controls must be inherited from Caliburn.Micro.Screen;

You must also keep naming conventions in mind. If you use MenuUC as the name of a ContentControl in your View, also create a property named MenuUC in your ViewModel;

Initialize your UserControl as I do in Constructor;

Now you can use ActivateItem(MenuUC) and DeactivateItem(MenuUC) everywhere in your code. Caliburn.Micro automatically detects which one you want to work with.

Example XAML View code:

<Window x:Class="YourProject.Views.YourView"
        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"
        mc:Ignorable="d"
        Title="YourViewTitle" Width="900" Height="480">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="4*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Menu Side Bar -->
        <ContentControl Grid.Row="0" Grid.Column="0" x:Name="MenuUC" />

        <!-- Panel -->
        <Border Grid.Column="1" Grid.RowSpan="2" BorderThickness="1,0,0,0" BorderBrush="#FF707070" >
            <ContentControl x:Name="PanelUC" />
        </Border>
    </Grid>
</Window>

Example C# ViewModel code:

class YourViewModel : Conductor<Screen>.Collection.AllActive
{
    // Menu Side Bar
    private MenuUCViewModel _menuUC;
    public MenuUCViewModel MenuUC
    {
        get { return _menuUC; }
        set { _menuUC = value; NotifyOfPropertyChange(() => MenuUC); }
    }

    // Panel
    private Screen _panelUC;
    public Screen PanelUC
    {
        get { return _panelUC; }
        set { _panelUC = value; NotifyOfPropertyChange(() => PanelUC); }
    }

    // Constructor
    public YourViewModel()
    {
        MenuUC = new MenuUCViewModel();
        ActivateItem(MenuUC);

        PanelUC = new FirstPanelUCViewModel();
        ActivateItem(PanelUC);
    }

    // Some method that changes PanelUC (previously FirstPanelUCViewModel) to SecondPanelUCViewModel
    public void ChangePanels()
    {
        DeactivateItem(PanelUC);
        PanelUC = new SecondPanelUCViewModel();
        ActivateItem(PanelUC);
    }
}

In the above example, ChangePanels() acts as a method to load new User Control into your ContentControl.

Also read this question, it might be help you further.


来源: stackexchange

问:
Rewrite jQuery function to Vanilla JS and optimize
First I want to apologize, because I am a bit newbie with JS and it's library jQuery. Basically I have written a javascript function that toggles my hamburger menu:

```<code>const menuToggle = document.querySelector('.menu-toggle');
let menuOpen = false;
menuToggle.addEventListener('click', () => {
  if(!menuOpen) {
    menuToggle.classList.add('open');
    menuOpen = true;
  } else {
    menuToggle.classList.remove('open');
    menuOpen = false;
  }
});
</code>```

Now I want to rewrite this jQuery function to Vanilla JS

```<code>$(function() {
  $('.toggle').on('click', function() {
    $('.inner-wrapper').toggleClass('open');
  });
});
</code>```

I tried this, but it is not working:

```<code>var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);
</code>```

I would like to combine both functions if possible. Thanks in advance!

答:
Try this,

```<code>searchElement.addEventListener("click", handleClick);
</code>```

And your current code will add a event listener to inner-wrapper class instead of toggle class.

The javascript representation of your jQuery code has to be something like this

```<code>document.querySelector('.toggle').addEventListener('click', function(){
   document.querySelector('.inner-wrapper').classList.toggle('open');
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
First I want to apologize, because I am a bit newbie with JS and it's library jQuery. Basically I have written a javascript function that toggles my hamburger menu:

const menuToggle = document.querySelector('.menu-toggle');
let menuOpen = false;
menuToggle.addEventListener('click', () => {
  if(!menuOpen) {
    menuToggle.classList.add('open');
    menuOpen = true;
  } else {
    menuToggle.classList.remove('open');
    menuOpen = false;
  }
});

Now I want to rewrite this jQuery function to Vanilla JS

$(function() {
  $('.toggle').on('click', function() {
    $('.inner-wrapper').toggleClass('open');
  });
});

I tried this, but it is not working:

var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);

I would like to combine both functions if possible. Thanks in advance!

Body:
Try this,

searchElement.addEventListener("click", handleClick);

And your current code will add a event listener to inner-wrapper class instead of toggle class.

The javascript representation of your jQuery code has to be something like this

document.querySelector('.toggle').addEventListener('click', function(){
   document.querySelector('.inner-wrapper').classList.toggle('open');
})


问:
Vectorize code in function where loops use range in Python/NumPy
I have a function which is called many times in other functions. To improve computation I am trying to vectorize the code though I did not manage to do so in this particular case in which there are complex ranges involved. Does any of you see how it can be done in this specific case?

```<code>def growdh_no_bloom(mx, mn, daylen, baset):

    if mn == 0:
        mn = 0.01
    if mx == mn:
        mx += 0.01
    dt = mx - mn

    idl = int(np.floor(daylen))

    # calculate day time hourly temperatures
    t = np.zeros(24)
    t[0] = mn

    for hour in range(1, idl+1):
        t[hour] = dt * np.sin(np.pi/(daylen+4)*(hour)) + mn

    # calculate sunset time and temperature
    ts1 = dt*np.sin(np.pi/(daylen+4)*daylen) + mn
    if ts1 <= 0:
        ts1 = 0.01

    # calculate hourly temperatures (nighttime)
    count = 0
    for hour in range(idl + 1, 24):
        count += 1
        t[hour] = ts1-(ts1-mn)/(np.log(24-daylen))*np.log(count)

    # growing degree hours
    gdhour = 0
    for hour in range(0, 24):
        if t[hour] - baset > 0:
            gdhour += (t[hour] - baset)
    return gdhour
</code>```

Thanks in advance!

答:
While Numba will definitely yield better performance, I think that a streamlined function will be of use to you as well, for future reference. Note how I removed all of the loops with simple broadcasting.</p>

```<code>def growdh_no_bloom(mx, mn, daylen, baset):
    mn = 0.01 if mn==0 else mn
    mx = mx + 0.01 if mx == mn else mx
    dt = mx - mn
    idl = int(np.floor(daylen))

    # calculate day time hourly temperatures
    t = np.zeros(24)
    t[0] = mn
    t[1:idl+1] = dt * np.sin(np.pi/(daylen+4)*np.arange(1,idl+1)) + mn

    # calculate sunset time and temperature
    ts1 = dt*np.sin(np.pi/(daylen+4)*daylen) + mn
    ts1 = 0.01 if ts1 <= 0 else ts1

    # calculate hourly temperatures (nighttime)
    t[idl+1:24] = ts1-(ts1-mn)/(np.log(24-daylen))*np.log(np.arange(1,24-idl))

    gdhour = t-baset
    return gdhour[gdhour>0].sum()
</code>```

Body:
I have a function which is called many times in other functions. To improve computation I am trying to vectorize the code though I did not manage to do so in this particular case in which there are complex ranges involved. Does any of you see how it can be done in this specific case?

def growdh_no_bloom(mx, mn, daylen, baset):

    if mn == 0:
        mn = 0.01
    if mx == mn:
        mx += 0.01
    dt = mx - mn

    idl = int(np.floor(daylen))

    # calculate day time hourly temperatures
    t = np.zeros(24)
    t[0] = mn

    for hour in range(1, idl+1):
        t[hour] = dt * np.sin(np.pi/(daylen+4)*(hour)) + mn

    # calculate sunset time and temperature
    ts1 = dt*np.sin(np.pi/(daylen+4)*daylen) + mn
    if ts1 <= 0:
        ts1 = 0.01

    # calculate hourly temperatures (nighttime)
    count = 0
    for hour in range(idl + 1, 24):
        count += 1
        t[hour] = ts1-(ts1-mn)/(np.log(24-daylen))*np.log(count)

    # growing degree hours
    gdhour = 0
    for hour in range(0, 24):
        if t[hour] - baset > 0:
            gdhour += (t[hour] - baset)
    return gdhour

Thanks in advance!

Body:
While Numba will definitely yield better performance, I think that a streamlined function will be of use to you as well, for future reference. Note how I removed all of the loops with simple broadcasting.

def growdh_no_bloom(mx, mn, daylen, baset):
    mn = 0.01 if mn==0 else mn
    mx = mx + 0.01 if mx == mn else mx
    dt = mx - mn
    idl = int(np.floor(daylen))

    # calculate day time hourly temperatures
    t = np.zeros(24)
    t[0] = mn
    t[1:idl+1] = dt * np.sin(np.pi/(daylen+4)*np.arange(1,idl+1)) + mn

    # calculate sunset time and temperature
    ts1 = dt*np.sin(np.pi/(daylen+4)*daylen) + mn
    ts1 = 0.01 if ts1 <= 0 else ts1

    # calculate hourly temperatures (nighttime)
    t[idl+1:24] = ts1-(ts1-mn)/(np.log(24-daylen))*np.log(np.arange(1,24-idl))

    gdhour = t-baset
    return gdhour[gdhour>0].sum()


问:
Apache Hudi commit id for current ingestion
How to get the current ingestion commit Id .I know HoodieDataSourceHelpers.latestCommit method can use to find the latest commit. But what happen if there is concurrent write in different thread. i need to find each thread commitID  </p>

答: Hudi does not allow concurrent writing at the moment. In any case HoodieDataSourceHelpers.latestCommit will return the latest commit always.


问:
How to use View Binding with Linear Layout?
I have a activity_main.xml file which looks like this.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center"
    tools:context=".MainActivity"
    android:id="@+id/main_linear_layout">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:id="@+id/dice_text"/>

    <Button
        android:id="@+id/roll_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/roll"/>

</LinearLayout>
</code>```

So when i try to create a view binding and use it in Activity file,
class MainActivity : AppCompatActivity() {

```<code>private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val root = binding.root
    setContentView(root.main_linear_layout)
    buttonClicked()
}

fun buttonClicked(): Unit {
    val roll_button = binding.mainLinearLayout.roll_button
    val text = binding.mainLinearLayout.dice_text
    roll_button.setOnClickListener {
        var randomNumber = Random().nextInt(6)+1
        text.text = randomNumber.toString()
    }
}
</code>```

}

i have some issues. Naturally since the Linear Layout has layout_gravity set to center, it should be centered in the screen, both vertically and horizontally. This is the case in the design editor of the xml which is how it is supposed to be.

But when i run the app, in my phone both the text and button, aligns center_horizontal but not vertically.

I tried giving center_vertical also but doesn't work.

But if i don't use the view binding and use findViewById , it works fine.

Edit: I have removed the mainLinearLayout from the binding. So its just

```<code>setContentView(root)

</code>```

I doesn't work.This is how i want it to be and this is how it is present in the Design View of the xml ( I have removed text and added Image)

But, when i run it, i get this. enter image description here

P.S I have just started learning android development

答:
Try this :

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = ActivityMainBinding.inflate(layoutInflater)
    val root = binding.root
    setContentView(root)
    buttonClicked()
}
</code>```

Source: https://developer.android.com/topic/libraries/view-binding#activities

Body:
I have a activity_main.xml file which looks like this.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center"
    tools:context=".MainActivity"
    android:id="@+id/main_linear_layout">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:id="@+id/dice_text"/>

    <Button
        android:id="@+id/roll_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/roll"/>

</LinearLayout>

So when i try to create a view binding and use it in Activity file,
class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val root = binding.root
    setContentView(root.main_linear_layout)
    buttonClicked()
}

fun buttonClicked(): Unit {
    val roll_button = binding.mainLinearLayout.roll_button
    val text = binding.mainLinearLayout.dice_text
    roll_button.setOnClickListener {
        var randomNumber = Random().nextInt(6)+1
        text.text = randomNumber.toString()
    }
}

}

i have some issues. Naturally since the Linear Layout has layout_gravity set to center, it should be centered in the screen, both vertically and horizontally. This is the case in the design editor of the xml which is how it is supposed to be.

But when i run the app, in my phone both the text and button, aligns center_horizontal but not vertically.

I tried giving center_vertical also but doesn't work.

But if i don't use the view binding and use findViewById , it works fine.

Edit: I have removed the mainLinearLayout from the binding. So its just

setContentView(root)

I doesn't work.This is how i want it to be and this is how it is present in the Design View of the xml ( I have removed text and added Image)

But, when i run it, i get this. enter image description here

P.S I have just started learning android development

Body:
Try this :

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = ActivityMainBinding.inflate(layoutInflater)
    val root = binding.root
    setContentView(root)
    buttonClicked()
}

Source: https://developer.android.com/topic/libraries/view-binding#activities


问:
Strange accounts are created within an application in development mode
I know the question is not about programming, but I'm a bit confused

I work on the Android app and have not published or shared it with anyone and there is no other app related to the app or databases

Despite that, I find accounts that I haven't added to databases, there are people who create accounts in databases in some way.
How can I find out how they can create an account?

These are some of the accounts who created my account :

```<code>admin@sheridanbuilding.com.au
megaliceb@aol.com
lcchen93@hotmail.com
headphonejackbuisness@gmail.com
</code>```

答: Once an account is created, there is no way to track how that happened.  The APIs for dealing with Firebase Auth are effectively public, so once you enable the email/password authentication method, anyone can start using it, even outside of your app.</p>

Body:
I know the question is not about programming, but I'm a bit confused

I work on the Android app and have not published or shared it with anyone and there is no other app related to the app or databases

Despite that, I find accounts that I haven't added to databases, there are people who create accounts in databases in some way.
How can I find out how they can create an account?

These are some of the accounts who created my account :

admin@sheridanbuilding.com.au
megaliceb@aol.com
lcchen93@hotmail.com
headphonejackbuisness@gmail.com


问:
Creating a plot with multiple pandas datadframes-Python
I am trying to built a code in which for approximate 100 .txt files that I open from a folder I generate a unique plot of the dataframes, in which I select just the first two columns. This is my code, which unfortunately doesn't work at all (I got 100 different plots)

```<code>import pandas as pd
import os
import glob

file_location = os.path.join('files','*.txt')
filenames = glob.glob(file_location)

for f in filenames:
  outfile = pd.read_csv(f, nrows=310, sep=" ", header=None)
  df = pd.DataFrame(outfile)
  data = df.iloc[:, 0:2]
  data.columns = ['x','y']
  #print(data)

  for frame in data:
     data.plot(x="x",y="y", alpha=0.5)
</code>```

Any help would be great! Thanks in advance

答:
You can do the plotting using the pyplot object itself, so you can handle the plotting behavior better. In your case, the following modification works:

```<code>from matplotlib import pyplot as plt

for f in filenames:
  df = pd.read_csv(f, nrows=310, sep=" ", header=None)

  # the df = pd.DataFrame(outputfile) is unecessary. pd.read_csv
  # returns a data frame in the first place

  data = df.iloc[:, 0:2]
  data.columns = ['x','y']

  plt.plot(data.x, data.y, alpha=0.5, color='blue')

plt.show() # or plt.savefig()
</code>```

If you don't specify the color every dataframe will be plotted with a unique color

Body:
I am trying to built a code in which for approximate 100 .txt files that I open from a folder I generate a unique plot of the dataframes, in which I select just the first two columns. This is my code, which unfortunately doesn't work at all (I got 100 different plots)

import pandas as pd
import os
import glob

file_location = os.path.join('files','*.txt')
filenames = glob.glob(file_location)

for f in filenames:
  outfile = pd.read_csv(f, nrows=310, sep=" ", header=None)
  df = pd.DataFrame(outfile)
  data = df.iloc[:, 0:2]
  data.columns = ['x','y']
  #print(data)

  for frame in data:
     data.plot(x="x",y="y", alpha=0.5)

Any help would be great! Thanks in advance

Body:
You can do the plotting using the pyplot object itself, so you can handle the plotting behavior better. In your case, the following modification works:

from matplotlib import pyplot as plt

for f in filenames:
  df = pd.read_csv(f, nrows=310, sep=" ", header=None)

  # the df = pd.DataFrame(outputfile) is unecessary. pd.read_csv
  # returns a data frame in the first place

  data = df.iloc[:, 0:2]
  data.columns = ['x','y']

  plt.plot(data.x, data.y, alpha=0.5, color='blue')

plt.show() # or plt.savefig()

If you don't specify the color every dataframe will be plotted with a unique color


问:
ValueError in dataframe while trying to extract day, month and year using datetime python library
I have three columns in my dataframe: Tweet Posted Time (UTC), Tweet Content, and Tweet Location. The "Tweet Posted Time (UTC)" column has date object in the format: 31 Mar 2020 10:49:01

My objective is to reformat the dataframe in such a way that the 'Tweet Posted Time (UTC)' column displays only the day, month and the year alone (such as 31-03-2020), to be able to plot a time-series graph, but my attempts result in the error below.

ValueError: time data '0       31 Mar 2020 10:49:01\n1       31 Mar 2020 05:48:43\n2       30 Mar 2020 05:38:50\n3       29 Mar 2020 21:19:23\n4       29 Mar 2020 20:28:22\n                ...         \n2488    02 Jan 2018 13:36:07\n2489    02 Jan 2018 10:33:21\n2490    01 Jan 2018 12:23:47\n2491    01 Jan 2018 06:03:51\n2492    01 Jan 2018 02:09:15\nName: Tweet Posted Time (UTC), Length: 2451, dtype: object' does not match format '%d %b %Y %H:%M:%S'

My code is below, can you tell me what I am doing wrong, please?

```<code>from datetime import datetime
import pandas as pd
import re #regular expression
from textblob import TextBlob
import string
import preprocessor as p

pd.set_option("expand_frame_repr", False)

df1 = pd.read_csv("C:/tweet_data.csv")

dataType = df1.dtypes
print(dataType)

# convert datetime object to string
old_formatDate = str(df1['Tweet Posted Time (UTC)'])

# extract day, month, and year and convert back to datetime object
date_TimeObject = datetime.strptime(old_formatDate, '%d %b %Y %H:%M:%S')
new_formatDate = date_TimeObject.strftime('%d-%m-%Y')
print(new_formatDate)
</code>```

答:
I researched and solved the problem by changing the data frame to panda series and then to datetime format. Then, applied dt.strftime.</p>

```<code>df.columns = ['Tweet_Posted_Time', 'Tweet_Content', 'Tweet_Location']
print(df)

# Convert the date and time column (Tweet_Posted_Time) from panda data frame to Panda Series
df1 = pd.Series(df['Tweet_Posted_Time'])
print(df1)

# Convert the Panda Series to datetime format
df1 = pd.to_datetime(df1)
print(df1)

# convert the date column to new date format
df1 = df1.dt.strftime('%d-%m-%Y')
print(df1)

# Replace the Column "Tweet_Posted_Time" in the original data frame with the new data frame containing new date format
df.assign(Tweet_Posted_Time=df1)````
</code>```

Body:
I have three columns in my dataframe: Tweet Posted Time (UTC), Tweet Content, and Tweet Location. The "Tweet Posted Time (UTC)" column has date object in the format: 31 Mar 2020 10:49:01

My objective is to reformat the dataframe in such a way that the 'Tweet Posted Time (UTC)' column displays only the day, month and the year alone (such as 31-03-2020), to be able to plot a time-series graph, but my attempts result in the error below.

ValueError: time data '0       31 Mar 2020 10:49:01\n1       31 Mar 2020 05:48:43\n2       30 Mar 2020 05:38:50\n3       29 Mar 2020 21:19:23\n4       29 Mar 2020 20:28:22\n                ...         \n2488    02 Jan 2018 13:36:07\n2489    02 Jan 2018 10:33:21\n2490    01 Jan 2018 12:23:47\n2491    01 Jan 2018 06:03:51\n2492    01 Jan 2018 02:09:15\nName: Tweet Posted Time (UTC), Length: 2451, dtype: object' does not match format '%d %b %Y %H:%M:%S'

My code is below, can you tell me what I am doing wrong, please?

from datetime import datetime
import pandas as pd
import re #regular expression
from textblob import TextBlob
import string
import preprocessor as p

pd.set_option("expand_frame_repr", False)

df1 = pd.read_csv("C:/tweet_data.csv")

dataType = df1.dtypes
print(dataType)

# convert datetime object to string
old_formatDate = str(df1['Tweet Posted Time (UTC)'])

# extract day, month, and year and convert back to datetime object
date_TimeObject = datetime.strptime(old_formatDate, '%d %b %Y %H:%M:%S')
new_formatDate = date_TimeObject.strftime('%d-%m-%Y')
print(new_formatDate)

Body:
I researched and solved the problem by changing the data frame to panda series and then to datetime format. Then, applied dt.strftime.

df.columns = ['Tweet_Posted_Time', 'Tweet_Content', 'Tweet_Location']
print(df)

# Convert the date and time column (Tweet_Posted_Time) from panda data frame to Panda Series
df1 = pd.Series(df['Tweet_Posted_Time'])
print(df1)

# Convert the Panda Series to datetime format
df1 = pd.to_datetime(df1)
print(df1)

# convert the date column to new date format
df1 = df1.dt.strftime('%d-%m-%Y')
print(df1)

# Replace the Column "Tweet_Posted_Time" in the original data frame with the new data frame containing new date format
df.assign(Tweet_Posted_Time=df1)````


问:
How to display working digital clock using React
I want to render digital clock on the browser , i don't know where to use setInterval() function in my script and also the what will be the name of function used as a first argument.</p>

```<code><!DOCTYPE html>
    <html>
    <head>
        <title>My First App</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
    </head>
    <body>
    <div id="react-app"></div>
    <div id="clock-box"></div>

    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>

    <script type="text/jsx">

    class StoryBox extends React.Component{
            render(){
                return(<div> Hello World </div> );
            }
        }
    var target= document.getElementById('react-app');
    var clockTarget=document.getElementById('clock-box');
    ReactDOM.render(<StoryBox/>,target)

    class ClockFunction extends React.Component{
        render(){
            return(<div>
                <h1>Digital Clock</h1>
                <h2>
                {
                    new Date().toLocaleTimeString()
                    }
                </h2>
            </div>) ;
        }
    }

    ReactDOM.render(<ClockFunction />,clockTarget);

    </script>

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

答:
// A very simple React Digital clock </p>

```<code>    class App extends React.Component {
        componentDidMount() {
            setInterval(() => {
                this.getTime();
            })
        }
        constructor() {
            super();
            this.state = {
                time: "00:00:00:AM",
            }
        }
        getTime() {
            setInterval(() => {
                let date = new Date();
                let hour = date.getHours();
                let minute = date.getMinutes();
                let seconds = date.getSeconds();
                let ampm = this.hour >= 12 ? 'AM' : 'PM';
                hour = hour % 12;
                hour = hour ? hour : 12;
                hour = fullTime(hour);
                minute = fullTime(minute);
                seconds = fullTime(seconds);
                this.setState({
                    time: hour % 12 + ":" + minute + ":" + seconds + ":" +
                 ampm,
                });
                function fullTime(n) { return n < 10 ? "0" + n : n }

            }, 1000);
        }
        render() {
            return (
                <div className="container">
                    <h3>{this.state.time}</h3>
                </div>
            );
        }
    };

    ReactDOM.render(<App />, document.querySelector("#root"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to render digital clock on the browser , i don't know where to use setInterval() function in my script and also the what will be the name of function used as a first argument.

<!DOCTYPE html>

        <title>My First App</title>

Body:
// A very simple React Digital clock

    class App extends React.Component {
        componentDidMount() {
            setInterval(() => {
                this.getTime();
            })
        }
        constructor() {
            super();
            this.state = {
                time: "00:00:00:AM",
            }
        }
        getTime() {
            setInterval(() => {
                let date = new Date();
                let hour = date.getHours();
                let minute = date.getMinutes();
                let seconds = date.getSeconds();
                let ampm = this.hour >= 12 ? 'AM' : 'PM';
                hour = hour % 12;
                hour = hour ? hour : 12;
                hour = fullTime(hour);
                minute = fullTime(minute);
                seconds = fullTime(seconds);
                this.setState({
                    time: hour % 12 + ":" + minute + ":" + seconds + ":" +
                 ampm,
                });
                function fullTime(n) { return n < 10 ? "0" + n : n }

            }, 1000);
        }
        render() {
            return (
                <div className="container">
                    <h3>{this.state.time}</h3>
                </div>
            );
        }
    };

    ReactDOM.render(<App />, document.querySelector("#root"));


问:
`rotate()` does not set `BBAccumRotation`?
Illustrator uses the BBAccumRotation to track an object's rotation in radians 0.51246700.

BBAccumRotation IS set if object:

Is currently rotated - radians = value of rotation

Was previously rotated and is currently at 0 degrees - radians = 0.000000

Is rotated by dragging a handle

Is rotated via Object > Transform > Rotate

Is rotated via Properties panel > Rotate

BBAccumRotation IS NOT set if object:

Was rotated via a script using rotate()

Is rotated via live Effects > Distort & Transform > Transform > Rotate

Was rotated with a live effect and expanded

The question is, is there a native / baked-in way to have rotate() set BBAccumRotation?

While it is possible to add a BBAccumRotation tag to an object, it gets treated like any custom tag - it isn't recognized by Illustrator at its rotation tag, so it isn't reflected in places like the Properties panel.

I understand I could use a custom tag to track what rotate() is doing - I'd rather not go there.

It just seems like rotate() should set BBAccumRotation and I'm hoping there's something I don't know.

If you're interested in seeing this for yourself, here are some test scripts:

Check an object's tags:

if (app.documents.length == 0 ) {
    alert('Open a document to run this script.');
} else if (app.activeDocument.selection.length != 1)  {
    alert('Select 1 object to run this script.');
} else {
    TagAlert();
}

function TagAlert() {

    var iDoc = app.activeDocument;
    var aObj = iDoc.selection;
    var nObj = aObj.length;

    for ( i = 0; i < nObj; i++ ) {

        var obj = selection[0];
        var aTags = obj.tags;
        var nTags = aTags.length;

        if (nTags == 0) {

            alert('No tags.')

        } else {

            for ( i = 0; i < nObj; i++ ) {

                var obj = aObj[0];
                var aTags = obj.tags;
                var nTags = aTags.length;

                for ( i = 0; i < nTags; i++ ) {
                    tagName = aTags[i].name;
                    tagVal = aTags[i].value;
                    alert(tagName + ' ' + tagVal);
                }
            } // for

        } // if
    } // for

}; // TagAlert

```

<p>Rotate an object 30 degrees:</p>

<pre class="lang-js prettyprint-override"><code>if (app.documents.length == 0 ) {
    alert('Open a document to run this script.');
} else if (app.activeDocument.selection.length != 1)  {
    alert('Select 1 and only 1 object to run this script.');
} else {
    RotateObject();
}

function RotateObject() {

    var iDoc = app.activeDocument;
    var aObj = iDoc.selection;
    var nObj = aObj.length;

    for(i = 0; i < nObj; i++) {
        aObj[i].rotate(30);
    }

};
</code>```

Thank you in advance :)

答:
The [Tags].add() method returns a Tag object that, when renamed to match a built-in tag such as, 'BBAccumRotation' is recognized by illustrator normally, such as in the properties panel.

The below code rotates the first selected object -22 degrees using .rotate() then rotates the bounding box accordingly. Note that [Tags].value must be converted from a String to a Number. Also note that this feature does not appear to be documented.

```<code>#target illustrator

// convert back to radians
function deg2Rad( n ) {
    return n * ( Math.PI / 180 );
}
function rotateBBox( layer, degrees ) {
    // `tag` will revert to an exiting BBAccumRotation tag if it exists
    // if it doesn't exit, it is created
    var tag = null;
    var i;
    for ( i = 0; i < layer.tags.length; i++ ) {
        if ( layer.tags[i].name === 'BBAccumRotation' ) {
            tag = layer.tags[i];
        }
        i += 1;
    }
    if ( !tag ) {
        tag = layer.tags.add();
        tag.name = 'BBAccumRotation';
    }
    if ( tag.value ) {
        // tag.value must be converted from a String
        tag.value = Number( tag.value ) + deg2Rad( degrees );
    } else {
        tag.value = deg2Rad( degrees );
    }
}
function main() {
    var doc = app.activeDocument;
    var angle, sel;
    if ( doc.selection.length < 1 ) {
        alert( 'At least one (1) layer must be selected.' );
        return 1;
    } else {
        doc = app.activeDocument;
        sel = doc.selection[0];
        angle = -22;
        sel.rotate( angle );
        rotateBBox( sel, angle );
    }
}
main();```
```

Body:
Illustrator uses the BBAccumRotation to track an object's rotation in radians 0.51246700.

BBAccumRotation IS set if object:

Is currently rotated - radians = value of rotation

Was previously rotated and is currently at 0 degrees - radians = 0.000000

Is rotated by dragging a handle

Is rotated via Object > Transform > Rotate

Is rotated via Properties panel > Rotate

BBAccumRotation IS NOT set if object:

Was rotated via a script using rotate()

Is rotated via live Effects > Distort & Transform > Transform > Rotate

Was rotated with a live effect and expanded

The question is, is there a native / baked-in way to have rotate() set BBAccumRotation?

While it is possible to add a BBAccumRotation tag to an object, it gets treated like any custom tag - it isn't recognized by Illustrator at its rotation tag, so it isn't reflected in places like the Properties panel.

I understand I could use a custom tag to track what rotate() is doing - I'd rather not go there.

It just seems like rotate() should set BBAccumRotation and I'm hoping there's something I don't know.

If you're interested in seeing this for yourself, here are some test scripts:

Check an object's tags:

if (app.documents.length == 0 ) {
    alert('Open a document to run this script.');
} else if (app.activeDocument.selection.length != 1)  {
    alert('Select 1 object to run this script.');
} else {
    TagAlert();
}

function TagAlert() {

    var iDoc = app.activeDocument;
    var aObj = iDoc.selection;
    var nObj = aObj.length;

    for ( i = 0; i < nObj; i++ ) {

        var obj = selection[0];
        var aTags = obj.tags;
        var nTags = aTags.length;

        if (nTags == 0) {

            alert('No tags.')

        } else {

            for ( i = 0; i < nObj; i++ ) {

                var obj = aObj[0];
                var aTags = obj.tags;
                var nTags = aTags.length;

                for ( i = 0; i < nTags; i++ ) {
                    tagName = aTags[i].name;
                    tagVal = aTags[i].value;
                    alert(tagName + ' ' + tagVal);
                }
            } // for

        } // if
    } // for

}; // TagAlert

Rotate an object 30 degrees:

if (app.documents.length == 0 ) {
    alert('Open a document to run this script.');
} else if (app.activeDocument.selection.length != 1)  {
    alert('Select 1 and only 1 object to run this script.');
} else {
    RotateObject();
}

function RotateObject() {

    var iDoc = app.activeDocument;
    var aObj = iDoc.selection;
    var nObj = aObj.length;

    for(i = 0; i < nObj; i++) {
        aObj[i].rotate(30);
    }

};

Thank you in advance :)

Body:
The [Tags].add() method returns a Tag object that, when renamed to match a built-in tag such as, 'BBAccumRotation' is recognized by illustrator normally, such as in the properties panel.

The below code rotates the first selected object -22 degrees using .rotate() then rotates the bounding box accordingly. Note that [Tags].value must be converted from a String to a Number. Also note that this feature does not appear to be documented.

#target illustrator

// convert back to radians
function deg2Rad( n ) {
    return n * ( Math.PI / 180 );
}
function rotateBBox( layer, degrees ) {
    // `tag` will revert to an exiting BBAccumRotation tag if it exists
    // if it doesn't exit, it is created
    var tag = null;
    var i;
    for ( i = 0; i < layer.tags.length; i++ ) {
        if ( layer.tags[i].name === 'BBAccumRotation' ) {
            tag = layer.tags[i];
        }
        i += 1;
    }
    if ( !tag ) {
        tag = layer.tags.add();
        tag.name = 'BBAccumRotation';
    }
    if ( tag.value ) {
        // tag.value must be converted from a String
        tag.value = Number( tag.value ) + deg2Rad( degrees );
    } else {
        tag.value = deg2Rad( degrees );
    }
}
function main() {
    var doc = app.activeDocument;
    var angle, sel;
    if ( doc.selection.length < 1 ) {
        alert( 'At least one (1) layer must be selected.' );
        return 1;
    } else {
        doc = app.activeDocument;
        sel = doc.selection[0];
        angle = -22;
        sel.rotate( angle );
        rotateBBox( sel, angle );
    }
}
main();```


问:
How to flatten a nested dict and use inner values on collision
Question

For the following dictionary:

```<code>{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
</code>```

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

```<code>{k:v for (k,v) in d.items() if not k == 'remove_me'}
</code>```

yields:

```<code>{'id': 1, 'label': 'hello'}
</code>```

not exactly what I need as I'm dropping the nested dict.

Desired output:

```<code>{'id': 1, 'label': 'hello','keep_me': 52}
</code>```

答:
You can try

```<code>d = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
for k, v in list(d.items()):
    if isinstance(v, dict):
        for i in v:
           if isinstance(v[i], dict):
               d.update(v[i])
           else:
               d.update(v)
        del d[k]
print(d)
</code>```

Output

```<code>{'id': 1, 'label': 'hello', 'keep_me': 52}
</code>```

This code will check if the values of each item are a dict and if so it will update the dict with the inner result and remove the current key value from the main dict.
By that, in the end, the d dict will stay only with a key and a string value without nested dicts.

Body:
Question

For the following dictionary:

{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

{k:v for (k,v) in d.items() if not k == 'remove_me'}

yields:

{'id': 1, 'label': 'hello'}

not exactly what I need as I'm dropping the nested dict.

Desired output:

{'id': 1, 'label': 'hello','keep_me': 52}

Body:
You can try

d = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
for k, v in list(d.items()):
    if isinstance(v, dict):
        for i in v:
           if isinstance(v[i], dict):
               d.update(v[i])
           else:
               d.update(v)
        del d[k]
print(d)

Output

{'id': 1, 'label': 'hello', 'keep_me': 52}

This code will check if the values of each item are a dict and if so it will update the dict with the inner result and remove the current key value from the main dict.
By that, in the end, the d dict will stay only with a key and a string value without nested dicts.


问:
Using Json properties in where clause laravel
I have this table discounts were I have a column called rules which is a json and it has book array inside it like this

Table Discounts:

```<code>Column Rules:

rules:"{\"books\":[1,2],others..}
</code>```

Now I want to check through Books table wheather that particular book consist in any discounts->rules->books or not !

What I have Tried is this:

```<code>$discount = Discount:: whereJsonContains('rules->books',$this->id)->get();
</code>```

But this is returning me empty array .

答:
The data types have to match:</p>

```<code>// [1, 2]
Discount::whereJsonContains('rules->books', 1)   // Works.
Discount::whereJsonContains('rules->books', '1') // Doesn't work.

// ["1", "2"]
Discount::whereJsonContains('rules->books', '1') // Works.
Discount::whereJsonContains('rules->books', 1)   // Doesn't work.
</code>```

Body:
I have this table discounts were I have a column called rules which is a json and it has book array inside it like this

Table Discounts:

Column Rules:

rules:"{\"books\":[1,2],others..}

Now I want to check through Books table wheather that particular book consist in any discounts->rules->books or not !

What I have Tried is this:

$discount = Discount:: whereJsonContains('rules->books',$this->id)->get();

But this is returning me empty array .

Body:
The data types have to match:

// [1, 2]
Discount::whereJsonContains('rules->books', 1)   // Works.
Discount::whereJsonContains('rules->books', '1') // Doesn't work.

// ["1", "2"]
Discount::whereJsonContains('rules->books', '1') // Works.
Discount::whereJsonContains('rules->books', 1)   // Doesn't work.


问:
Parsing a tab-delimited text file to replace columns with one vertical list (Python)
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

```<code>for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine
</code>```

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

```<code>while segmentedLine:
    item = segmentedLine.split("\t")
    print item
</code>```

Thanks very much for any input.

答:
So you have

```<code>foo<tab>bar<tab>baz
bla<tab>bla<tab>bla
</code>```

and you want it to be

```<code>foo
bar
baz
bla
bla
bla
</code>```

Right?

Then you can just do

```<code>with open("myfile.txt", "r") as f:
    text = f.read().replace("\t", "\n")
</code>```

Now text is a single string. If you want a list of all the items instead (["foo", "bar", "baz", "bla", "bla", "bla"]), use

```<code>text = f.read().replace("\t", "\n").split("\n")
</code>```

Body:
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

while segmentedLine:
    item = segmentedLine.split("\t")
    print item

Thanks very much for any input.

Body:
So you have

foo<tab>bar<tab>baz
bla<tab>bla<tab>bla

and you want it to be

foo
bar
baz
bla
bla
bla

Right?

Then you can just do

with open("myfile.txt", "r") as f:
    text = f.read().replace("\t", "\n")

Now text is a single string. If you want a list of all the items instead (["foo", "bar", "baz", "bla", "bla", "bla"]), use

text = f.read().replace("\t", "\n").split("\n")


问:
MIME type error when applying CSS files with GO Gorilla mux server
I'm having issues with including css files in a GO webserver using Gorilla Mux. I get the following error in the Google Chrome console:

```<code>forum:1 Refused to apply style from 'http://localhost:8080/css/forum.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
</code>```

I understand that a lot of people fail using a FileServer by handling the "/" wrong, but this also won't work for me. My file struture is as follow:
file structure
When I run the server, I execute in cmd: go run src/main.go. I also tried running it in the src folder. But that won't work too. In the HTML file, I add the css file with

```<code><link rel="stylesheet" type="text/css" href="/css/forum.css" />
</code>```

My GO code is below. I tried handling the FileServer in two ways, one of them is commented out above the other. Both won't work. Everything else is working except the FileServer.

```<code>package main

import (
    "fmt"
    "net/http"
    "html/template"

    "github.com/gorilla/mux"
)

var templates *template.Template

func main() {
    r := mux.NewRouter()

    templates = template.Must(template.ParseGlob("src/templates/*.html"))
    cssHandler := http.FileServer(http.Dir("./static/css"))

    r.HandleFunc("/home", homeGetHandler).Methods("GET")
    r.HandleFunc("/home", homePostHandler).Methods("POST")
    r.HandleFunc("/forum", forumGetHandler).Methods("GET")
    r.HandleFunc("/forum", forumPostHandler).Methods("POST")

    http.Handle("/forum", r)
    http.Handle("/home", r)
    // http.Handle("/css/", http.StripPrefix("/src/static/css/", cssHandler))
    r.PathPrefix("/css/").Handler(http.StripPrefix("/src/static/css/", cssHandler))

    http.ListenAndServe(":8080", nil)
}

func homeGetHandler(w http.ResponseWriter, r *http.Request) {
    templates.ExecuteTemplate(w, "home.html", nil)
}

func homePostHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    comment := r.PostForm.Get("comment")
    fmt.Println(comment)
    http.Redirect(w, r,"/home", 302)
}

func forumGetHandler(w http.ResponseWriter, r *http.Request) {
    templates.ExecuteTemplate(w, "forum.html", nil)
}

func forumPostHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    comment := r.PostForm.Get("post")
    fmt.Println(comment)
    http.Redirect(w, r,"/forum", 302)
}
</code>```

[SOLUTION]
I found the answer:

```<code>http.Handle("/forum", r)
http.Handle("/home", r)
</code>```

should just be:

```<code>http.Handle("/",r)
</code>```

答:
The problem is that your csshandler returns the contents of the file with Content-Type set to "text/plain". You have to set it to "text/css" to have the browser interpret it as a CSS file. You can set the content type before returning the file contents using a middleware-like function:</p>

```<code>func SetHeader(header,value string, handle http.Handler) func(http.ResponseWriter,*http.Request) {
   return func(w http.ResponseWriter,req *http.Request) {
       w.Header().Set(header,value)
       handle.ServeHTTP(w,req)
   }
}

r.PathPrefix("/css/").HandlerFunc(SetHeader("Content-Type","text/css",http.StripPrefix("/src/static/css/", cssHandler)))

</code>```

Body:
I'm having issues with including css files in a GO webserver using Gorilla Mux. I get the following error in the Google Chrome console:

forum:1 Refused to apply style from 'http://localhost:8080/css/forum.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

I understand that a lot of people fail using a FileServer by handling the "/" wrong, but this also won't work for me. My file struture is as follow:
file structure
When I run the server, I execute in cmd: go run src/main.go. I also tried running it in the src folder. But that won't work too. In the HTML file, I add the css file with

<link rel="stylesheet" type="text/css" href="/css/forum.css" />

My GO code is below. I tried handling the FileServer in two ways, one of them is commented out above the other. Both won't work. Everything else is working except the FileServer.

package main

import (
    "fmt"
    "net/http"
    "html/template"

    "github.com/gorilla/mux"
)

var templates *template.Template

func main() {
    r := mux.NewRouter()

    templates = template.Must(template.ParseGlob("src/templates/*.html"))
    cssHandler := http.FileServer(http.Dir("./static/css"))

    r.HandleFunc("/home", homeGetHandler).Methods("GET")
    r.HandleFunc("/home", homePostHandler).Methods("POST")
    r.HandleFunc("/forum", forumGetHandler).Methods("GET")
    r.HandleFunc("/forum", forumPostHandler).Methods("POST")

    http.Handle("/forum", r)
    http.Handle("/home", r)
    // http.Handle("/css/", http.StripPrefix("/src/static/css/", cssHandler))
    r.PathPrefix("/css/").Handler(http.StripPrefix("/src/static/css/", cssHandler))

    http.ListenAndServe(":8080", nil)
}

func homeGetHandler(w http.ResponseWriter, r *http.Request) {
    templates.ExecuteTemplate(w, "home.html", nil)
}

func homePostHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    comment := r.PostForm.Get("comment")
    fmt.Println(comment)
    http.Redirect(w, r,"/home", 302)
}

func forumGetHandler(w http.ResponseWriter, r *http.Request) {
    templates.ExecuteTemplate(w, "forum.html", nil)
}

func forumPostHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    comment := r.PostForm.Get("post")
    fmt.Println(comment)
    http.Redirect(w, r,"/forum", 302)
}

[SOLUTION]
I found the answer:

http.Handle("/forum", r)
http.Handle("/home", r)

should just be:

http.Handle("/",r)

Body:
The problem is that your csshandler returns the contents of the file with Content-Type set to "text/plain". You have to set it to "text/css" to have the browser interpret it as a CSS file. You can set the content type before returning the file contents using a middleware-like function:

func SetHeader(header,value string, handle http.Handler) func(http.ResponseWriter,*http.Request) {
   return func(w http.ResponseWriter,req *http.Request) {
       w.Header().Set(header,value)
       handle.ServeHTTP(w,req)
   }
}

r.PathPrefix("/css/").HandlerFunc(SetHeader("Content-Type","text/css",http.StripPrefix("/src/static/css/", cssHandler)))


答:
What's because you're serving your css file with wrong MIME type, you should set right header for css. Use:</p>

```<code>func serveCss(w http.ResponseWriter, r *http.Request) {
  // some code here
  w.Header().Add("Content-Type", "text/css")
  // some code here
}
</code>```

Title: MIME type error when applying CSS files with GO Gorilla mux server

Body:
What's because you're serving your css file with wrong MIME type, you should set right header for css. Use:

func serveCss(w http.ResponseWriter, r *http.Request) {
  // some code here
  w.Header().Add("Content-Type", "text/css")
  // some code here
}


问:
Reason and suggestion for: TypeError: not all arguments converted during string formatting
Why this error is occurring and how can I fix it?
I am trying to write this code as a practice in codewars.

```<code>def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers= list(splitted_num)#splitted string was already a list
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds.index[0, 1] if len(odds)<len(evens) else evens[0, 1])

numbers= ("2 4 7 8 10")
print(iq_test(numbers))
</code>```

ERROR:

```<code>Traceback (most recent call last):
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 13, in <module>
    print(iq_test(numbers))
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in iq_test
    odds = [x for x in list_numbers if x%2!=0]
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in <listcomp>
    odds = [x for x in list_numbers if x%2!=0]
TypeError: not all arguments converted during string formatting
</code>```

This is the question:

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

答:
If this was your objective

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

This should do it

```<code>def iq_test(numbers):
    splitted_num=numbers.split()
    # to make all the strings to characters
    list_numbers = list(map(int,splitted_num))
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    # you're trying to return the index of the different number among the given list
    # + 1 is that for index starts at 0 so the position will be index + 1
        return list_numbers.index(odds[0])+1 if len(odds) == 1 else list_numbers.index(evens[0])+1

numbers = ("2 4 7 8 10")
print(iq_test(numbers))
</code>```

Body:
Why this error is occurring and how can I fix it?
I am trying to write this code as a practice in codewars.

def iq_test(numbers):
    splitted_num=numbers.split()
    list_numbers= list(splitted_num)#splitted string was already a list
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    return (odds.index[0, 1] if len(odds)<len(evens) else evens[0, 1])

numbers= ("2 4 7 8 10")
print(iq_test(numbers))

ERROR:

Traceback (most recent call last):
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 13, in <module>
    print(iq_test(numbers))
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in iq_test
    odds = [x for x in list_numbers if x%2!=0]
  File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in <listcomp>
    odds = [x for x in list_numbers if x%2!=0]
TypeError: not all arguments converted during string formatting

This is the question:

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

Body:
If this was your objective

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. Question: ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

This should do it

def iq_test(numbers):
    splitted_num=numbers.split()
    # to make all the strings to characters
    list_numbers = list(map(int,splitted_num))
    odds = [x for x in list_numbers if x%2!=0]
    evens= [x for x in list_numbers if x%2==0]
    # you're trying to return the index of the different number among the given list
    # + 1 is that for index starts at 0 so the position will be index + 1
        return list_numbers.index(odds[0])+1 if len(odds) == 1 else list_numbers.index(evens[0])+1

numbers = ("2 4 7 8 10")
print(iq_test(numbers))


问:
How to acces user detail in template in django
I want check whether logged in  user is doctor or patient i tried the following method to check that thing,but did not succeed can any one help me.

model.py

forms.py

index.html

output

or what does this error means:

```<code>Could not parse the remainder: '=='Doctor'' from 'user.user_type=='Doctor''
</code>```

答:
Make sure you have spaces around ==. It should be user.user_type == 'Doctor' instead of user.user_type=='Doctor'

Looks like you also have a typo in index.html.

Change user.user_type=='Pateint' to user.user_type == 'Patient'. Note the spaces around ==.

Body:
I want check whether logged in  user is doctor or patient i tried the following method to check that thing,but did not succeed can any one help me.

model.py

forms.py

index.html

output

or what does this error means:

Could not parse the remainder: '=='Doctor'' from 'user.user_type=='Doctor''


问:
Question on "smart" replacing in mathematica
How do I tell mathematica to do this replacement smartly? (or how do I get smarter at telling mathematica to do what i want)

```<code>expr = b + c d + ec + 2 a;
expr /. a + b :> 1

Out = 2 a + b + c d + ec
</code>```

I expect the answer to be a + cd + ec + 1. And before someone suggests, I don't want to do a :> 1 - b, because for aesthetic purposes, I'd like to have both a and b in my equation as long as the a+b = 1 simplification cannot be made.

In addition, how do I get it to replace all instances of 1-b, -b+1 or -1+b, b-1 with a or -a respectively and vice versa?

Here's an example for this part:

```<code>expr = b + c (1 - a) + (-1 + b)(a - 1) + (1 -a -b) d + 2 a
</code>```

答:
You can use a customised version of FullSimplify by supplying your own transformations to FullSimplify and let it figure out the details:

```<code>In[1]:= MySimplify[expr_,equivs_]:= FullSimplify[expr,
          TransformationFunctions ->
            Prepend[
              Function[x,x-#]&/@Flatten@Map[{#,-#}&,equivs/.Equal->Subtract],
              Automatic
            ]
        ]
In[2]:= MySimplify[2a+b+c*d+e*c, {a+b==1}]
Out[2]= a + c(d + e) + 1
</code>```

equivs/.Equal->Subtract turns given equations into expressions equal to zero (e.g. a+b==1 -> a+b-1). Flatten@Map[{#,-#}&, ] then constructs also negated versions and flattens them into a single list. Function[x,x-#]& /@ turns the zero expressions into functions, which subtract the zero expressions (the #) from what is later given to them (x) by FullSimplify.

It may be necessary to specify your own ComplexityFunction for FullSimplify, too, if your idea of simple differs from FullSimplify's default ComplexityFunction (which is roughly equivalent to LeafCount), e.g.:

```<code>MySimplify[expr_, equivs_] := FullSimplify[expr,
  TransformationFunctions ->
    Prepend[
      Function[x,x-#]&/@Flatten@Map[{#,-#}&,equivs/.Equal->Subtract],
      Automatic
    ],
  ComplexityFunction -> (
    1000 LeafCount[#] +
    Composition[
      Total,Flatten,Map[ArrayDepth[#]#&,#]&,CoefficientArrays
    ][#] &
  )
]
</code>```

In your example case, the default ComplexityFunction works fine, though.

Body:
How do I tell mathematica to do this replacement smartly? (or how do I get smarter at telling mathematica to do what i want)

expr = b + c d + ec + 2 a;
expr /. a + b :> 1

Out = 2 a + b + c d + ec

I expect the answer to be a + cd + ec + 1. And before someone suggests, I don't want to do a :> 1 - b, because for aesthetic purposes, I'd like to have both a and b in my equation as long as the a+b = 1 simplification cannot be made.

In addition, how do I get it to replace all instances of 1-b, -b+1 or -1+b, b-1 with a or -a respectively and vice versa?

Here's an example for this part:

expr = b + c (1 - a) + (-1 + b)(a - 1) + (1 -a -b) d + 2 a

Body:
You can use a customised version of FullSimplify by supplying your own transformations to FullSimplify and let it figure out the details:

In[1]:= MySimplify[expr_,equivs_]:= FullSimplify[expr,
          TransformationFunctions ->
            Prepend[
              Function[x,x-#]&/@Flatten@Map[{#,-#}&,equivs/.Equal->Subtract],
              Automatic
            ]
        ]
In[2]:= MySimplify[2a+b+c*d+e*c, {a+b==1}]
Out[2]= a + c(d + e) + 1

equivs/.Equal->Subtract turns given equations into expressions equal to zero (e.g. a+b==1 -> a+b-1). Flatten@Map[{#,-#}&, ] then constructs also negated versions and flattens them into a single list. Function[x,x-#]& /@ turns the zero expressions into functions, which subtract the zero expressions (the #) from what is later given to them (x) by FullSimplify.

It may be necessary to specify your own ComplexityFunction for FullSimplify, too, if your idea of simple differs from FullSimplify's default ComplexityFunction (which is roughly equivalent to LeafCount), e.g.:

MySimplify[expr_, equivs_] := FullSimplify[expr,
  TransformationFunctions ->
    Prepend[
      Function[x,x-#]&/@Flatten@Map[{#,-#}&,equivs/.Equal->Subtract],
      Automatic
    ],
  ComplexityFunction -> (
    1000 LeafCount[#] +
    Composition[
      Total,Flatten,Map[ArrayDepth[#]#&,#]&,CoefficientArrays
    ][#] &
  )
]

In your example case, the default ComplexityFunction works fine, though.


问:
Vert.x WriteStream setWriteQueueMaxSize
I am new for Vert.x. When I read writestream in the article from https://vertx.io/docs/vertx-core/java/ as following:

```<code>setWriteQueueMaxSize: set the number of object at which the write queue is
 considered full, and the method writeQueueFull returns true. Note that,
when the write queue is considered full, if write is called the data will
still be accepted and queued. The actual number depends on the stream
implementation, for Buffer the size represents the actual number of bytes
written and not the number of buffers.
</code>```

especially this statement - "Note that, when the write queue is considered full, if write is called the data will still be accepted and queued.", from this statement, I have a few of questions:

(1) Is there any size limitation for writing to stream? I mean, such as event bus, how many messages can be written to event bus? Does it depend on memory? suppose I keep on writing messages to event bus and message doesn't be consumed, does it cause Out of Memory in Java?

(2) If there is some limitation for writing, where and how can I check default queue size? Such as, I want to know the default queue size of Vert.x KafkaProducer, where can I check it?

Any ideas are appreciated.

答:
There are actually three separate questions there, but I'll give it a shot anyway:

Is there any size limitation for writing to stream?

That depends on the stream implementation. But I've yet to see one implementation that actually uses WriteQueueMaxSize

how many messages can be written to event bus? Does it depend on memory?

EventBus is a special case. If nobody is consuming from EventBus, it will simply drop messages, so in such a trivial case, an infinite number could be written. But if there are consumers, and they're slow, yes, eventually you'll run out of memory. EventBus implementation currently doesn't do anything with WriteQueueMaxSize

If there is some limitation for writing, where and how can I check default queue size? Such as, I want to know the default queue size of Vert.x KafkaProducer, where can I check it?

All Vert.x project are open source, so you'll usually find them on GitHub (or other open source repo, but I don't remember any that are not on GitHub, actually).

Particularly for Vert.x KafkaProducer, you can see the code here:

https://github.com/vert-x3/vertx-kafka-client/blob/1720d5a6792f70509fd7249a47ab50b930cee7a7/src/main/java/io/vertx/kafka/client/producer/impl/KafkaProducerImpl.java#L217

Title: Vert.x WriteStream setWriteQueueMaxSize

Body:
I am new for Vert.x. When I read writestream in the article from https://vertx.io/docs/vertx-core/java/ as following:

setWriteQueueMaxSize: set the number of object at which the write queue is
 considered full, and the method writeQueueFull returns true. Note that,
when the write queue is considered full, if write is called the data will
still be accepted and queued. The actual number depends on the stream
implementation, for Buffer the size represents the actual number of bytes
written and not the number of buffers.

especially this statement - "Note that, when the write queue is considered full, if write is called the data will still be accepted and queued.", from this statement, I have a few of questions:

(1) Is there any size limitation for writing to stream? I mean, such as event bus, how many messages can be written to event bus? Does it depend on memory? suppose I keep on writing messages to event bus and message doesn't be consumed, does it cause Out of Memory in Java?

(2) If there is some limitation for writing, where and how can I check default queue size? Such as, I want to know the default queue size of Vert.x KafkaProducer, where can I check it?

Any ideas are appreciated.


问:
Ask guidance to make video web application
I'm trying to make web application that can
upload file via 'html input file',
play video on certain html,
and seek time code where users want to play.

I want to make those features based on node.js and express.

I found some tutorials, but they are based on system file, not from user's input.

```<code>const { createServer } = require('http');
const {
  stat,
  createReadStream,
  createWriteStream
} = require('fs');
const { promisify } = require('util');
const fileName = '../../powder-day.mp4';
const fileInfo = promisify(stat);
const multiparty = require('multiparty');

const respondWithVideo = async (req, res) => {
  const { size } = await fileInfo(fileName);
  await console.log(fileInfo(fileName));
  const range = req.headers.range;
  if (range) {
    let [start, end] = range.replace(/bytes=/, '').split('-');
    start = parseInt(start, 10);
    end = end ? parseInt(end, 10) : size - 1;
    res.writeHead(206, {
       'Content-Range': `bytes ${start}-${end}/${size}`,
       'Accept-Ranges': 'bytes',
       'Content-Length': (end-start) + 1,
       'Content-Type': 'video/mp4'
    })
    createReadStream(fileName, { start, end }).pipe(res);
  } else {
    res.writeHead(200, {
      'Content-Length': size,
      'Content-Type': 'video/mp4'
    });
    createReadStream(fileName).pipe(res);
  }
}

createServer((req, res) => {
  if (req.method === 'POST') {
    let form = new multiparty.Form();
    form.on('part', (part) => {
      part.pipe(createWriteStream(`./${part.filename}`))
        .on('close', () => {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(`<h1>File uploaded: ${part.filename}</h1>`);
        })
    });
    form.parse(req);
  } else if (req.url === '/video') {
    respondWithVideo(req, res);
  } else {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`
      <form enctype="multipart/form-data" method="POST" action="/">
        <input type="file" name="upload-file" />
        <button>Upload File</button>
      </form>
    `);
  }

}).listen(3000, () => console.log('server running - 3000'));
</code>```

Is there any guide to do stream video with buffer string, not from a system path?

please advise

答:
Why not just use the regular video HTML5 video tag?  if your video is: https://example.com/myvideo.mp4

you can just append #t=10,20 and the video will start at 10 seconds, and stop 10 seconds later (20 seconds into the video).

It would look like this:
https://example.com/myvideo.mp4#t=10,20

source: HTML5 Rocks

Body:
I'm trying to make web application that can
upload file via 'html input file',
play video on certain html,
and seek time code where users want to play.

I want to make those features based on node.js and express.

I found some tutorials, but they are based on system file, not from user's input.

const { createServer } = require('http');
const {
  stat,
  createReadStream,
  createWriteStream
} = require('fs');
const { promisify } = require('util');
const fileName = '../../powder-day.mp4';
const fileInfo = promisify(stat);
const multiparty = require('multiparty');

const respondWithVideo = async (req, res) => {
  const { size } = await fileInfo(fileName);
  await console.log(fileInfo(fileName));
  const range = req.headers.range;
  if (range) {
    let [start, end] = range.replace(/bytes=/, '').split('-');
    start = parseInt(start, 10);
    end = end ? parseInt(end, 10) : size - 1;
    res.writeHead(206, {
       'Content-Range': `bytes ${start}-${end}/${size}`,
       'Accept-Ranges': 'bytes',
       'Content-Length': (end-start) + 1,
       'Content-Type': 'video/mp4'
    })
    createReadStream(fileName, { start, end }).pipe(res);
  } else {
    res.writeHead(200, {
      'Content-Length': size,
      'Content-Type': 'video/mp4'
    });
    createReadStream(fileName).pipe(res);
  }
}

createServer((req, res) => {
  if (req.method === 'POST') {
    let form = new multiparty.Form();
    form.on('part', (part) => {
      part.pipe(createWriteStream(`./${part.filename}`))
        .on('close', () => {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(`<h1>File uploaded: ${part.filename}</h1>`);
        })
    });
    form.parse(req);
  } else if (req.url === '/video') {
    respondWithVideo(req, res);
  } else {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`
      <form enctype="multipart/form-data" method="POST" action="/">
        <input type="file" name="upload-file" />
        <button>Upload File</button>
      </form>
    `);
  }

}).listen(3000, () => console.log('server running - 3000'));

Is there any guide to do stream video with buffer string, not from a system path?

please advise


问:
Load more posts with AJAX and also add pagination in URL
On load more button, posts load without page load using AJAX, but wanted to implement Wordpress pagination on load more along with URL changing. Suggestions are welcome.</p>

答:
```<code>    /* Category/tag page Masonry Grid */
    var $mgrid = $( '.post-grid' ).masonry();
    $mgrid.masonry( {
        itemSelector: '.post-outer',
    } );

    /* ------------------ Load More Posts Category/tag page ------------------ */
    $( document ).on( 'click', '#post-button', function(e) {
        e.preventDefault();
        var offset = $( this ).attr( 'data-value' );
        var cat = $( this ).attr( 'data-cat' ); //load more button attribute
        var tag = $( this ).attr( 'data-tag' ); //load more button attribute
        var page = $( this ).attr( 'data-page' ); //load more button attribute
        var $content;
        $.ajax( {
            type: "post",
            async: false,
            dataType: "json",
            url: localizeObj.ajaxurl, //localize script in functions.php
            data: {
                action: 'fetch_posts', //ajax load more function in functions.php
                offset: offset,
                cat: cat,
                tag: tag,
                page: page,
                search_term: localizeObj.search_term,
                current_page: localizeObj.current_page
            },
            beforeSend: function() {
            },
            success: function(response) {
                /* Adding page numbers on ajax load more */
                var pathname = window.location.pathname;

                if ( response.success == 'yes' ) {
                    $content = $(response.posts);
                    $( '.post-masonry-grid' ).append( $content ).masonry( 'appended', $content );
                    page = parseInt(page) + 1;
                    offset = parseInt(offset) + 6;

                    $('.post-grid-outer').each( function() {
                        $('.post-grid-outer').addClass(offset);
                    });

                    $( '#post-grid-button' ).attr( 'data-value', offset );
                    $( '#post-grid-button' ).attr( 'data-page', page );

                    var page_num = '';
                    if(page <= 2) {
                        var page_num = 'page/'+ page;
                    } else {
                        var page_num =  page;
                    }
                    window.history.pushState("URL", "Title", page_num); // Add page numbers to URL

                } else {
                    $( '#post-button' ).hide();
                }
            },
            complete : function() {
            }
        } );
    } );
</code>```


问:
Replace (Blank) values in PowerBI with Zero
I'm trying to set up a Hospitalization Dashboard within PowerBI and I'm using the KPI indicator to showcase the number of patients in that particular location.

My Source Data looks as follows:

```<code>Full Name | ID | Location
Patient A | xxxxxA | ITU
Patient B | xxxxxA | IDU
</code>```

Then I generate a KPI indicator that if is Count of Location and filtered for anything that contains 'ITU'. At times, this generates a '(BLANK)' value in the indicator and I would like to know how to replace this with zero. Somehow can't figure out where to get started, if to do a measure etc.

The following questions somehow didn't help:

PowerBI - Replace Zeros with Blanks

PowerBI Differentiate BLANK value and 0 value

Replacing Blank values with Zero using Dax

Any help would be appreciated!

答:
If your KPI measure is numeric, then you can usually just add + 0 to the measure since

```<code>BLANK() + 0 = 0
</code>```

Body:
I'm trying to set up a Hospitalization Dashboard within PowerBI and I'm using the KPI indicator to showcase the number of patients in that particular location.

My Source Data looks as follows:

Full Name | ID | Location
Patient A | xxxxxA | ITU
Patient B | xxxxxA | IDU

Then I generate a KPI indicator that if is Count of Location and filtered for anything that contains 'ITU'. At times, this generates a '(BLANK)' value in the indicator and I would like to know how to replace this with zero. Somehow can't figure out where to get started, if to do a measure etc.

The following questions somehow didn't help:

PowerBI - Replace Zeros with Blanks

PowerBI Differentiate BLANK value and 0 value

Replacing Blank values with Zero using Dax

Any help would be appreciated!

Body:
If your KPI measure is numeric, then you can usually just add + 0 to the measure since

BLANK() + 0 = 0


问:
Set type for function parameters?
Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:

```<code>function myFunction(Date myDate, String myString)
{
    //do stuff
}
</code>```

Thank you!

Update: Being that the answer is a resounding "no," if I want myDate to be treated as a date (in order to call date functions on it), I have to cast it as a date inside the function or set a new variable of type Date to it?

答:
TypeScript is one of the best solutions for now.

TypeScript extends JavaScript by adding types to the language.

typescript version demo

```<code>// type alias
type myDateType = Date;
type myStringType = string;

function myFunction(myDate: myDateType, myString: myStringType) {
  // do stuff
  console.log(`myDate =`, myDate);
  console.log(`myString =`, myString);
}

myFunction(new Date(), 'TypeScript is awesome!');

</code>```

try this playground online

refs

https://www.typescriptlang.org/

Title: Set type for function parameters?

Body:
Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:

function myFunction(Date myDate, String myString)
{
    //do stuff
}

Thank you!

Update: Being that the answer is a resounding "no," if I want myDate to be treated as a date (in order to call date functions on it), I have to cast it as a date inside the function or set a new variable of type Date to it?

Body:
TypeScript is one of the best solutions for now.

TypeScript extends JavaScript by adding types to the language.

typescript version demo

// type alias
type myDateType = Date;
type myStringType = string;

function myFunction(myDate: myDateType, myString: myStringType) {
  // do stuff
  console.log(`myDate =`, myDate);
  console.log(`myString =`, myString);
}

myFunction(new Date(), 'TypeScript is awesome!');

try this playground online

refs

https://www.typescriptlang.org/


问:
Client side showing , hiding is risky
I have a div which contains a button .I am initially setting div display:none & depending upon the user rights i am showing it to user using javascript.

```<code><div id="mydiv" style="display:none">
    <asp:Button id="btn" runat="server"/>
</div>

PageMethods.GetRights(onsuccess);

function onsuccess(result){
   if(result.isaccessible)
   {
      $("#mydiv").show();
   }
}
</code>```

Is Showing,Hiding at client risky. I dont want to use updatepanel if it is risky what is an alternative to this i have?

答:
You'll need to re-check if the user has access to this functonality when they click the butotn and the request is posted to your server..

An easier way to handle this is to add a class to the body

```<code>< body class="logged_in" >
</code>```

if they are logged in..

Then css rules

```<code>#mydiv { display: none; }
.logged_in #mydiv { display: block; }
</code>```

Title: Client side showing , hiding is risky

Body:
I have a div which contains a button .I am initially setting div display:none & depending upon the user rights i am showing it to user using javascript.

    <asp:Button id="btn" runat="server"/>

PageMethods.GetRights(onsuccess);

function onsuccess(result){
   if(result.isaccessible)
   {
      $("#mydiv").show();
   }
}

Is Showing,Hiding at client risky. I dont want to use updatepanel if it is risky what is an alternative to this i have?

Body:
You'll need to re-check if the user has access to this functonality when they click the butotn and the request is posted to your server..

An easier way to handle this is to add a class to the body

< body class="logged_in" >

if they are logged in..

Then css rules

#mydiv { display: none; }
.logged_in #mydiv { display: block; }


答:
Flattening a dictionary is a whole thing in itself. Does this accomplish your goal? (Untested, I'm typing on my phone a.t.m.):</p>

```<code>def flattenDict(myDict, blacklist):
  returnDict = {}
  for key, val in myDict:
    If isinstance(val, "dict"):
       myDict.update(flattenDict(val))
    elif key in blacklist:
       continue
    elif val in blacklist:
        continue
    returnDict[key] = val
  return returnDict

cleanDict = flattenDict(myDict, ["remove_me", "world"])
</code>```

Title: How to flatten a nested dict and use inner values on collision

Body:
Question

For the following dictionary:

{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

{k:v for (k,v) in d.items() if not k == 'remove_me'}

yields:

{'id': 1, 'label': 'hello'}

not exactly what I need as I'm dropping the nested dict.

Desired output:

{'id': 1, 'label': 'hello','keep_me': 52}

Body:
Flattening a dictionary is a whole thing in itself. Does this accomplish your goal? (Untested, I'm typing on my phone a.t.m.):

def flattenDict(myDict, blacklist):
  returnDict = {}
  for key, val in myDict:
    If isinstance(val, "dict"):
       myDict.update(flattenDict(val))
    elif key in blacklist:
       continue
    elif val in blacklist:
        continue
    returnDict[key] = val
  return returnDict

cleanDict = flattenDict(myDict, ["remove_me", "world"])