问:
How do I add a Vertical Scrollbar to Telerik RadLegendControl within RadCartesianChart?
I am developing a program within UWP that will have the ability to chart data on-screen, and must support the potential that a user may want to chart a large number of series on it.

The Chart that I am using is Telerik's RadCartesianChart and I am using a RadLegendControl for showing the legend for the chart. This is laid out on a Grid that has two Columns and one Row. In the first Column (0) is the RadLegendControl. In the second Column (1) is the RadCartesianChart.

When a large number of Series are drawn, this can result in the Legend going down below the bottom of the app, cutting off the remaining items in the legend. This is basically an "excessive" example of the usage of this chart and I'm wanting to make sure it can function effectively when put under this kind of use.

Is there a way to add a scrollbar to the Legend Control so that a user can scroll through the legend? Or should I be looking at a different method for showing the legend?

This is for a program made within UWP that is currently targeting a minimum version of Windows 10 1803 and aiming for 1809, using Visual Studio 2019.

I made a post over on Telerik's forum asking this question and it was suggested that there is possibly an external component that is letting the legend extend to its full height off-screen and they provided a possible solution in trying to set an explicit maximum height to see the scrollbar appear when it reaches that upper bound. As such, in the XAML I set MaxHeight="300", which is much smaller than the average Chart's legend would require, such that I could easily see if the Scrollbar appeared. When I tried this, no Scrollbar appeared.

Originally I was having the RadLegendControl being drawn utilising a StackPanel to reorder the Legend to display from top-down instead of left-to-right so that it could fit alongside the Chart. I suspected that the StackPanel's internal ScrollViewer may have been conflicting with the RadLegendControl's internal ScrollViewer. I removed the StackPanel layout to ensure that it could not conflict to see if a ScrollViewer would then appear. It did not (I tested a horizontal one as well, to no success).

I have tried other solutions such as binding the MaxHeight property of the RadLegendControl to the Height or ActualHeight of the Grid row that it is on, explicitly setting VerticalScrollMode to Enabled and VerticalScrollVisibility to Visible.

This is the RadLegendControl code within XAML, still with the MaxHeight set explicitly to 300:

<telerikPrimitives:RadLegendControl
    x:Name="LegendForChart"
    LegendProvider="{Binding ElementName=MainChart}"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch"
    HorizontalContentAlignment="Left"
    VerticalContentAlignment="Top"
    MaxHeight="300"
    >
    <telerikPrimitives:RadLegendControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </telerikPrimitives:RadLegendControl.ItemsPanel>
</telerikPrimitives:RadLegendControl>
```

<p>Where telerikPrimitives is defined with the following:</p>

<pre class="lang-xml prettyprint-override"><code>xmlns:telerikPrimitives="using:Telerik.UI.Xaml.Controls.Primitives"
</code>```

I have tried adding/modifying the following lines:

MaxHeight="{Binding ElementName=ChartGrid, Path=Height, Mode=Oneway}"
MaxHeight="{Binding ElementName=ChartGrid, Path=ActualHeight, Mode=Oneway}"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollMode="Enabled"
```

Currently with my file that can display ~332 Series on my Chart, the Legend does not have a Scrollbar showing, with the items disappearing off-screen. (Unfortunately I don't have enough rep to show an image).

I would like to find a solution where, if there are sufficient Series showing, a vertical Scrollbar would appear and allow the user to scroll down through the Legend.

I realise this may appear as excessive, but I would like to ensure that my program behaves appropriately if a user would, for any reason, decide to display a large number of Series on the chart.

答:
Since you just provide the RadLegendControl XAML code, I did not see your whole XAML code sample. I'm not sure what the issue is on your side.

So, I made a simple code sample according to the Telerik's official document.

I just use a ScrollViewer control to wrap the RadLegendControl, then it will be scrollable.

Please see my code sample:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*"></ColumnDefinition>
        <ColumnDefinition Width="8*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <telerikChart:RadCartesianChart x:Name="chart" Grid.Column="1">
        <telerikChart:RadCartesianChart.HorizontalAxis>
            <telerikChart:CategoricalAxis />
        </telerikChart:RadCartesianChart.HorizontalAxis>
        <telerikChart:RadCartesianChart.VerticalAxis>
            <telerikChart:LinearAxis />
        </telerikChart:RadCartesianChart.VerticalAxis>
        <telerikChart:RadCartesianChart.SeriesProvider>
            <telerikChart:ChartSeriesProvider x:Name="provider">
                <telerikChart:ChartSeriesProvider.SeriesDescriptors>
                    <telerikChart:CategoricalSeriesDescriptor ItemsSourcePath="GetData" ValuePath="Value" CategoryPath="Category" LegendTitlePath="LegendTitle">
                        <telerikChart:CategoricalSeriesDescriptor.Style>
                            <Style TargetType="telerikChart:BarSeries">
                                <Setter Property="CombineMode" Value="Cluster" />
                            </Style>
                        </telerikChart:CategoricalSeriesDescriptor.Style>
                    </telerikChart:CategoricalSeriesDescriptor>
                </telerikChart:ChartSeriesProvider.SeriesDescriptors>
            </telerikChart:ChartSeriesProvider>
        </telerikChart:RadCartesianChart.SeriesProvider>
    </telerikChart:RadCartesianChart>
    <ScrollViewer>
        <telerikPrimitives:RadLegendControl x:Name="LegendForChart" LegendProvider="{Binding ElementName=chart}">
            <telerikPrimitives:RadLegendControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsStackPanel Orientation="Vertical" />
                </ItemsPanelTemplate>
            </telerikPrimitives:RadLegendControl.ItemsPanel>
        </telerikPrimitives:RadLegendControl>
    </ScrollViewer>
</Grid>
</code>```

```<code>private Random r = new Random();

    public List<ViewModel> GenerateCollection()
    {
        List<ViewModel> collection = new List<ViewModel>();
        for (int i = 0; i < 500; i++)
        {
            ViewModel vm = new ViewModel();
            vm.GetData = GenerateData();
            vm.LegendTitle = "ViewModel " + i;
            collection.Add(vm);
        }

        return collection;
    }

    public List<Data> GenerateData()
    {
        List<Data> data = new List<Data>();
        data.Add(new Data { Category = "Apple", Value = r.Next(1, 20) });
        data.Add(new Data { Category = "Orange", Value = r.Next(10, 30) });
        data.Add(new Data { Category = "Lemon", Value = r.Next(20, 40) });

        return data;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        this.provider.Source = GenerateCollection();
    }
</code>```

```<code>public class ViewModel
{
    public List<Data> GetData { get; set; }

    public string LegendTitle { get; set; }
}

public class Data
{
    public double Value { get; set; }

    public string Category { get; set; }
}
</code>```

Body:
I am developing a program within UWP that will have the ability to chart data on-screen, and must support the potential that a user may want to chart a large number of series on it.

The Chart that I am using is Telerik's RadCartesianChart and I am using a RadLegendControl for showing the legend for the chart. This is laid out on a Grid that has two Columns and one Row. In the first Column (0) is the RadLegendControl. In the second Column (1) is the RadCartesianChart.

When a large number of Series are drawn, this can result in the Legend going down below the bottom of the app, cutting off the remaining items in the legend. This is basically an "excessive" example of the usage of this chart and I'm wanting to make sure it can function effectively when put under this kind of use.

Is there a way to add a scrollbar to the Legend Control so that a user can scroll through the legend? Or should I be looking at a different method for showing the legend?

This is for a program made within UWP that is currently targeting a minimum version of Windows 10 1803 and aiming for 1809, using Visual Studio 2019.

I made a post over on Telerik's forum asking this question and it was suggested that there is possibly an external component that is letting the legend extend to its full height off-screen and they provided a possible solution in trying to set an explicit maximum height to see the scrollbar appear when it reaches that upper bound. As such, in the XAML I set MaxHeight="300", which is much smaller than the average Chart's legend would require, such that I could easily see if the Scrollbar appeared. When I tried this, no Scrollbar appeared.

Originally I was having the RadLegendControl being drawn utilising a StackPanel to reorder the Legend to display from top-down instead of left-to-right so that it could fit alongside the Chart. I suspected that the StackPanel's internal ScrollViewer may have been conflicting with the RadLegendControl's internal ScrollViewer. I removed the StackPanel layout to ensure that it could not conflict to see if a ScrollViewer would then appear. It did not (I tested a horizontal one as well, to no success).

I have tried other solutions such as binding the MaxHeight property of the RadLegendControl to the Height or ActualHeight of the Grid row that it is on, explicitly setting VerticalScrollMode to Enabled and VerticalScrollVisibility to Visible.

This is the RadLegendControl code within XAML, still with the MaxHeight set explicitly to 300:

<telerikPrimitives:RadLegendControl
    x:Name="LegendForChart"
    LegendProvider="{Binding ElementName=MainChart}"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch"
    HorizontalContentAlignment="Left"
    VerticalContentAlignment="Top"
    MaxHeight="300"
    >
    <telerikPrimitives:RadLegendControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </telerikPrimitives:RadLegendControl.ItemsPanel>
</telerikPrimitives:RadLegendControl>

Where telerikPrimitives is defined with the following:

xmlns:telerikPrimitives="using:Telerik.UI.Xaml.Controls.Primitives"

I have tried adding/modifying the following lines:

MaxHeight="{Binding ElementName=ChartGrid, Path=Height, Mode=Oneway}"
MaxHeight="{Binding ElementName=ChartGrid, Path=ActualHeight, Mode=Oneway}"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollMode="Enabled"

Currently with my file that can display ~332 Series on my Chart, the Legend does not have a Scrollbar showing, with the items disappearing off-screen. (Unfortunately I don't have enough rep to show an image).

I would like to find a solution where, if there are sufficient Series showing, a vertical Scrollbar would appear and allow the user to scroll down through the Legend.

I realise this may appear as excessive, but I would like to ensure that my program behaves appropriately if a user would, for any reason, decide to display a large number of Series on the chart.

Body:
Since you just provide the RadLegendControl XAML code, I did not see your whole XAML code sample. I'm not sure what the issue is on your side.

So, I made a simple code sample according to the Telerik's official document.

I just use a ScrollViewer control to wrap the RadLegendControl, then it will be scrollable.

Please see my code sample:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*"></ColumnDefinition>
        <ColumnDefinition Width="8*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <telerikChart:RadCartesianChart x:Name="chart" Grid.Column="1">
        <telerikChart:RadCartesianChart.HorizontalAxis>
            <telerikChart:CategoricalAxis />
        </telerikChart:RadCartesianChart.HorizontalAxis>
        <telerikChart:RadCartesianChart.VerticalAxis>
            <telerikChart:LinearAxis />
        </telerikChart:RadCartesianChart.VerticalAxis>
        <telerikChart:RadCartesianChart.SeriesProvider>
            <telerikChart:ChartSeriesProvider x:Name="provider">
                <telerikChart:ChartSeriesProvider.SeriesDescriptors>
                    <telerikChart:CategoricalSeriesDescriptor ItemsSourcePath="GetData" ValuePath="Value" CategoryPath="Category" LegendTitlePath="LegendTitle">
                        <telerikChart:CategoricalSeriesDescriptor.Style>
                            <Style TargetType="telerikChart:BarSeries">
                                <Setter Property="CombineMode" Value="Cluster" />
                            </Style>
                        </telerikChart:CategoricalSeriesDescriptor.Style>
                    </telerikChart:CategoricalSeriesDescriptor>
                </telerikChart:ChartSeriesProvider.SeriesDescriptors>
            </telerikChart:ChartSeriesProvider>
        </telerikChart:RadCartesianChart.SeriesProvider>
    </telerikChart:RadCartesianChart>
    <ScrollViewer>
        <telerikPrimitives:RadLegendControl x:Name="LegendForChart" LegendProvider="{Binding ElementName=chart}">
            <telerikPrimitives:RadLegendControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsStackPanel Orientation="Vertical" />
                </ItemsPanelTemplate>
            </telerikPrimitives:RadLegendControl.ItemsPanel>
        </telerikPrimitives:RadLegendControl>
    </ScrollViewer>
</Grid>

private Random r = new Random();

    public List<ViewModel> GenerateCollection()
    {
        List<ViewModel> collection = new List<ViewModel>();
        for (int i = 0; i < 500; i++)
        {
            ViewModel vm = new ViewModel();
            vm.GetData = GenerateData();
            vm.LegendTitle = "ViewModel " + i;
            collection.Add(vm);
        }

        return collection;
    }

    public List<Data> GenerateData()
    {
        List<Data> data = new List<Data>();
        data.Add(new Data { Category = "Apple", Value = r.Next(1, 20) });
        data.Add(new Data { Category = "Orange", Value = r.Next(10, 30) });
        data.Add(new Data { Category = "Lemon", Value = r.Next(20, 40) });

        return data;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        this.provider.Source = GenerateCollection();
    }

public class ViewModel
{
    public List<Data> GetData { get; set; }

    public string LegendTitle { get; set; }
}

public class Data
{
    public double Value { get; set; }

    public string Category { get; set; }
}


来源: stackexchange

问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
Useful for

Gui (complex Property when you use PropertyGrid, Form header text)

DataBinding (thats the way how it working)

And any other string output.

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

OwnerDisplayName: Avram


问:
How to bring ajax search onkeyup with jquery
My Script to call ajax

```<code><script language="javascript">
function search_func(value)
{
    $.ajax({
       type: "GET",
       url: "sample.php",
       data: {'search_keyword' : value},
       dataType: "text",
       success: function(msg){
                   //Receiving the result of search here
       }
    });
}
</script>
</code>```

HTML

```<code>   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</code>```

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

答:
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) . </p>

<p>Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment) </p>

ContentLicense: CC BY-SA 3.0

Body:
My Script to call ajax

HTML

   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

Body:
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .

Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)


问:
How to align elements properly in a CoordinatorLayout under a CollapsingLayout?
I want to achieve the hierarchy shown in the preview picture below, I have no prior knowledge of collapsible layout and coordinator layout but what I did caused the view pager to NOT to show it's content.

I am working in a main activity that has a Coordinator layout as a root layout, a collapsing toolbar, a viewpager, a bottom navigation bar and a hidden bottom sheet

PS: I am working with AndroidX support library.

This is my XML Layout activity_main.xml

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent"
    android:fitsSystemWindows="true">

    <!-- RETRACTABLE TOOLBAR -->
    <com.google.android.material.appbar.AppBarLayout
       android:id="@+id/appbar"
       android:layout_width="match_parent"
       android:layout_height="@dimen/appbar_header_height"
       android:fitsSystemWindows="true"
       android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
       <com.google.android.material.appbar.CollapsingToolbarLayout
           android:id="@+id/collapsing_toolbar"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:fitsSystemWindows="true"
           app:contentScrim="?attr/colorPrimary"
           app:expandedTitleMarginStart="@dimen/activity_margin_content"
           app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
           <ImageView
                android:id="@+id/iv_banner_img"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/banner"
                android:tintMode="multiply"
                app:layout_collapseMode="parallax" />
                <View
                    android:layout_width="match_parent"
                    android:layout_height="80dp"
                    android:layout_gravity="top"
                    android:background="@drawable/scrim_topdown"
                    android:fitsSystemWindows="true"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="160dp"
                    android:layout_gravity="bottom"
                    android:background="@drawable/scrim"/>
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:layout_gravity="end">
                    <ImageView
                        android:src="@drawable/ic_user_placeholder"
                        android:id="@+id/iv_parent_profile_sm"
                        android:layout_width="32dp"
                        android:layout_height="32dp"/>
                </LinearLayout>
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/anim_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
                <LinearLayout
                    android:gravity="center_vertical"
                    android:layout_gravity="bottom"
                    android:layout_marginStart="12dp"
                    android:layout_marginEnd="12dp"
                    android:layout_marginBottom="12dp"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <LinearLayout
                        android:gravity="center_vertical"
                        android:layout_gravity="bottom"
                        android:orientation="horizontal"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <TextView
                            android:padding="4dp"
                            android:layout_marginEnd="6dp"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center_vertical"
                            android:id="@+id/tv_name"
                            android:drawableStart="@drawable/ic_person"/>
                        <TextView
                            android:layout_marginEnd="6dp"
                            android:padding="4dp"
                            android:id="@+id/tv_birth"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center_vertical"
                            android:drawableStart="@drawable/ic_cake"/>
                        <ImageView
                            android:padding="8dp"
                            android:id="@+id/iv_gender"
                            android:layout_width="32dp"
                            android:layout_height="32dp" />
                    </LinearLayout>
                </LinearLayout>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>

    <!-- VIEW PAGER -->
    <androidx.viewpager.widget.ViewPager
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <!-- NAVIGATION BAR -->
    <com.gauravk.bubblenavigation.BubbleNavigationLinearView
            android:layout_alignParentBottom="true"
            android:id="@+id/bottom_navigation_view_linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorWhite"
            android:elevation="12dp"
            android:padding="6dp"
            android:animateLayoutChanges="true"
            android:layout_gravity="bottom">
            <!-- bottom navigation bar elements -->
    </com.gauravk.bubblenavigation.BubbleNavigationLinearView>

    <!-- BOTTOM SHEETS -->
    <include layout="@layout/details_sheet" />
    <include layout="@layout/add_sheet"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

This is the desired result:

答: I got what I needed by wrapping everything in a RelativeLayout then I kept tweaking android:layout_above and android:layout_below until I got right

ContentLicense: CC BY-SA 4.0

Body:
I want to achieve the hierarchy shown in the preview picture below, I have no prior knowledge of collapsible layout and coordinator layout but what I did caused the view pager to NOT to show it's content.

I am working in a main activity that has a Coordinator layout as a root layout, a collapsing toolbar, a viewpager, a bottom navigation bar and a hidden bottom sheet

PS: I am working with AndroidX support library.

This is my XML Layout activity_main.xml

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parent"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
       android:id="@+id/appbar"
       android:layout_width="match_parent"
       android:layout_height="@dimen/appbar_header_height"
       android:fitsSystemWindows="true"
       android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
       <com.google.android.material.appbar.CollapsingToolbarLayout
           android:id="@+id/collapsing_toolbar"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:fitsSystemWindows="true"
           app:contentScrim="?attr/colorPrimary"
           app:expandedTitleMarginStart="@dimen/activity_margin_content"
           app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
           <ImageView
                android:id="@+id/iv_banner_img"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/banner"
                android:tintMode="multiply"
                app:layout_collapseMode="parallax" />
                <View
                    android:layout_width="match_parent"
                    android:layout_height="80dp"
                    android:layout_gravity="top"
                    android:background="@drawable/scrim_topdown"
                    android:fitsSystemWindows="true"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="160dp"
                    android:layout_gravity="bottom"
                    android:background="@drawable/scrim"/>
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:layout_gravity="end">
                    <ImageView
                        android:src="@drawable/ic_user_placeholder"
                        android:id="@+id/iv_parent_profile_sm"
                        android:layout_width="32dp"
                        android:layout_height="32dp"/>
                </LinearLayout>
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/anim_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
                <LinearLayout
                    android:gravity="center_vertical"
                    android:layout_gravity="bottom"
                    android:layout_marginStart="12dp"
                    android:layout_marginEnd="12dp"
                    android:layout_marginBottom="12dp"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <LinearLayout
                        android:gravity="center_vertical"
                        android:layout_gravity="bottom"
                        android:orientation="horizontal"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <TextView
                            android:padding="4dp"
                            android:layout_marginEnd="6dp"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center_vertical"
                            android:id="@+id/tv_name"
                            android:drawableStart="@drawable/ic_person"/>
                        <TextView
                            android:layout_marginEnd="6dp"
                            android:padding="4dp"
                            android:id="@+id/tv_birth"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center_vertical"
                            android:drawableStart="@drawable/ic_cake"/>
                        <ImageView
                            android:padding="8dp"
                            android:id="@+id/iv_gender"
                            android:layout_width="32dp"
                            android:layout_height="32dp" />
                    </LinearLayout>
                </LinearLayout>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <com.gauravk.bubblenavigation.BubbleNavigationLinearView
            android:layout_alignParentBottom="true"
            android:id="@+id/bottom_navigation_view_linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorWhite"
            android:elevation="12dp"
            android:padding="6dp"
            android:animateLayoutChanges="true"
            android:layout_gravity="bottom">

    </com.gauravk.bubblenavigation.BubbleNavigationLinearView>

    <include layout="@layout/details_sheet" />
    <include layout="@layout/add_sheet"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

This is the desired result:


问:
tally employee occurance in data frame within pandas, when column contains mulitple values
i have the following excel file

```<code>ID     EmpName                   date           cost
1      bob smith              01/01/2019     10
2      Jane Doe               01/04/2019     20
3      steve ray, bob smith   01/03/2017     100
</code>```

If i want to count the occurrences of each person: bob, jane, and steve ... but on ID 3 (as well as other rows) the data in the name field has multiple employees listed which isn't ideal.. what is my best approach to tally this?

Looking for something like this

```<code>employee      count       cost
bob smith     2           110
jane doe      1           20
steve ray     1           100
</code>```

Second question:

If my data is as follows:

```<code>ID     EmpName1      Empname2    date           cost
1      bob smith                 01/01/2019     10
2      Jane Doe                  01/04/2019     20
3      steve ray     bob smith   01/03/2017     100
</code>```

could this be tallied in a similar way?

答:
using get_dummies

```<code>s=df.EmpName.str.get_dummies(', ')
pd.concat([s.sum(),s.mul(df.cost,0).sum()],axis=1)
Out[666]:
           0    1
Jane Doe   1   20
bobs mith  2  110
steve ray  1  100
</code>```

Or we using unnesting

```<code>df.EmpName=df.EmpName.str.split(',')
unnesting(df,['EmpName']).groupby('EmpName').cost.agg(['sum','count'])
Out[669]:
          sum  count
EmpName
JaneDoe    20      1
bobsmith  110      2
steveray  100      1
</code>```

Update

```<code>s=df[['EmpName1','Empname2','cost']].melt(['cost']).groupby('value').cost.agg(['sum','count'])
s.drop('')
Out[678]:
          sum  count
value
JaneDoe    20      1
bobsmith  110      2
steveray  100      1
</code>```

Or wide_to_long

```<code>pd.wide_to_long(df,['EmpName'],i=['ID'],j='number').groupby('EmpName').cost.agg(['sum','count'])
</code>```

```<code>def unnesting(df, explode):
    idx = df.index.repeat(df[explode[0]].str.len())
    df1 = pd.concat([
        pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
    df1.index = idx

    return df1.join(df.drop(explode, 1), how='left')
</code>```

Body:
i have the following excel file

ID     EmpName                   date           cost
1      bob smith              01/01/2019     10
2      Jane Doe               01/04/2019     20
3      steve ray, bob smith   01/03/2017     100

If i want to count the occurrences of each person: bob, jane, and steve ... but on ID 3 (as well as other rows) the data in the name field has multiple employees listed which isn't ideal.. what is my best approach to tally this?

Looking for something like this

employee      count       cost
bob smith     2           110
jane doe      1           20
steve ray     1           100

Second question:

If my data is as follows:

ID     EmpName1      Empname2    date           cost
1      bob smith                 01/01/2019     10
2      Jane Doe                  01/04/2019     20
3      steve ray     bob smith   01/03/2017     100

could this be tallied in a similar way?

Body:
using get_dummies

s=df.EmpName.str.get_dummies(', ')
pd.concat([s.sum(),s.mul(df.cost,0).sum()],axis=1)
Out[666]:
           0    1
Jane Doe   1   20
bobs mith  2  110
steve ray  1  100

Or we using unnesting

df.EmpName=df.EmpName.str.split(',')
unnesting(df,['EmpName']).groupby('EmpName').cost.agg(['sum','count'])
Out[669]:
          sum  count
EmpName
JaneDoe    20      1
bobsmith  110      2
steveray  100      1

Update

s=df[['EmpName1','Empname2','cost']].melt(['cost']).groupby('value').cost.agg(['sum','count'])
s.drop('')
Out[678]:
          sum  count
value
JaneDoe    20      1
bobsmith  110      2
steveray  100      1

Or wide_to_long

pd.wide_to_long(df,['EmpName'],i=['ID'],j='number').groupby('EmpName').cost.agg(['sum','count'])

def unnesting(df, explode):
    idx = df.index.repeat(df[explode[0]].str.len())
    df1 = pd.concat([
        pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
    df1.index = idx

    return df1.join(df.drop(explode, 1), how='left')


问:
How do I find out and change the value of <input type = "text"> in asp.net?
I want to find the value of  and want to mask the first 4th of the text field to another character when the length of the text field is 4 or greater.

but I don't know well asp.net skill. help me plz.

here is some html in body tag

    <form id="form1" runat="server">

            <input type="text" runat="server" id="input1" name="input1" value="TestText" />
            <input type="button" runat="server" class="btnCnvt" name="btnCnvt" id="btnCnvt" value="convert" onclick="GetValue()" />

    </form>

```

<p>here is javascript :(</p>

```
```

答: Your button is from server side, So, javascript function will not fire on OnClick event, instead use OnClientClick event.

Body:
I want to find the value of  and want to mask the first 4th of the text field to another character when the length of the text field is 4 or greater.

but I don't know well asp.net skill. help me plz.

here is some html in body tag

    <form id="form1" runat="server">

            <input type="text" runat="server" id="input1" name="input1" value="TestText" />
            <input type="button" runat="server" class="btnCnvt" name="btnCnvt" id="btnCnvt" value="convert" onclick="GetValue()" />

    </form>

here is javascript :(


问:
Describing the first few evaluation steps of a given foldr function
The following function is given:

```<code>mystery a b c xs =
  foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b
</code>```

I know what the function does roughly but I have a hard time really understanding the intermediate steps. I picked following example:

```<code>mystery 1 2 3 [1, 2, 3]
</code>```

Especially the use of rec is giving me a hard time. I assume that one of the final steps looks like this:

```<code>(\a b -> 3 + (b + 3 + 3 + 3) - 3) [] 1 2
</code>```

So the output is 11. Could someone describe the first few steps of the execution? What happens after:

```<code>foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1, 2, 3] 1 2
</code>```

答:
The key here is that the foldr operation is constructing a function, then applying it to a and b; we can clarify it by adding parentheses:

mystery a b c xs =
(foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs) a b
```

<p>If the xs list is empty, you get simply the initial function <code>\a b -> a + b - c</code>, which is then applied to a and b.</p>

<p>if it is not empty, then it makes succesive transformations to that function (in each iteration, "rec" is the previous function, which is used to construct a new one).</p>

<p>To illustrate, let's run the foldr by hand for <code>mystery 1 2 3 [1, 2, 3]</code>;
initially, we have:</p>

<pre class="lang-hs prettyprint-override"><code>foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1,2,3]
</code>```

Applying the equations for foldr:

foldr f z []     = z
foldr f z (x:xs) = f x (foldr f z xs)
```

<p>Reduces the expression to:</p>

<pre class="lang-hs prettyprint-override"><code>(\rec a b -> rec 1 (b + 3)) (foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [2,3])
</code>```

Repeating for the next value in the list we get:

(\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [3])
```

<p>Then, for the last one:</p>

<pre class="lang-hs prettyprint-override"><code>(\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\rec a b -> rec 3 (b + 3)) (\a b -> a + b - 3)
</code>```

We need to compose those functions, to create the final function - replacing "rec" with the previous function:

(\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\rec a b -> rec 3 (b + 3)) (\a b -> a + b - 3)
=> (\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\a b -> (\a b -> a + b - 3) 3 (b + 3))
=> (\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\a b -> 3 + (b + 3) - 3))
=> (\rec a b -> rec 1 (b + 3)) (\a b -> (\a b -> 3 + (b + 3) - 3)) 2 (b + 3))
=> (\rec a b -> rec 1 (b + 3)) (\a b -> 3 + ((b + 3) + 3) - 3))
=> \a b -> (\a b -> 3 + ((b + 3) + 3) - 3)) 1 (b + 3)
=> \a b -> 3 + (((b + 3) + 3) + 3) - 3)
=> \a b -> b + 9
```

then, we apply \a b -> b + 9 to the original "a" and "b" (which are 1 and 2), and get 2 + 9 = 11

Body:
The following function is given:

mystery a b c xs =
  foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b

I know what the function does roughly but I have a hard time really understanding the intermediate steps. I picked following example:

mystery 1 2 3 [1, 2, 3]

Especially the use of rec is giving me a hard time. I assume that one of the final steps looks like this:

(\a b -> 3 + (b + 3 + 3 + 3) - 3) [] 1 2

So the output is 11. Could someone describe the first few steps of the execution? What happens after:

foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1, 2, 3] 1 2

Body:
The key here is that the foldr operation is constructing a function, then applying it to a and b; we can clarify it by adding parentheses:

mystery a b c xs =
(foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs) a b

If the xs list is empty, you get simply the initial function \a b -> a + b - c, which is then applied to a and b.

if it is not empty, then it makes succesive transformations to that function (in each iteration, "rec" is the previous function, which is used to construct a new one).

To illustrate, let's run the foldr by hand for mystery 1 2 3 [1, 2, 3];
initially, we have:

foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1,2,3]

Applying the equations for foldr:

foldr f z []     = z
foldr f z (x:xs) = f x (foldr f z xs)

Reduces the expression to:

(\rec a b -> rec 1 (b + 3)) (foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [2,3])

Repeating for the next value in the list we get:

(\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [3])

Then, for the last one:

(\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\rec a b -> rec 3 (b + 3)) (\a b -> a + b - 3)

We need to compose those functions, to create the final function - replacing "rec" with the previous function:

(\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\rec a b -> rec 3 (b + 3)) (\a b -> a + b - 3)
=> (\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\a b -> (\a b -> a + b - 3) 3 (b + 3))
=> (\rec a b -> rec 1 (b + 3)) (\rec a b -> rec 2 (b + 3)) (\a b -> 3 + (b + 3) - 3))
=> (\rec a b -> rec 1 (b + 3)) (\a b -> (\a b -> 3 + (b + 3) - 3)) 2 (b + 3))
=> (\rec a b -> rec 1 (b + 3)) (\a b -> 3 + ((b + 3) + 3) - 3))
=> \a b -> (\a b -> 3 + ((b + 3) + 3) - 3)) 1 (b + 3)
=> \a b -> 3 + (((b + 3) + 3) + 3) - 3)
=> \a b -> b + 9

then, we apply \a b -> b + 9 to the original "a" and "b" (which are 1 and 2), and get 2 + 9 = 11


问:
skopt's BayesSearchCV with CatBoost
I am trying to use the skopt's BayesSearchCV method with Catboost.However i am confused on where to pass in the indices of categorical features native to catboost on to bayesSearch object's fit() method.

```<code>clf = catboost.CatBoostClassifier()
search_spaces = {'iterations': (10, 1000),
                 'depth': (1, 10),
                 'learning_rate': (0.001, 0.5),
                 'random_strength': (1e-9, 10)}
pt = BayesSearchCV(clf,
                    search_spaces,
                    n_iter=40)
pt.fit(x_train,y_train)
</code>```

fit() throws error couldn't convert categorical to float,

i know, the error is because i am not passing the indices of the categorical variables but i can't pass them in the bayes's fit() method.Also tried the catboost's pool() method which din't work either.

答:
I had a similar problem with CalibratedClassifierCV. So, posting the solution here. Maybe that would work for you.

You can try approaching this problem by first encoding categorical features into numerical just to fool BayesSearchCV but still pass the categorical feature indices while initiating CatBoostClassifier() so CatBoost can leverage them appropriately:

```<code># Import necessary libraries
from sklearn.calibration import CalibratedClassifierCV
from catboost import CatBoostClassifier

# Initialize Calibrated Classifier with Catboost
model_combined = CalibratedClassifierCV(
    CatBoostClassifier(cat_features=<cat_features_indexes>),
    method='isotonic',
    cv=5,
)
</code>```

Title: skopt's BayesSearchCV with CatBoost

Body:
I am trying to use the skopt's BayesSearchCV method with Catboost.However i am confused on where to pass in the indices of categorical features native to catboost on to bayesSearch object's fit() method.

clf = catboost.CatBoostClassifier()
search_spaces = {'iterations': (10, 1000),
                 'depth': (1, 10),
                 'learning_rate': (0.001, 0.5),
                 'random_strength': (1e-9, 10)}
pt = BayesSearchCV(clf,
                    search_spaces,
                    n_iter=40)
pt.fit(x_train,y_train)

fit() throws error couldn't convert categorical to float,

i know, the error is because i am not passing the indices of the categorical variables but i can't pass them in the bayes's fit() method.Also tried the catboost's pool() method which din't work either.

Body:
I had a similar problem with CalibratedClassifierCV. So, posting the solution here. Maybe that would work for you.

You can try approaching this problem by first encoding categorical features into numerical just to fool BayesSearchCV but still pass the categorical feature indices while initiating CatBoostClassifier() so CatBoost can leverage them appropriately:

# Import necessary libraries
from sklearn.calibration import CalibratedClassifierCV
from catboost import CatBoostClassifier

# Initialize Calibrated Classifier with Catboost
model_combined = CalibratedClassifierCV(
    CatBoostClassifier(cat_features=<cat_features_indexes>),
    method='isotonic',
    cv=5,
)


问:
4 functions near identical, one works but the others dont no errors
I have 4 functions that should grab some text from a specific docx file that are highlighted scan4<colour> is the varialbe of the text, these functions are near identical but are searching and replacing different highglighted text, they print out the same but they dont replace the text

these are 2 functions of 4, the yellow one works while the green one doesnt
what the code does is it searches and replaces the text then encrypts then uses the encrypted string into the main document, the other does the exact same but searches for a different highlighted colour. I try to encrypt the first function works but the second one doesn't

This code searches for yellow encodes the text and then replaces it so the un-encrypted document shows the encrypted string of the contents

```<code>def securi1_key():
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
        global key1
        key1 = file.read()
        file.close()

    def rewrite_yellow():
        securi1_key()
        save_yellow_text()
        #   get key from file
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
        texty = scan4yellow.decode("utf-8")
        encodedy = texty.encode()

        #   encrypt message
        f = Fernet(key1)
        encryptedy = f.encrypt(encodedy)
        print(scan4yellow)
        print(scan4yellow.decode("utf-8"))
        document = docx.Document(f1)
        for paragraph in document.paragraphs:
            if scan4yellow.decode("utf-8") in paragraph.text:
                inline = paragraph.runs
                # loops for runs
                for i in range(len(inline)):
                    if scan4yellow.decode("utf-8") in inline[i].text:
                        text = inline[i].text.replace(scan4yellow.decode("utf-8"), encryptedy.decode("utf-8"))
                        inline[i].text = text
        document.save(f1)

    def save_yellow_text():
        securi1_key()
        fp = f1
        p = Path(fp)
        filename1 = p.stem

        storedtexty = filename1 + " Yellow Text"
        storedtextencryptedy = storedtexty + ".encrypted"
        list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")

        if storedtexty in list_of_files:
            storedtexty = (storedtexty + "1")

        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty, "w+")
        file.write(scan4yellow.decode("utf-8"))

        input_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty)

        if storedtextencryptedy in list_of_files:
            storedtextencryptedy = (storedtextencryptedy + "1")

        output_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedy)

        with open(input_file1, "rb") as f:
            data = f.read()

        fernet = Fernet(key1)
        encrypted = fernet.encrypt(data)

        with open(output_file1, "wb") as f:
            f.write(encrypted)

        file.close()
        os.remove(input_file1)
</code>```

this code should do the exact same but for the colour green :

```<code>def securi2_key():
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
        global key2
        key2 = file.read()
        file.close()

    def rewrite_green():
        securi2_key()
        save_green_text()
        #   get key from file
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
        textg = scan4green.decode("utf-8")
        encodedg = textg.encode()
        print(encodedg)

        #   encrypt message
        f = Fernet(key2)
        encryptedg = f.encrypt(encodedg)
        print(encryptedg)

        document = docx.Document(f1)
        for paragraph in document.paragraphs:
            if scan4green.decode("utf-8") in paragraph.text:
                inline = paragraph.runs
                # loops for runs
                for i in range(len(inline)):
                    if scan4green.decode("utf-8") in inline[i].text:
                        text = inline[i].text.replace(scan4green.decode("utf-8"), encryptedg.decode("utf-8"))
                        inline[i].text = text
        document.save(f1)

    def save_green_text():
        securi2_key()
        fp = f1
        p = Path(fp)
        filename2 = p.stem

        storedtextg = filename2 + " Green Text"
        storedtextencryptedg = storedtextg + ".encrypted"
        list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")

        if storedtextg in list_of_files:
            storedtextg = (storedtextg + "1")

        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg, "w+")
        file.write(scan4green.decode("utf-8"))
        print(scan4green.decode("utf-8") + "tested1")

        input_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg)

        if storedtextencryptedg in list_of_files:
            storedtextencryptedg = (storedtextencryptedg + "1")

        output_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedg)

        with open(input_file2, "rb") as f:
            data = f.read()

        fernet = Fernet(key2)
        encrypted = fernet.encrypt(data)

        with open(output_file2, "wb") as f:
            f.write(encrypted)

        file.close()
        os.remove(input_file2)
</code>```

I should have some incoherent string replace the actual text and the actual text saved in another file encrypted, but all this does is work for the first yellow function but not the green function

Ideally it should take the text from the read in file, make a copy write it out to a file and encrypt that then take the string of encryption from that and replace it where it was in the read in file, but it only works for the yellow code while the green and the other code which are near identical do not work

答: I have found an answer, what I changed has nothing to do with the code I provided but when I read in the text it was scan4green = (word.find(tag_t).text.encode('utf-8').lower()). this apparently caused it not to work properly but the scan4yellow did work because i didn't have .lower() attached to the end.

Body:
I have 4 functions that should grab some text from a specific docx file that are highlighted scan4<colour> is the varialbe of the text, these functions are near identical but are searching and replacing different highglighted text, they print out the same but they dont replace the text

these are 2 functions of 4, the yellow one works while the green one doesnt
what the code does is it searches and replaces the text then encrypts then uses the encrypted string into the main document, the other does the exact same but searches for a different highlighted colour. I try to encrypt the first function works but the second one doesn't

This code searches for yellow encodes the text and then replaces it so the un-encrypted document shows the encrypted string of the contents

def securi1_key():
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
        global key1
        key1 = file.read()
        file.close()

    def rewrite_yellow():
        securi1_key()
        save_yellow_text()
        #   get key from file
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
        texty = scan4yellow.decode("utf-8")
        encodedy = texty.encode()

        #   encrypt message
        f = Fernet(key1)
        encryptedy = f.encrypt(encodedy)
        print(scan4yellow)
        print(scan4yellow.decode("utf-8"))
        document = docx.Document(f1)
        for paragraph in document.paragraphs:
            if scan4yellow.decode("utf-8") in paragraph.text:
                inline = paragraph.runs
                # loops for runs
                for i in range(len(inline)):
                    if scan4yellow.decode("utf-8") in inline[i].text:
                        text = inline[i].text.replace(scan4yellow.decode("utf-8"), encryptedy.decode("utf-8"))
                        inline[i].text = text
        document.save(f1)

    def save_yellow_text():
        securi1_key()
        fp = f1
        p = Path(fp)
        filename1 = p.stem

        storedtexty = filename1 + " Yellow Text"
        storedtextencryptedy = storedtexty + ".encrypted"
        list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")

        if storedtexty in list_of_files:
            storedtexty = (storedtexty + "1")

        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty, "w+")
        file.write(scan4yellow.decode("utf-8"))

        input_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty)

        if storedtextencryptedy in list_of_files:
            storedtextencryptedy = (storedtextencryptedy + "1")

        output_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedy)

        with open(input_file1, "rb") as f:
            data = f.read()

        fernet = Fernet(key1)
        encrypted = fernet.encrypt(data)

        with open(output_file1, "wb") as f:
            f.write(encrypted)

        file.close()
        os.remove(input_file1)

this code should do the exact same but for the colour green :

def securi2_key():
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
        global key2
        key2 = file.read()
        file.close()

    def rewrite_green():
        securi2_key()
        save_green_text()
        #   get key from file
        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
        textg = scan4green.decode("utf-8")
        encodedg = textg.encode()
        print(encodedg)

        #   encrypt message
        f = Fernet(key2)
        encryptedg = f.encrypt(encodedg)
        print(encryptedg)

        document = docx.Document(f1)
        for paragraph in document.paragraphs:
            if scan4green.decode("utf-8") in paragraph.text:
                inline = paragraph.runs
                # loops for runs
                for i in range(len(inline)):
                    if scan4green.decode("utf-8") in inline[i].text:
                        text = inline[i].text.replace(scan4green.decode("utf-8"), encryptedg.decode("utf-8"))
                        inline[i].text = text
        document.save(f1)

    def save_green_text():
        securi2_key()
        fp = f1
        p = Path(fp)
        filename2 = p.stem

        storedtextg = filename2 + " Green Text"
        storedtextencryptedg = storedtextg + ".encrypted"
        list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")

        if storedtextg in list_of_files:
            storedtextg = (storedtextg + "1")

        file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg, "w+")
        file.write(scan4green.decode("utf-8"))
        print(scan4green.decode("utf-8") + "tested1")

        input_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg)

        if storedtextencryptedg in list_of_files:
            storedtextencryptedg = (storedtextencryptedg + "1")

        output_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedg)

        with open(input_file2, "rb") as f:
            data = f.read()

        fernet = Fernet(key2)
        encrypted = fernet.encrypt(data)

        with open(output_file2, "wb") as f:
            f.write(encrypted)

        file.close()
        os.remove(input_file2)

I should have some incoherent string replace the actual text and the actual text saved in another file encrypted, but all this does is work for the first yellow function but not the green function

Ideally it should take the text from the read in file, make a copy write it out to a file and encrypt that then take the string of encryption from that and replace it where it was in the read in file, but it only works for the yellow code while the green and the other code which are near identical do not work


答:
You will probably want to restructure your data into something that looks more like

```<code>ID     EmpName                   date           cost
1      bob smith              01/01/2019     10
2      Jane Doe               01/04/2019     20
3      steve ray              01/03/2017     100
1      bob smith              01/03/2017     100
</code>```

From this point you can use a groupby and a sum statement to find what you are looking for. Something along the lines of:

```<code>df.groupby(['EmpName'])[['cost']].sum()
</code>```

Not changing this can lead to nightmares at later stages of your analysis. It is best standard to have one record per line to avoid later errors.

Title: tally employee occurance in data frame within pandas, when column contains mulitple values

Body:
You will probably want to restructure your data into something that looks more like

ID     EmpName                   date           cost
1      bob smith              01/01/2019     10
2      Jane Doe               01/04/2019     20
3      steve ray              01/03/2017     100
1      bob smith              01/03/2017     100

From this point you can use a groupby and a sum statement to find what you are looking for. Something along the lines of:

df.groupby(['EmpName'])[['cost']].sum()

Not changing this can lead to nightmares at later stages of your analysis. It is best standard to have one record per line to avoid later errors.


问:
Processing Raw data from kinect in matlab
I am using Microsoft kinect v1 in MATLAB and want to get depth data on every pixel in meters.

I am not sure how to get that data because I am getting uint16 and as far as I have read is that it provides depth only in 13 bits, So how do I get those 13 bits and do some conversion to get depth exactly in meters.

I have searched a lot about it but could not get to any conclusion.

```<code>
    Kinectinfo = imaqhwinfo('kinect');
    colorinfo = Kinectinfo.DeviceInfo(1);
    depthinfo = Kinectinfo.DeviceInfo(2);
    colorvid = videoinput('kinect',1);
    depthvid = videoinput('kinect',2);
    srcDepth = getselectedsource(depthvid);

    % Set the frames per trigger for both devices to 1.

    colorvid.FramesPerTrigger = 1;
    depthvid.FramesPerTrigger = 1;

    % Set the trigger repeat for both devices to 200, in order to acquire 201 frames from both the color sensor and the depth sensor.

    colorvid.TriggerRepeat = 200;
    depthvid.TriggerRepeat = 200;
    %Configure the camera for manual triggering for both sensors.

    triggerconfig([colorvid depthvid],'manual');
    % Start both video objects.

    start([colorvid depthvid]);

    %Trigger the devices, then get the acquired data.

    % Trigger 200 times to get the frames.

    for i = 1:200
        % Trigger both objects.
        trigger([colorvid depthvid])
        % Get the acquired frames and metadata.
        [imgColor, ts_color, metaData_Color] = getdata(colorvid);
        [imgDepth, ts_depth, metaData_Depth] = getdata(depthvid);
    end

</code>```

```<code>[NYU Depth and RGB image][1]
[Histogram of swaped Raw Depth image][2]
[Histogram of Raw Depth Image][3]
</code>```

I would like to have some code for conversion or any SDK that provides me with meters in matlab.

Thanks alot.

答:
According to several articles, eg. such as here and here, the first three bits are code for the player that the device has identified, but this is only activated if skeleton tracking is enabled. If you don't enable skeleton tracking, the three bits are set to zero.

If you are using matlab, the depth images are 16bit double images, and contain data that is already extracted from the 13bits (most probably because skeleton tracking is already disabled, hence 3 MSB are zero.) Therefore you dont need to convert/extract the 13 bit data in matlab or libfreenect etc becuase the bits be already zero.

According to the Matlab help page, matlab ImAq toolbox requires the installation of Kinect for Windows Runtime; because it uses the Kinect SDK Kinect drivers to acquire data. And according to this SO answer, "using Microsoft SDK, so the values that are returned from kinect sensor are already real distances in mm."

Therefore, you dont really need to bitshift data in matlab. The only reason you would need to do it, would be if you are getting raw depth stream from the kinect drivers (?) in C++/C# and the 16bit data would include the 3 LSB bits.

Body:
I am using Microsoft kinect v1 in MATLAB and want to get depth data on every pixel in meters.

I am not sure how to get that data because I am getting uint16 and as far as I have read is that it provides depth only in 13 bits, So how do I get those 13 bits and do some conversion to get depth exactly in meters.

I have searched a lot about it but could not get to any conclusion.

    Kinectinfo = imaqhwinfo('kinect');
    colorinfo = Kinectinfo.DeviceInfo(1);
    depthinfo = Kinectinfo.DeviceInfo(2);
    colorvid = videoinput('kinect',1);
    depthvid = videoinput('kinect',2);
    srcDepth = getselectedsource(depthvid);

    % Set the frames per trigger for both devices to 1.

    colorvid.FramesPerTrigger = 1;
    depthvid.FramesPerTrigger = 1;

    % Set the trigger repeat for both devices to 200, in order to acquire 201 frames from both the color sensor and the depth sensor.

    colorvid.TriggerRepeat = 200;
    depthvid.TriggerRepeat = 200;
    %Configure the camera for manual triggering for both sensors.

    triggerconfig([colorvid depthvid],'manual');
    % Start both video objects.

    start([colorvid depthvid]);

    %Trigger the devices, then get the acquired data.

    % Trigger 200 times to get the frames.

    for i = 1:200
        % Trigger both objects.
        trigger([colorvid depthvid])
        % Get the acquired frames and metadata.
        [imgColor, ts_color, metaData_Color] = getdata(colorvid);
        [imgDepth, ts_depth, metaData_Depth] = getdata(depthvid);
    end

[NYU Depth and RGB image][1]
[Histogram of swaped Raw Depth image][2]
[Histogram of Raw Depth Image][3]

I would like to have some code for conversion or any SDK that provides me with meters in matlab.

Thanks alot.


问:
How can I set drop down values from JSON file
I am new to selectize and I would like to set the drop down list options of the tag input from a JSON file, right now the drop down shows what is on the input value.    </p>

```<code>{"California":["Los Angeles","San Diego","San Jose","San Francisco","Fresno","Sacramento"]}

<input type="text" id="myCity" class="form-control mb-4" placeholder="City" value="San Diego, San Francisco">

<script class="show">
$('#myCity').selectize({
                        delimiter: ',',
                        persist: false,
                        maxItems: 5,
                        plugins: ['remove_button'],
    create: function(input) {
return {
value: input,
text: input
                            }
                        }
                    });
</script>
</code>```

答: you can also loop in cities and append the each option as a child on DOM object.</p>

Body:
I am new to selectize and I would like to set the drop down list options of the tag input from a JSON file, right now the drop down shows what is on the input value.

{"California":["Los Angeles","San Diego","San Jose","San Francisco","Fresno","Sacramento"]}

<input type="text" id="myCity" class="form-control mb-4" placeholder="City" value="San Diego, San Francisco">


问:
Searching for literal string with Select-String and extracting part of string
The value of $DeviceID is : "PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0"

I'm trying to search for that string in .INF files with "Select-String" :

```<code> Select-String -Path C:\file.inf -Pattern "$DeviceID"
</code>```

But it won't take the string as is, it's having a problem with the "\V":

```
Select-String : La chaîne PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\
3&11583659&1&B0 n’est pas une expression régulière valide: analyse de
"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0" - Séquence
d'échappement \V non reconnue.
Au caractère Ligne:15 : 5
+     Select-String -Path $($_.FullName) -pattern "$($erreur.DeviceID)"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand
```

Sorry for the french but it basically says "String is not a valid regex. Escape sequence \V not recognized".

答:
I see you already have your answer but there is another switch that will do this as well.

For comparison...

-list

```<code>select-string -path "$TargeUNC\*.ps1" -Pattern 'Get-WmiObject' -list |
Select-Object -First 3

# Results

2018-01-15 Enable the Disk Cleanup tool on Windows Server.ps1:45:$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
3D_chart.ps1:1:get-wmiobject win32_perfformatteddata_perfdisk_logicaldisk
7 cmdlet Hyper-V Tips.ps1:15:$vm = Get-WmiObject -Namespace root\virtualization\v2 -Class
</code>```

-vs -SimpleMatch

```<code>select-string -path "$TargeUNC\*.ps1" -Pattern 'Get-WmiObject' -SimpleMatch |
Select-Object -First 3

# Results

2018-01-15 Enable the Disk Cleanup tool on Windows Server.ps1:45:$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
3D_chart.ps1:1:get-wmiobject win32_perfformatteddata_perfdisk_logicaldisk
7 cmdlet Hyper-V Tips.ps1:15:$vm = Get-WmiObject -Namespace root\virtualization\v2 -Class
</code>```

Body:
The value of $DeviceID is : "PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0"

I'm trying to search for that string in .INF files with "Select-String" :

 Select-String -Path C:\file.inf -Pattern "$DeviceID"

But it won't take the string as is, it's having a problem with the "\V":

Select-String : La chaîne PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\
3&11583659&1&B0 n’est pas une expression régulière valide: analyse de
"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0" - Séquence
d'échappement \V non reconnue.
Au caractère Ligne:15 : 5
+     Select-String -Path $($_.FullName) -pattern "$($erreur.DeviceID)"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand

Sorry for the french but it basically says "String is not a valid regex. Escape sequence \V not recognized".

Body:
I see you already have your answer but there is another switch that will do this as well.

For comparison...

-list

select-string -path "$TargeUNC\*.ps1" -Pattern 'Get-WmiObject' -list |
Select-Object -First 3

# Results

2018-01-15 Enable the Disk Cleanup tool on Windows Server.ps1:45:$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
3D_chart.ps1:1:get-wmiobject win32_perfformatteddata_perfdisk_logicaldisk
7 cmdlet Hyper-V Tips.ps1:15:$vm = Get-WmiObject -Namespace root\virtualization\v2 -Class

-vs -SimpleMatch

select-string -path "$TargeUNC\*.ps1" -Pattern 'Get-WmiObject' -SimpleMatch |
Select-Object -First 3

# Results

2018-01-15 Enable the Disk Cleanup tool on Windows Server.ps1:45:$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
3D_chart.ps1:1:get-wmiobject win32_perfformatteddata_perfdisk_logicaldisk
7 cmdlet Hyper-V Tips.ps1:15:$vm = Get-WmiObject -Namespace root\virtualization\v2 -Class


问:
Math domain error with calculating discriminate
My program is solving quadratic equations that the user inputs with their a, b and c values. The issue is with my compute_discriminate function. I thought it was because you cannot take the square root of a negative number, so I said if d is negative, say there is no solution. However, I am getting an error in line 56, saying
x1 = (-b + math.sqrt(d)) / (2 * a)
ValueError: math domain error

Help with this situation would be extremely helpful, Python is new to me and I am wanting to get this to work!

Tried saying if d is negative, say there is no solution before defining x1 and x2.

```<code>a = 0
b = 0
c = 0
import math

def evaluate_quad_function(a, b, c, x):
    f_of_x = a * (x ** 2) + (b * x) + c
    return f_of_x  # return the calculated result

print("Welcome to the Quadratic Solver for f(x)=ax^2+bx+c")
a = input("Enter Value for a:")
b = input("Enter Value for b:")
c = input("Enter Value for c:")
# cannot do math on string, convert to float
a = float(a)
b = float(b)
c = float(c)
f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c

def print_sign(x):
    # check the sign if positive or negative
    return '+' if x > 0 else '-'

if a == 1:
    print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")
if b == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ", print_sign(c), abs(c), sep="")
if c == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")

x = input("Enter Value for x:")
x = float(x)

fx = evaluate_quad_function(a, b, c, x)
print("F" + "(" + str(x) + ")""=", str(fx))
temp = input("\nPress Enter to continue...")  # wait

x0 = -b / (2 * a)
x0 = float(x0)
if a > 0:
    print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
else:
    print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
temp = input("\nPress Enter to continue...")  # wait

def compute_discriminate():
    print("Solving for f(x) = 0")
    d = (b ** 2) - (4 * a * c)
    if d < 0:
        print("No real solution.")
    x1 = (-b + math.sqrt(d)) / (2 * a)
    x2 = (-b - math.sqrt(d)) / (2 * a)
    print("Discriminant is", str(d))
    if d > 0:
        (print("Two Real Solutions", str(x1), "and", str(x2)))

    if d == 0:
        print("One real solution:", str(x0))

print(compute_discriminate())
</code>```

答:
After you check if d<0 is true, you need to also return/exit the function, or else it will continue to execute.</p>

```<code>d = (b ** 2) - (4 * a * c)
if d < 0:
    print("No real solution.")
    return # Exit the function now
x1 = (-b + math.sqrt(d)) / (2 * a)
</code>```

Body:
My program is solving quadratic equations that the user inputs with their a, b and c values. The issue is with my compute_discriminate function. I thought it was because you cannot take the square root of a negative number, so I said if d is negative, say there is no solution. However, I am getting an error in line 56, saying
x1 = (-b + math.sqrt(d)) / (2 * a)
ValueError: math domain error

Help with this situation would be extremely helpful, Python is new to me and I am wanting to get this to work!

Tried saying if d is negative, say there is no solution before defining x1 and x2.

a = 0
b = 0
c = 0
import math

def evaluate_quad_function(a, b, c, x):
    f_of_x = a * (x ** 2) + (b * x) + c
    return f_of_x  # return the calculated result

print("Welcome to the Quadratic Solver for f(x)=ax^2+bx+c")
a = input("Enter Value for a:")
b = input("Enter Value for b:")
c = input("Enter Value for c:")
# cannot do math on string, convert to float
a = float(a)
b = float(b)
c = float(c)
f_x0 = a * ((-b) / (2 * a) ** 2) + (b * (-b) / (2 * a)) + c

def print_sign(x):
    # check the sign if positive or negative
    return '+' if x > 0 else '-'

if a == 1:
    print("\nFunction is: f(x)= ", "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")
if b == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), "x ", print_sign(c), abs(c), sep="")
if c == 1:
    print("\nFunction is: f(x)= ", a, "x**2 ", print_sign(b), abs(b), "x ", print_sign(c), abs(c), sep="")

x = input("Enter Value for x:")
x = float(x)

fx = evaluate_quad_function(a, b, c, x)
print("F" + "(" + str(x) + ")""=", str(fx))
temp = input("\nPress Enter to continue...")  # wait

x0 = -b / (2 * a)
x0 = float(x0)
if a > 0:
    print("f(x) has a minimum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
else:
    print("f(x) has a maximum at " + str(x0) + " with a value f(x0)=" + str(f_x0))
temp = input("\nPress Enter to continue...")  # wait

def compute_discriminate():
    print("Solving for f(x) = 0")
    d = (b ** 2) - (4 * a * c)
    if d < 0:
        print("No real solution.")
    x1 = (-b + math.sqrt(d)) / (2 * a)
    x2 = (-b - math.sqrt(d)) / (2 * a)
    print("Discriminant is", str(d))
    if d > 0:
        (print("Two Real Solutions", str(x1), "and", str(x2)))

    if d == 0:
        print("One real solution:", str(x0))

print(compute_discriminate())

Body:
After you check if d<0 is true, you need to also return/exit the function, or else it will continue to execute.

d = (b ** 2) - (4 * a * c)
if d < 0:
    print("No real solution.")
    return # Exit the function now
x1 = (-b + math.sqrt(d)) / (2 * a)


问:
Can I set target VM in azure powershell when adding inbound nat rule?
In an azure RM load-balancer I can create a nat rule FTP using powershell, but would also like to set the target virtual machine using powershell. The only way I know how to set the target is in the portal.

I have two VMs in the load balancer. I tried using Add-AzLoadBalancerInboundNatRuleConfig, but don't see a parameter for target VM.

My script:
$lb  |  Add-AzLoadBalancerInboundNatRuleConfig -Name $EndpointName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $i -BackendPort $i

If it's not possible to set the target in powershell, what alternatives are there besides the portal?

I found the answer. The key is to add the LoadBalancerInboundNatRuleId to the Ip Configuration.

Here's a function to get the LoadBalancerInboundNatRuleId that I created for this purpose:

```<code>Function natRuleID ($sourcePortName) {
return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
}
</code>```

And here is my sample script that adds two load balancer nat rules and then sets the target network interface for a virtual machine:

```<code># Add Load Balancer Nat Rules:
$lb = Get-AzLoadBalancer -Name $lbName -ResourceGroupName $rgName
$feip = Get-AzLoadBalancerFrontendIpConfig -Name $feipName -LoadBalancer $lb
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleRdpName-FrontendIpConfiguration $feip -Protocol tcp -FrontendPort $rdpPortNumber -BackendPort 3389
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleFtpName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $ftpPublicPortForImplicit990  -BackendPort 990
$lb | Set-AzLoadBalancer  #save the new LB rules

# Set nat rule targets:
Function natRuleID ($sourcePortName) {
    return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
    }
$rules = @()
$rules = $rules += natRuleID($natRuleFtpName)
$rules = $rules += natRuleID($natRuleRdpName)
$nic = Get-AzNetworkInterface -Name $nicName -ResourceGroupName $rgName
$nic | Set-AzNetworkInterfaceIpConfig -Name $ipConfigName  -LoadBalancerInboundNatRuleId $rules
$nic | Set-AzNetworkInterface #save the new ipConfig rules
</code>```

答:
For the Load Balancer Nat rules, it describes like this:

Standard Load Balancer backend pools expand to any virtual machine
  resource in a virtual network. It can contain up to 1000 backend
  instances. A backend instance is an IP configuration, which is a
  property of a NIC resource.

So there are two steps to create for the VM:

create the nat rule in the load balancer, the PowerShell command is Add-AzLoadBalancerInboundNatRuleConfig, Azure CLI command is az network lb inbound-nat-rule create.

associate the nat rule to the VM nic, the PowerShell command is Add-AzNetworkInterfaceIpConfig, Azure CLI command is az network nic ip-config inbound-nat-rule add.

You can add the Nat rule in one step in the portal, but you need to do two steps through command. And you also need to pay attention to that the NSG rule is also necessary to allow the traffic to the port.

Body:
In an azure RM load-balancer I can create a nat rule FTP using powershell, but would also like to set the target virtual machine using powershell. The only way I know how to set the target is in the portal.

I have two VMs in the load balancer. I tried using Add-AzLoadBalancerInboundNatRuleConfig, but don't see a parameter for target VM.

My script:
$lb  |  Add-AzLoadBalancerInboundNatRuleConfig -Name $EndpointName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $i -BackendPort $i

If it's not possible to set the target in powershell, what alternatives are there besides the portal?

I found the answer. The key is to add the LoadBalancerInboundNatRuleId to the Ip Configuration.

Here's a function to get the LoadBalancerInboundNatRuleId that I created for this purpose:

Function natRuleID ($sourcePortName) {
return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
}

And here is my sample script that adds two load balancer nat rules and then sets the target network interface for a virtual machine:

# Add Load Balancer Nat Rules:
$lb = Get-AzLoadBalancer -Name $lbName -ResourceGroupName $rgName
$feip = Get-AzLoadBalancerFrontendIpConfig -Name $feipName -LoadBalancer $lb
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleRdpName-FrontendIpConfiguration $feip -Protocol tcp -FrontendPort $rdpPortNumber -BackendPort 3389
$lb | Add-AzLoadBalancerInboundNatRuleConfig -Name $natRuleFtpName -FrontendIPConfiguration $feip -Protocol "Tcp" -FrontendPort $ftpPublicPortForImplicit990  -BackendPort 990
$lb | Set-AzLoadBalancer  #save the new LB rules

# Set nat rule targets:
Function natRuleID ($sourcePortName) {
    return  "/subscriptions/$subscriptionID/resourceGroups/$rgName/providers/Microsoft.Network/loadBalancers/$lbName/InboundNatRules/$sourcePortName"
    }
$rules = @()
$rules = $rules += natRuleID($natRuleFtpName)
$rules = $rules += natRuleID($natRuleRdpName)
$nic = Get-AzNetworkInterface -Name $nicName -ResourceGroupName $rgName
$nic | Set-AzNetworkInterfaceIpConfig -Name $ipConfigName  -LoadBalancerInboundNatRuleId $rules
$nic | Set-AzNetworkInterface #save the new ipConfig rules


问:
How to use join properply in codeigniter with multiple tables
Im trying to connect 5 tables in codeigniter and i am having some trouble getting the correct result please help. I think the error is in my query but Im not sure.

I've tried many join statements already but I cant seem to find the correct answer. That's why I posted it here because im hopeless alreadyyy please help someoneee ~

Here are the schema and DB. Hope this helps

Schema

Database

```<code> public function get_receiving_details_mawb($id){

        $this->ops_db->select('d.quantity, e.sku_code, a.quantity AS actual,
        abs(d.quantity - a.quantity) AS variance');
        $this->ops_db->from('sk_rcv_d a');
        $this->ops_db->where_in('a.rcv_id', $id);
        $this->ops_db->join('sk_rcv_h b', 'a.rcv_id = b.id', 'inner');
        $this->ops_db->join('sk_booking_h c', 'b.booking_id = c.id','inner');
        $this->ops_db->join('sk_booking_d d', 'c.id = d.book_id', 'inner');
        $this->ops_db->join('sk_item e', 'd.item_id = e.id', 'inner');
        $this->ops_db->group_by('d.id');//d.id
        $query = $this->ops_db->get();
        return $query->result_array();
    }

    public function get_rcvh_mawb($id) {

       $this->ops_db->where("mawb_no", $id);
       $query = $this->ops_db->get("sk_rcv_h");
       $how = array();
       foreach($query->result_array() as $row) {
         $id = $row['id'];
         $how[] = $id;
       }
       return $how;
    }

-------------------------------
        $wat  = $this->wh_db->get_rcvh_mawb($mawb);
        $item_details = array();
        $items = array();
        $results  = $this->wh_db->get_receiving_details_mawb($wat);
        foreach($results as $res) {
          extract($res);
          if (! array_key_exists($sku_code, $items)) {
          $items[$sku_code] = array("sku_code" => $sku_code, "quantity" => 0,
          "actual" => 0, "variance" => 0);
         }
         $items[$sku_code]['quantity'] = $quantity;
         $items[$sku_code]['actual'] += $actual;
         $items[$sku_code]['variance'] = $items[$sku_code]['quantity'] -
         $items[$sku_code]['actual'];
        }

        foreach($items as $res) {
        $item_details[] = array("sku" => $res['sku_code'], "qty" =>
        $res['quantity'], "actual" => $res['actual'], "variance" =>
        $res['variance']);
        }

        $final     = array("mawb_no" => $mawb, "status" => $stat_api,
        "status_date" => $stat_api_date, "items" => $item_details);
</code>```

This is the result I got:

```<code>     {
        "mawb_no": "MASTERPOD-1",
        "status": "Received",
        "status_date": "2019-05-27 19:35:42",
        "items": [
            {
                "sku": "RTISSUE",
                "qty": "50",
                "actual": 50,
                "variance": 0
            },
            {
                "sku": "ISOALCO",
                "qty": "102",
                "actual": 50,
                "variance": 52
            }
        ]
    }
</code>```

What i should get:

```<code>    {
        "mawb_no": "MASTERPOD-1",
        "status": "Received",
        "status_date": "2019-05-27 19:35:42",
        "items": [
            {
                "sku": "RTISSUE",
                "qty": "50",
                "actual": 50,
                "variance": 0
            },
            {
                "sku": "ISOALCO",
                "qty": "102",
                "actual": 102,
                "variance": 0
            }
        ]
     }
</code>```

答:
According to your scheme its all working fine but with inner join it gives you all four possible results according to the conditions in you example, you need to specify exactly what is your desired result upon getting the result, you need a condition, by adding having condition i was able to mimic your desired results, i'm not sure that it will be valid in all cases but you can try and you got the idea anyways ( conditional inputs or conditional results ):

```<code>$this->db->select('d.quantity, e.sku_code, a.quantity AS actual, abs(d.quantity - a.quantity) AS variance');
$this->db->from('sk_rcv_d a');
$this->db->where('a.rcv_id', $id);
$this->db->join('sk_rcv_h b', 'a.rcv_id = b.id', 'inner');
$this->db->join('sk_booking_h c', 'b.booking_id = c.id', 'inner');
$this->db->join('sk_booking_d d', 'c.id = d.book_id', 'inner');
$this->db->join('sk_item e', 'd.item_id = e.id', 'inner');
$this->db->having('actual = quantity');
</code>```

You don't need groub_by in this case, and the above query will give you this:

```<code>array(2) {
  [0] => array(4) {
    ["quantity"] => string(2) "50"
    ["sku_code"] => string(7) "RTISSUE"
    ["actual"] => string(2) "50"
    ["variance"] => string(1) "0"
  }
  [1] => array(4) {
    ["quantity"] => string(3) "102"
    ["sku_code"] => string(7) "ISOALCO"
    ["actual"] => string(3) "102"
    ["variance"] => string(1) "0"
  }
}
</code>```

Body:
Im trying to connect 5 tables in codeigniter and i am having some trouble getting the correct result please help. I think the error is in my query but Im not sure.

I've tried many join statements already but I cant seem to find the correct answer. That's why I posted it here because im hopeless alreadyyy please help someoneee ~

Here are the schema and DB. Hope this helps

Schema

Database

 public function get_receiving_details_mawb($id){

        $this->ops_db->select('d.quantity, e.sku_code, a.quantity AS actual,
        abs(d.quantity - a.quantity) AS variance');
        $this->ops_db->from('sk_rcv_d a');
        $this->ops_db->where_in('a.rcv_id', $id);
        $this->ops_db->join('sk_rcv_h b', 'a.rcv_id = b.id', 'inner');
        $this->ops_db->join('sk_booking_h c', 'b.booking_id = c.id','inner');
        $this->ops_db->join('sk_booking_d d', 'c.id = d.book_id', 'inner');
        $this->ops_db->join('sk_item e', 'd.item_id = e.id', 'inner');
        $this->ops_db->group_by('d.id');//d.id
        $query = $this->ops_db->get();
        return $query->result_array();
    }

    public function get_rcvh_mawb($id) {

       $this->ops_db->where("mawb_no", $id);
       $query = $this->ops_db->get("sk_rcv_h");
       $how = array();
       foreach($query->result_array() as $row) {
         $id = $row['id'];
         $how[] = $id;
       }
       return $how;
    }

-------------------------------
        $wat  = $this->wh_db->get_rcvh_mawb($mawb);
        $item_details = array();
        $items = array();
        $results  = $this->wh_db->get_receiving_details_mawb($wat);
        foreach($results as $res) {
          extract($res);
          if (! array_key_exists($sku_code, $items)) {
          $items[$sku_code] = array("sku_code" => $sku_code, "quantity" => 0,
          "actual" => 0, "variance" => 0);
         }
         $items[$sku_code]['quantity'] = $quantity;
         $items[$sku_code]['actual'] += $actual;
         $items[$sku_code]['variance'] = $items[$sku_code]['quantity'] -
         $items[$sku_code]['actual'];
        }

        foreach($items as $res) {
        $item_details[] = array("sku" => $res['sku_code'], "qty" =>
        $res['quantity'], "actual" => $res['actual'], "variance" =>
        $res['variance']);
        }

        $final     = array("mawb_no" => $mawb, "status" => $stat_api,
        "status_date" => $stat_api_date, "items" => $item_details);

This is the result I got:

     {
        "mawb_no": "MASTERPOD-1",
        "status": "Received",
        "status_date": "2019-05-27 19:35:42",
        "items": [
            {
                "sku": "RTISSUE",
                "qty": "50",
                "actual": 50,
                "variance": 0
            },
            {
                "sku": "ISOALCO",
                "qty": "102",
                "actual": 50,
                "variance": 52
            }
        ]
    }

What i should get:

    {
        "mawb_no": "MASTERPOD-1",
        "status": "Received",
        "status_date": "2019-05-27 19:35:42",
        "items": [
            {
                "sku": "RTISSUE",
                "qty": "50",
                "actual": 50,
                "variance": 0
            },
            {
                "sku": "ISOALCO",
                "qty": "102",
                "actual": 102,
                "variance": 0
            }
        ]
     }

Body:
According to your scheme its all working fine but with inner join it gives you all four possible results according to the conditions in you example, you need to specify exactly what is your desired result upon getting the result, you need a condition, by adding having condition i was able to mimic your desired results, i'm not sure that it will be valid in all cases but you can try and you got the idea anyways ( conditional inputs or conditional results ):

$this->db->select('d.quantity, e.sku_code, a.quantity AS actual, abs(d.quantity - a.quantity) AS variance');
$this->db->from('sk_rcv_d a');
$this->db->where('a.rcv_id', $id);
$this->db->join('sk_rcv_h b', 'a.rcv_id = b.id', 'inner');
$this->db->join('sk_booking_h c', 'b.booking_id = c.id', 'inner');
$this->db->join('sk_booking_d d', 'c.id = d.book_id', 'inner');
$this->db->join('sk_item e', 'd.item_id = e.id', 'inner');
$this->db->having('actual = quantity');

You don't need groub_by in this case, and the above query will give you this:

array(2) {
  [0] => array(4) {
    ["quantity"] => string(2) "50"
    ["sku_code"] => string(7) "RTISSUE"
    ["actual"] => string(2) "50"
    ["variance"] => string(1) "0"
  }
  [1] => array(4) {
    ["quantity"] => string(3) "102"
    ["sku_code"] => string(7) "ISOALCO"
    ["actual"] => string(3) "102"
    ["variance"] => string(1) "0"
  }
}


问:
Monitor and Detect a change in Excel file and refresh location of the web page
I have an excel file where data is refreshing from third party application.

Problem to solve: My DJANGO web application should monitor that excel file continuously and detect a change from that excel file. Whenever there is a change then particular location of web page should be refreshed.

Could somebody please give suggestions to achieve this functionality?

答: Basically, you need to check with a runtime process (e.g a cron) if the previously version of your file is different to the new version calling your runtime process. This means that you could read the content of the CSV file (could be with import csv or using pandas ìmport pandas as pd) and store it in some place (e.g another temporal file), then (according the time of you define to execute your cron) the content will be check again, and compare it against the content of what you previously have stored. If this happens, you could use Ajax to refresh your website section or use a real time library to refresh automatically, and store the new csv content again.


问:
How to extract multiple columns according to condition
I am new to this data analysis, I am currently working with a company's data. Where I have more than 100 columns worth of data. These columns are interrelated to each other, where the first four columns provide the description of the data so (id, domain, description, actual target). Rest of the other columns are just other numerical value that basically states the target value they reached for that day.

So, basically the question the company asked me to find is, which id have fluctuated the most and which id have failing to reach target.

I wanted to know, how i can properly execute the question, as its my very first time doing data analysis for a company.

What i did was firstly, i grouped the domain to see how many id's are associated with different domains.

Then I went about finding mean of every id in each domain (grouped). In finding the mean i can basically see if the id is failing to reach the target for that domain. Self explanatory, if most id's are failing to reach the target in specific domain, that means the domain/id is failing to reach the target.

```<code>df.groupby('Domain)['Id'].count() /*This tells me different domain with how many id's are there */
df[(df.Domain == 'Finance')].mean(axis = 1) /*Finance is just one of the domain that has different id's associated to it */
</code>```

But what the problem i am facing is that i can extract the mean of each id in grouped domain, however I can't seem to open the id and target columns that is associated to those mean values. So i can compare if the mean value is reaching the target value.

答:
I guess you have a dataset similar to this:

```<code>import pandas as pd
data = {'domain': ['Finance', 'RD', 'Finance', 'RD'], 'target': [34, 2, 41, 86]}
df = pd.DataFrame(data)

    domain  target
0  Finance      34
1       RD       2
2  Finance      41
3       RD      86
</code>```

Of course, you can use groupby to find statistical values of specific columns. For example,

```<code>df_grouped = df.groupby('domain')['target'].sum().reset_index()

    domain  target
0  Finance      75
1       RD      88
</code>```

By using mean() or other statistical functions, you must be aware of your sample size which might affect your interpretation. For instance,

```<code>data = {'domain': ['Finance', 'RD', 'RD', 'RD'], 'target': [100, 2, 54, 86]}
df = pd.DataFrame(data)

    domain  target
0  Finance     100
1       RD       2
2       RD      54
3       RD      86

df_grouped = df.groupby('domain')['target'].mean()

    domain      target
0  Finance  100.000000
1       RD   47.333333
</code>```

Data Visualization

```<code>import matplotlib.pyplot as plt
df_grouped.plot.bar()
plt.show()
</code>```

Body:
I am new to this data analysis, I am currently working with a company's data. Where I have more than 100 columns worth of data. These columns are interrelated to each other, where the first four columns provide the description of the data so (id, domain, description, actual target). Rest of the other columns are just other numerical value that basically states the target value they reached for that day.

So, basically the question the company asked me to find is, which id have fluctuated the most and which id have failing to reach target.

I wanted to know, how i can properly execute the question, as its my very first time doing data analysis for a company.

What i did was firstly, i grouped the domain to see how many id's are associated with different domains.

Then I went about finding mean of every id in each domain (grouped). In finding the mean i can basically see if the id is failing to reach the target for that domain. Self explanatory, if most id's are failing to reach the target in specific domain, that means the domain/id is failing to reach the target.

df.groupby('Domain)['Id'].count() /*This tells me different domain with how many id's are there */
df[(df.Domain == 'Finance')].mean(axis = 1) /*Finance is just one of the domain that has different id's associated to it */

But what the problem i am facing is that i can extract the mean of each id in grouped domain, however I can't seem to open the id and target columns that is associated to those mean values. So i can compare if the mean value is reaching the target value.

Body:
I guess you have a dataset similar to this:

import pandas as pd
data = {'domain': ['Finance', 'RD', 'Finance', 'RD'], 'target': [34, 2, 41, 86]}
df = pd.DataFrame(data)

    domain  target
0  Finance      34
1       RD       2
2  Finance      41
3       RD      86

Of course, you can use groupby to find statistical values of specific columns. For example,

df_grouped = df.groupby('domain')['target'].sum().reset_index()

    domain  target
0  Finance      75
1       RD      88

By using mean() or other statistical functions, you must be aware of your sample size which might affect your interpretation. For instance,

data = {'domain': ['Finance', 'RD', 'RD', 'RD'], 'target': [100, 2, 54, 86]}
df = pd.DataFrame(data)

    domain  target
0  Finance     100
1       RD       2
2       RD      54
3       RD      86

df_grouped = df.groupby('domain')['target'].mean()

    domain      target
0  Finance  100.000000
1       RD   47.333333

Data Visualization

import matplotlib.pyplot as plt
df_grouped.plot.bar()
plt.show()


问:
Aligning right to left on UICollectionView with contents
I tried with the following question:

Aligning right to left on UICollectionView but it's not achieved my goal.

What I was tried:

In viewDidLoad():

```<code>collectionView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
</code>```

In cellForItemAtIndexPath():

```<code>cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
</code>```

My current CollectionView is on the left, but I want it to look like the CollecitonView on the right.

```<code>dataSource = ["item1","item2","item3","item4","item5","item6"]
</code>```

Update:

Change semanticContentAttribute of the collectionView to .forceRightToLeft

```<code>collectionView.semanticContentAttribute = .forceRightToLeft
</code>```

by  @RajeshKumar answered

I notice. items has spacing too much between two element for example item1 and item2 How can i reduce  that the space and rest of things? ok for me. on the other hand I tried with layout.minimumInteritemSpacing = 0 but it is not worked for me and item3 not alinement right too.

答:
In viewDidLoad():

```<code> let alignedFlowLayout = collectionView.collectionViewLayout as? AlignedCollectionViewFlowLayout
 collectionView.transform = CGAffineTransform(scaleX: -1, y: 1)
 [enter link description here][1]alignedFlowLayout?.horizontalAlignment = .left
</code>```

@Hemang  comment worked for me.

If you have any subviews in your cell, then you have transform it as well. For e.g.

```<code>self.titleLabel.transform = CGAffineTransform(scaleX: -1, y: 1)
</code>```

AlignedCollectionViewFlowLayout

Body:
I tried with the following question:

Aligning right to left on UICollectionView but it's not achieved my goal.

What I was tried:

In viewDidLoad():

collectionView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)

In cellForItemAtIndexPath():

cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)

My current CollectionView is on the left, but I want it to look like the CollecitonView on the right.

dataSource = ["item1","item2","item3","item4","item5","item6"]

Update:

Change semanticContentAttribute of the collectionView to .forceRightToLeft

collectionView.semanticContentAttribute = .forceRightToLeft

by  @RajeshKumar answered

I notice. items has spacing too much between two element for example item1 and item2 How can i reduce  that the space and rest of things? ok for me. on the other hand I tried with layout.minimumInteritemSpacing = 0 but it is not worked for me and item3 not alinement right too.

Body:
In viewDidLoad():

 let alignedFlowLayout = collectionView.collectionViewLayout as? AlignedCollectionViewFlowLayout
 collectionView.transform = CGAffineTransform(scaleX: -1, y: 1)
 [enter link description here][1]alignedFlowLayout?.horizontalAlignment = .left

@Hemang  comment worked for me.

If you have any subviews in your cell, then you have transform it as well. For e.g.

self.titleLabel.transform = CGAffineTransform(scaleX: -1, y: 1)

AlignedCollectionViewFlowLayout