问:
Opened ContextMenu -> RightClick triggers LeftClickCommand in ViewModel
I have a ContextMenu bound to an HierarchicalDataTemplate that displays a TreeView structure. The ContextMenu also is a HierarchicalDataTemplate that obtains its structure through an ObservableCollection of MenuItemViewModels.

My problem is, that when running the program a RightClick on an already opened ContextMenu unwantedly triggers a LeftClick on the MenuItem - why is that so? What am i missing? I am unable to find the error in code and would appreciate any help.

The XAML for the TreeView:

```<code><HierarchicalDataTemplate x:Key="TreeHierarchicalDataTemplate" DataType="{x:Type model:TreeNodeBaseViewModel}" ItemsSource="{Binding Path=SubItems, UpdateSourceTrigger=PropertyChanged}" ItemContainerStyle="{StaticResource  MenuItemTemplateItemContainerStyle}">
<!--...-->
</HierarchicalDataTemplate>

<Style x:Key="MenuItemTemplateItemContainerStyle" TargetType="{x:Type TreeViewItem}">
    <Setter Property="ContextMenu" Value="{DynamicResource MenuItemContextMenu}"/>
    <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
    <Setter Property="AllowDrop" Value="{Binding IsDropAllowed}"/>
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
    <Setter Property="Tag" Value="{Binding}"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsVisible}" Value="False">
            <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
        <Trigger Property="beh:TreeNodeMouseOver.IsMouseDirectlyOverItem" Value="True">
            <Setter Property="Background" Value="AliceBlue" />
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

The XAML for the ContextMenu:

```<code><ContextMenu x:Key="MenuItemContextMenu" ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=TreeViewModel.MenuItems, UpdateSourceTrigger=PropertyChanged}">
    <ContextMenu.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type model:MenuItemBaseViewModel}" ItemsSource="{Binding Path=SubItems, UpdateSourceTrigger=PropertyChanged}">
            <TextBlock Text="{Binding Header}"/>
        </HierarchicalDataTemplate>
    </ContextMenu.ItemTemplate>
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="ToolTip" Value="{Binding ToolTip}"/>
            <Setter Property="IsHitTestVisible" Value="True"/>
            <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
            <Setter Property="Command" Value="{Binding MouseLeftButtonDownCommand}"/> <!--LeftClick is bound to ViewModel here, but RightClick is not even defined anywhere in MenuItem or ViewModel-->
            <Style.Triggers>
                <DataTrigger Binding="{Binding VisibleSubItems}" Value="0">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type MenuItem}">
                                <Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                                    <Grid Margin="-1">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition MinWidth="22" SharedSizeGroup="MenuItemIconColumnGroup" Width="Auto"/>
                                            <ColumnDefinition Width="13"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="20"/>
                                            <ColumnDefinition SharedSizeGroup="MenuItemIGTColumnGroup" Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto" />
                                        </Grid.ColumnDefinitions>
                                        <ContentPresenter x:Name="Icon" Content="{TemplateBinding Icon}" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/>
                                        <Border x:Name="GlyphPanel" BorderBrush="#FF26A0DA" BorderThickness="1" Background="#3D26A0DA" ClipToBounds="False" HorizontalAlignment="Center" Height="22" Margin="-1,0,0,0" Visibility="Hidden" VerticalAlignment="Center" Width="22">
                                            <Path x:Name="Glyph" Data="F1M10,1.2L4.7,9.1 4.5,9.1 0,5.2 1.3,3.5 4.3,6.1 8.3,0 10,1.2z" Fill="#FF212121" FlowDirection="LeftToRight" Height="11" Width="10"/>
                                        </Border>
                                        <ContentPresenter x:Name="menuHeaderContainer" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Grid.Column="2" ContentStringFormat="{TemplateBinding HeaderStringFormat}" ContentSource="Header" HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center"/>
                                        <TextBlock x:Name="menuGestureText" Grid.Column="4" Margin="{TemplateBinding Padding}" Opacity="0.7" Text="{TemplateBinding InputGestureText}" VerticalAlignment="Center"/>
                                        <Button Grid.Column="5" Margin="2" Command="{Binding EditCommand}" Visibility="{Binding IsEditVisible, Converter={StaticResource BooleanToVisibilityConverter}}" Background="Transparent" BorderThickness="0">
                                            <iconPacks:PackIconMaterialLight Width="14" Height="14" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center" Kind="Cog" />
                                        </Button>
                                        <Button Grid.Column="6" Margin="2" Command="{Binding HelpCommand}" Visibility="{Binding IsInfoVisible, Converter={StaticResource BooleanToVisibilityConverter}}" Background="Transparent" BorderThickness="0">
                                            <iconPacks:PackIconMaterial  Width="14" Height="14" Foreground="Blue" HorizontalAlignment="Center" VerticalAlignment="Center" Kind="InformationOutline" />
                                        </Button>
                                    </Grid>
                                </Border>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="Icon" Value="{x:Null}">
                                        <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
                                    </Trigger>
                                    <Trigger Property="IsChecked" Value="True">
                                        <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/>
                                        <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/>
                                    </Trigger>
                                    <Trigger Property="IsHighlighted" Value="True">
                                        <Setter Property="Background" TargetName="templateRoot" Value="#3D26A0DA"/>
                                        <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF26A0DA"/>
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="#FF707070"/>
                                        <Setter Property="Fill" TargetName="Glyph" Value="#FF707070"/>
                                    </Trigger>
                                    <MultiTrigger>
                                        <MultiTrigger.Conditions>
                                            <Condition Property="IsHighlighted" Value="True"/>
                                            <Condition Property="IsEnabled" Value="False"/>
                                        </MultiTrigger.Conditions>
                                        <Setter Property="Background" TargetName="templateRoot" Value="#0A000000"/>
                                        <Setter Property="BorderBrush" TargetName="templateRoot" Value="#21000000"/>
                                    </MultiTrigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding IsVisible}" Value="false">
                    <Setter Property="MenuItem.Visibility" Value="Collapsed"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding PackIcon.IconType}" Value="{x:Type iconPacks:PackIconSimpleIconsKind}">
                    <Setter Property="MenuItem.Icon" Value="{StaticResource Simple}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding PackIcon.IconType}" Value="{x:Type iconPacks:PackIconEntypoKind}">
                    <Setter Property="MenuItem.Icon" Value="{StaticResource Entypo}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding PackIcon.IconType}" Value="{x:Type iconPacks:PackIconFontAwesomeKind}">
                    <Setter Property="MenuItem.Icon" Value="{StaticResource FontAwesome}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding PackIcon.IconType}" Value="{x:Type iconPacks:PackIconMaterialKind}">
                    <Setter Property="MenuItem.Icon" Value="{StaticResource Material}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding PackIcon.IconType}" Value="{x:Type iconPacks:PackIconMaterialLightKind}">
                    <Setter Property="MenuItem.Icon" Value="{StaticResource MaterialLight}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding PackIcon.IconType}" Value="{x:Type iconPacks:PackIconModernKind}">
                    <Setter Property="MenuItem.Icon" Value="{StaticResource Modern}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding PackIcon.IconType}" Value="{x:Type iconPacks:PackIconOcticonsKind}">
                    <Setter Property="MenuItem.Icon" Value="{StaticResource Octicons}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContextMenu.ItemContainerStyle>
    <i:Interaction.Behaviors>
        <beh:EventToCommandBehavior Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=TreeViewModel.ContextMenuOpenedCommand}" Event="Opened" PassArguments="True" />
    </i:Interaction.Behaviors>
</ContextMenu>
</code>```

答:
That behavior is by design. If you want seperate left/right click handlers for your menu items then you need to add the corresponding MouseBindings to your MenuItem InputBindings collection. If you need to do that in a style then you can use the Attach behavior in this question.</p>

```<code><ContextMenu.ItemContainerStyle>
    <Style TargetType="MenuItem">
        <Setter Property="behaviors:Attach.InputBindings">
            <Setter.Value>
                <InputBindingCollection>
                    <MouseBinding Gesture="LeftClick" Command="{Binding LeftClickCommand}" />
                    <MouseBinding Gesture="RightClick" Command="{Binding RightClickCommand}" />
                </InputBindingCollection>
            </Setter.Value>
        </Setter>
    </Style>
</ContextMenu.ItemContainerStyle>
</code>```

Body:
I have a ContextMenu bound to an HierarchicalDataTemplate that displays a TreeView structure. The ContextMenu also is a HierarchicalDataTemplate that obtains its structure through an ObservableCollection of MenuItemViewModels.

My problem is, that when running the program a RightClick on an already opened ContextMenu unwantedly triggers a LeftClick on the MenuItem - why is that so? What am i missing? I am unable to find the error in code and would appreciate any help.

The XAML for the TreeView:

<HierarchicalDataTemplate x:Key="TreeHierarchicalDataTemplate" DataType="{x:Type model:TreeNodeBaseViewModel}" ItemsSource="{Binding Path=SubItems, UpdateSourceTrigger=PropertyChanged}" ItemContainerStyle="{StaticResource  MenuItemTemplateItemContainerStyle}">

</HierarchicalDataTemplate>

</Style>

The XAML for the ContextMenu:

<ContextMenu x:Key="MenuItemContextMenu" ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=TreeViewModel.MenuItems, UpdateSourceTrigger=PropertyChanged}">
    <ContextMenu.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type model:MenuItemBaseViewModel}" ItemsSource="{Binding Path=SubItems, UpdateSourceTrigger=PropertyChanged}">
            <TextBlock Text="{Binding Header}"/>
        </HierarchicalDataTemplate>
    </ContextMenu.ItemTemplate>
    <ContextMenu.ItemContainerStyle>

        </Style>
    </ContextMenu.ItemContainerStyle>

        <beh:EventToCommandBehavior Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=TreeViewModel.ContextMenuOpenedCommand}" Event="Opened" PassArguments="True" />

</ContextMenu>

Body:
That behavior is by design. If you want seperate left/right click handlers for your menu items then you need to add the corresponding MouseBindings to your MenuItem InputBindings collection. If you need to do that in a style then you can use the Attach behavior in this question.

<ContextMenu.ItemContainerStyle>
    <Style TargetType="MenuItem">
        <Setter Property="behaviors:Attach.InputBindings">
            <Setter.Value>
                <InputBindingCollection>
                    <MouseBinding Gesture="LeftClick" Command="{Binding LeftClickCommand}" />
                    <MouseBinding Gesture="RightClick" Command="{Binding RightClickCommand}" />
                </InputBindingCollection>
            </Setter.Value>
        </Setter>
    </Style>
</ContextMenu.ItemContainerStyle>


来源: stackexchange

问:
Is there a native component for the Floating action button in Android Material Design?
My question revolves around the Floating action button that was introduced in Android Material Design.

There are many library offering this component on GitHub as:

Android-floating-action-button

FloatingActionButton

CircularFloatingActionMenu

Fab

Floating-action-button

But my question is:

Is there a native component with the last release of android.support.vX that was built for Floating action button?

Components such as :

android.support.v7.cardview

android.support.v4.widget.DrawerLayout

android.support.v7.widget.RecyclerView

...

答:
All the above answers are now out of date.

FABS are available as part of Material Components for Android:
https://material.io/develop/android/docs/getting-started/

Here is the class: https://developer.android.com/reference/com/google/android/material/floatingactionbutton/FloatingActionButton

Don't miss the Catalog app with working examples:
https://github.com/material-components/material-components-android

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
java bit manipulation
```<code>byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}
</code>```

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

答:
I'm not sure about this. But, my guess is that

```<code>x >>> 1
</code>```

gets promoted to a int from byte, because the literal "1" is an int. Then what you are observing makes sense.

OwnerDisplayName: jbu

Title: java bit manipulation

Body:
byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

Body:
I'm not sure about this. But, my guess is that

x >>> 1

gets promoted to a int from byte, because the literal "1" is an int. Then what you are observing makes sense.

OwnerDisplayName: DasBoot

ContentLicense: CC BY-SA 2.5


问:
Cutting String by using regexp
I want to cut the string using regexp, but not to cut the regexp part...

```<code>String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
String[] substract=path.split("my_");
path=substract1[1].toString();// books/bought/2011/adventure/Black-Ship01/312 pages/...
String[] substract2=path.split("-Ship.."); //split using -Ship and two random simbols
path=substract[1].toString();

RESULT:   path= "books/bought/2011/adventure/Black"
Should be path= "books/bought/2011/adventure/Black-Ship01"
</code>```

so how to add -Ship01 ??

答: Try using positive lookbehind: String[] substract2=path.split("(?<=-Ship..)"). This matches the pattern but doesn't consume the characters.

Title: Cutting String by using regexp

Body:
I want to cut the string using regexp, but not to cut the regexp part...

String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
String[] substract=path.split("my_");
path=substract1[1].toString();// books/bought/2011/adventure/Black-Ship01/312 pages/...
String[] substract2=path.split("-Ship.."); //split using -Ship and two random simbols
path=substract[1].toString();

RESULT:   path= "books/bought/2011/adventure/Black"
Should be path= "books/bought/2011/adventure/Black-Ship01"

so how to add -Ship01 ??


问:
How to run some code before page is displayed
I have trouble running some code before page loads in jquery or js. Anything I do the page would have a brief load then my codes run. I run code before user sees the page but it loads in a brief milliseconds then my code runs.

I have done some solutions and didn't do what I want:

I've put my codes before document.ready

I've put my code in head section

I've put my code in a function then called the function in head tag

I also tried onload() in js

But the same result: my code runs after milliseconds and user sees the page before running code in these milliseconds

Any ideas?

答: You could put your code in 'loading' state of document via document.readyState but in this state DOM is not ready to operate. Here your have example how to use document.readyState https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState#Different_states_of_readiness What actualy do you want to do?


问:
Add files from database project into MSI
I've got a database project, that contains custom SQL scripts, I need to add the scripts to the MSI folder so that my custom action can pick it up and execute them.

Getting the following errors

HeatGeneratedFileList.wxs(6,0): error LGHT0103: The system cannot find the file 'SourceDir\TestScript - Copy.sql'.

HeatGeneratedFileList.wxs(9,0): error LGHT0103: The system cannot find the file 'SourceDir\TestScript.sql'.

I have created done the actions using heat:

```<code> <Target Name="BeforeBuild">
    <HeatDirectory Directory="../Database/DatabaseFiles/" OutputFile="HeatGeneratedFileList.wxs" ComponentGroupName="Database.Installer" DirectoryRefId="INSTALLFOLDER" AutogenerateGuids="true" ToolPath="$(WixToolPath)" SuppressFragments="true" SuppressRegistry="true" SuppressRootDirectory="true" SuppressCom="true" />
  </Target>
</code>```

This is the HeatGeneratedFileList.wxs file

```<code> <?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <DirectoryRef Id="INSTALLFOLDER">
            <Component Id="cmp35BC97AC12F21A6F6154759C2D9B5430" Guid="*">
                <File Id="filDEDB241BDDF1A0CD0B001190398F5F5F" KeyPath="yes" Source="SourceDir\TestScript - Copy.sql" />
            </Component>
            <Component Id="cmp221D9003B2C58612888DBC0D1CEBC730" Guid="*">
                <File Id="filF6EA2F11A51AF10E1517FFB9152307EE" KeyPath="yes" Source="SourceDir\TestScript.sql" />
            </Component>
        </DirectoryRef>
    </Fragment>
    <Fragment>
        <ComponentGroup Id="AgentX.Database.Installer">
            <ComponentRef Id="cmp35BC97AC12F21A6F6154759C2D9B5430" />
            <ComponentRef Id="cmp221D9003B2C58612888DBC0D1CEBC730" />
        </ComponentGroup>
    </Fragment>
</Wix>
</code>```

I want to run this code from my custom action to execute the two scripts:

```<code> private static bool ProcessSQLFile(Session session, string script)
        {
            var success = true;
            try
            {
                var connectionStringBuilder = BuildConnectionString(session);

                var scriptToRun = File.ReadAllText(script);

                var connectionString = new SqlConnection(connectionStringBuilder.ConnectionString);

                var server = new Server(new ServerConnection(connectionString));

                server.ConnectionContext.ExecuteNonQuery(scriptToRun);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                success = false;
            }

            return success;
        }
</code>```

答:
I missed the following in my csproj file:</p>

```<code><ItemGroup>
      <LinkerBindInputPaths Include="%(ProjectReference.RootDir)%(ProjectReference.Directory)bin\$(Configuration)\DatabaseFiles\" />
    </ItemGroup>
</code>```

Body:
I've got a database project, that contains custom SQL scripts, I need to add the scripts to the MSI folder so that my custom action can pick it up and execute them.

Getting the following errors

HeatGeneratedFileList.wxs(6,0): error LGHT0103: The system cannot find the file 'SourceDir\TestScript - Copy.sql'.

HeatGeneratedFileList.wxs(9,0): error LGHT0103: The system cannot find the file 'SourceDir\TestScript.sql'.

I have created done the actions using heat:

 <Target Name="BeforeBuild">
    <HeatDirectory Directory="../Database/DatabaseFiles/" OutputFile="HeatGeneratedFileList.wxs" ComponentGroupName="Database.Installer" DirectoryRefId="INSTALLFOLDER" AutogenerateGuids="true" ToolPath="$(WixToolPath)" SuppressFragments="true" SuppressRegistry="true" SuppressRootDirectory="true" SuppressCom="true" />
  </Target>

This is the HeatGeneratedFileList.wxs file

 <?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <DirectoryRef Id="INSTALLFOLDER">
            <Component Id="cmp35BC97AC12F21A6F6154759C2D9B5430" Guid="*">
                <File Id="filDEDB241BDDF1A0CD0B001190398F5F5F" KeyPath="yes" Source="SourceDir\TestScript - Copy.sql" />
            </Component>
            <Component Id="cmp221D9003B2C58612888DBC0D1CEBC730" Guid="*">
                <File Id="filF6EA2F11A51AF10E1517FFB9152307EE" KeyPath="yes" Source="SourceDir\TestScript.sql" />
            </Component>
        </DirectoryRef>
    </Fragment>
    <Fragment>
        <ComponentGroup Id="AgentX.Database.Installer">
            <ComponentRef Id="cmp35BC97AC12F21A6F6154759C2D9B5430" />
            <ComponentRef Id="cmp221D9003B2C58612888DBC0D1CEBC730" />
        </ComponentGroup>
    </Fragment>
</Wix>

I want to run this code from my custom action to execute the two scripts:

 private static bool ProcessSQLFile(Session session, string script)
        {
            var success = true;
            try
            {
                var connectionStringBuilder = BuildConnectionString(session);

                var scriptToRun = File.ReadAllText(script);

                var connectionString = new SqlConnection(connectionStringBuilder.ConnectionString);

                var server = new Server(new ServerConnection(connectionString));

                server.ConnectionContext.ExecuteNonQuery(scriptToRun);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                success = false;
            }

            return success;
        }

Body:
I missed the following in my csproj file:

<ItemGroup>
      <LinkerBindInputPaths Include="%(ProjectReference.RootDir)%(ProjectReference.Directory)bin\$(Configuration)\DatabaseFiles\" />
    </ItemGroup>


问:
.NET Console.Readline doesn't read the first line entered
I wrote a console application but the first input line is always ignored.

```<code>static void Main(string[] args)
{
        try
        {
            string line;

            while ((line = Console.ReadLine()) != "exit")
            {
                string input = Console.ReadLine().ToString();
                Console.WriteLine("I wrote: " + input);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
}
</code>```

When I run this, the result is as follows:

Any ideas why this is happening? I already tried writing a line before the first line, but the same problem occurs.

答:
This way:

```<code>static void Main(string[] args)
{
    try
    {
        string line;
        while ((line = Console.ReadLine()) != "exit")
        {
            Console.WriteLine("I writed: " + line);
            string input = Console.ReadLine().ToString();
            Console.WriteLine("I writed: " + input);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
</code>```

You were printing only input and never line

Maybe you wanted to do it this way:

```<code>static void Main(string[] args)
{
    try
    {
        string input;
        while ((input = Console.ReadLine()) != "exit")
        {
            Console.WriteLine("I writed: " + input);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
</code>```

Body:
I wrote a console application but the first input line is always ignored.

static void Main(string[] args)
{
        try
        {
            string line;

            while ((line = Console.ReadLine()) != "exit")
            {
                string input = Console.ReadLine().ToString();
                Console.WriteLine("I wrote: " + input);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
}

When I run this, the result is as follows:

Any ideas why this is happening? I already tried writing a line before the first line, but the same problem occurs.

Body:
This way:

static void Main(string[] args)
{
    try
    {
        string line;
        while ((line = Console.ReadLine()) != "exit")
        {
            Console.WriteLine("I writed: " + line);
            string input = Console.ReadLine().ToString();
            Console.WriteLine("I writed: " + input);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

You were printing only input and never line

Maybe you wanted to do it this way:

static void Main(string[] args)
{
    try
    {
        string input;
        while ((input = Console.ReadLine()) != "exit")
        {
            Console.WriteLine("I writed: " + input);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


问:
Homework about using a file for input in bash
So basically i have been assigned this homework in which i have to make a bash script that gets its input from a file of numbers, and exports the bigger number, the smaller number their sum and their average.

I have tried to find a way to do this in a simple way, he told us to do it in a fashion of ./bashscript < numbers.txt, however i cant seem to know how to search for that neither can i find a clear simple solution to the problem, i guess that finding the bigger and smaller number as well as the average should be simple once i get some stuff going but now i am at a loss...

if i were to input a .txt file that had:
3
4
5
3
2
1

It should give me the greater : 5
the smaller: 1
the amount:6
and an average:3

答:
you mean something like this?

```<code>#!/bin/bash

# read data from stdin
read -r data

# read numbers into array
IFS=' ' arr=($data)

# initialize max and min with first number
max=${arr[0]}
min=${arr[0]}

# loop over all numbers
for value in "${arr[@]}"; do

   # if value greater then max, save value as max
   [[ $value > $max ]] && max="$value"

   # if value lower than min, save value as min
   [[ $value < $min ]] && min="$value"

   # sum values
   (( sum += value ))
done

# get count of array entries
amount="${#arr[@]}"

# calculate average
(( avr = sum / amount ))

# print output
printf "the greater: %d the smaller: %d the amount: %d average: %d\n" "$max" "$min" "$amount" "$avr"
</code>```

Usage

```<code>script.sh < a.txt
</code>```

Output

```<code>the greater: 5 the smaller: 1 the amount: 6 average: 3
</code>```

Body:
you mean something like this?

#!/bin/bash

# read data from stdin
read -r data

# read numbers into array
IFS=' ' arr=($data)

# initialize max and min with first number
max=${arr[0]}
min=${arr[0]}

# loop over all numbers
for value in "${arr[@]}"; do

   # if value greater then max, save value as max
   [[ $value > $max ]] && max="$value"

   # if value lower than min, save value as min
   [[ $value < $min ]] && min="$value"

   # sum values
   (( sum += value ))
done

# get count of array entries
amount="${#arr[@]}"

# calculate average
(( avr = sum / amount ))

# print output
printf "the greater: %d the smaller: %d the amount: %d average: %d\n" "$max" "$min" "$amount" "$avr"

Usage

script.sh < a.txt

Output

the greater: 5 the smaller: 1 the amount: 6 average: 3


问:
Why does my custom checkbox not correctly propagate change value if I set the type after view init?
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

```<code><a-component-that-handles-animating-placeholder-etc>
    <input custom-checkbox formControlName="field"/>
</<a-component-that-handles-animating-placeholder-etc>
</code>```

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

```<code><custom-input [disabled]="isDisabled"]></custom-input>
</code>```

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

```<code>  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }
</code>```

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

```<code><input type="checkbox" custom-checkbox/>
</code>```

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k

答:
The answer seems to be that the Angular framework declares how to deal with form controls before host binding kicks in which means that for checkboxes the listener for its value has already been setup to point to input.value, and later changing the input type doesnt change the listener.

From what I have tried I think there is no real solution, you just have to ensure the control has a type for your ks-checkbox directive / component. You can do that using the parentElement property if you DI the elementRef.

Body:
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

    <input custom-checkbox formControlName="field"/>
</

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

<custom-input [disabled]="isDisabled"]></custom-input>

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

<input type="checkbox" custom-checkbox/>

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k


问:
Test mode of stripe :: CONNECTED_STRIPE_ACCOUNT_ID
From where can I get the CONNECTED_STRIPE_ACCOUNT_ID

Can anyone help me with the steps to obtain the same for the test mode of stripe?

答:
This is the ID of the connected account that you want to perform operations on. It should be in the format acct_12345. You can find it in your dashboard:

Go to https://dashboard.stripe.com/test/connect/accounts/overview

Click on the account you want

The account ID is in the top right


问:
setState() block the UI when two setState() run
Here is my componentDidMount() method :

componentDidMount() {
    const subscription = accelerometer.subscribe(({ x, y, z, timestamp }) => {
        x = Math.trunc(x*100);
        this.setState({x})
    });
}
```

<p>In above method, every 100 millisecond state is changing. I used that state in my <code>render()</code> method as below : </p>

<pre class="lang-js prettyprint-override"><code>render() {
    const animatedImageStyle = StyleSheet.flatten([
      styles.captureButton,
      {
        transform: [{rotateZ:this.state.x + 'deg'}]
      }
    ])

    return (
      <SideMenu
        menu={leftMenu}
        isOpen={this.state.isOpenLeftMenu}
        menuPosition={'left'}
        bounceBackOnOverdraw={false}
        onChange={(isOpenLeftMenu) => this.updateLeftMenuState(isOpenLeftMenu)}
      >
        <View>
            <TouchableOpacity
                activeOpacity={0.5}
                onPress={(this.state.recordingMode == 'camera')?() => this.takePicture():() => this.toggleRecording()}
              >
                <Image
                  source={require('../assets/imgs/forRotate.png')}
                  style={animatedImageStyle}
                />
            </TouchableOpacity>
        </View>
      </SideMenu>
    )
}
</code>```

Now, the problem is that when I trying to open sidemenu, it is not opening, I mean it opening but hanging too much. My whole app hanging too much.

I think that's because of below method :

updateLeftMenuState(isMenuOpen) {
    this.setState({
      isOpenLeftMenu:isMenuOpen
    })
}
```

Notice that I am updating another state called isOpenLeftMenu, which may blocked during I update state x.

Can anyone tell me what't going wrong here ?

答: you can move the animation view in a separate component along with subscription logic. So the state update of that component won't affect the SideMenu component.</p>

Body:
Here is my componentDidMount() method :

componentDidMount() {
    const subscription = accelerometer.subscribe(({ x, y, z, timestamp }) => {
        x = Math.trunc(x*100);
        this.setState({x})
    });
}

In above method, every 100 millisecond state is changing. I used that state in my render() method as below :

render() {
    const animatedImageStyle = StyleSheet.flatten([
      styles.captureButton,
      {
        transform: [{rotateZ:this.state.x + 'deg'}]
      }
    ])

    return (
      <SideMenu
        menu={leftMenu}
        isOpen={this.state.isOpenLeftMenu}
        menuPosition={'left'}
        bounceBackOnOverdraw={false}
        onChange={(isOpenLeftMenu) => this.updateLeftMenuState(isOpenLeftMenu)}
      >
        <View>
            <TouchableOpacity
                activeOpacity={0.5}
                onPress={(this.state.recordingMode == 'camera')?() => this.takePicture():() => this.toggleRecording()}
              >
                <Image
                  source={require('../assets/imgs/forRotate.png')}
                  style={animatedImageStyle}
                />
            </TouchableOpacity>
        </View>
      </SideMenu>
    )
}

Now, the problem is that when I trying to open sidemenu, it is not opening, I mean it opening but hanging too much. My whole app hanging too much.

I think that's because of below method :

updateLeftMenuState(isMenuOpen) {
    this.setState({
      isOpenLeftMenu:isMenuOpen
    })
}

Notice that I am updating another state called isOpenLeftMenu, which may blocked during I update state x.

Can anyone tell me what't going wrong here ?


问:
Error: No matching distribution found for pip
I am trying to install pip in my python 2.6.6, I have Oracle Linux 6

I followed the answers given at this link Link

I downloaded get-pip.py file and ran the following command

```<code>sudo python2.6 get-pip.py
</code>```

However I get the following error

```<code>[root@bigdatadev3 Downloads]# sudo python2.6 get-pip.py
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
Collecting pip
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad210>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cadad0>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad6d0>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad790>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad110>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Could not find a version that satisfies the requirement pip (from versions: )
No matching distribution found for pip
</code>```

The error shows some network issue, but I have full open internet access here.

How can I install pip?

I also tried yum, yum install python-pip but it gave the following message

```<code>[root@bigdatadev3 ~]# yum install python-pip
Loaded plugins: refresh-packagekit, security, ulninfo
Setting up Install Process
No package python-pip available.
Error: Nothing to do
</code>```

Update 1:

I used the following command,

```<code>python get-pip.py --proxy="MY_PROXY"
</code>```

I get the following error

```<code>DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
    Collecting pip
    Exception:
    Traceback (most recent call last):
      File "/tmp/tmpnz7ISh/pip.zip/pip/basecommand.py", line 215, in main
        status = self.run(options, args)
      File "/tmp/tmpnz7ISh/pip.zip/pip/commands/install.py", line 324, in run
        requirement_set.prepare_files(finder)
      File "/tmp/tmpnz7ISh/pip.zip/pip/req/req_set.py", line 380, in prepare_files
        ignore_dependencies=self.ignore_dependencies))
      File "/tmp/tmpnz7ISh/pip.zip/pip/req/req_set.py", line 554, in _prepare_file
        require_hashes
      File "/tmp/tmpnz7ISh/pip.zip/pip/req/req_install.py", line 278, in populate_link
        self.link = finder.find_requirement(self, upgrade)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 465, in find_requirement
        all_candidates = self.find_all_candidates(req.name)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 423, in find_all_candidates
        for page in self._get_pages(url_locations, project_name):
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 568, in _get_pages
        page = self._get_page(location)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 683, in _get_page
        return HTMLPage.get_page(link, session=self.session)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 792, in get_page
        "Cache-Control": "max-age=600",
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/sessions.py", line 488, in get
        return self.request('GET', url, **kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/download.py", line 386, in request
        return super(PipSession, self).request(method, url, *args, **kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/sessions.py", line 475, in request
        resp = self.send(prep, **send_kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/sessions.py", line 596, in send
        r = adapter.send(request, **kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/cachecontrol/adapter.py", line 47, in send
        resp = super(CacheControlAdapter, self).send(request, **kw)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 390, in send
        conn = self.get_connection(request.url, proxies)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 290, in get_connection
        proxy_manager = self.proxy_manager_for(proxy)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
        **proxy_kwargs
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 43, in SOCKSProxyManager
        raise InvalidSchema("Missing dependencies for SOCKS support.")
    InvalidSchema: Missing dependencies for SOCKS support.
</code>```

答: First run cmd as administrator in windows. Then just try python get-pip.py --trusted-host=files.pythonhosted.org --trusted-host=pypi.org. I have tried and it works for me.

Body:
I am trying to install pip in my python 2.6.6, I have Oracle Linux 6

I followed the answers given at this link Link

I downloaded get-pip.py file and ran the following command

sudo python2.6 get-pip.py

However I get the following error

[root@bigdatadev3 Downloads]# sudo python2.6 get-pip.py
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
Collecting pip
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad210>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cadad0>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad6d0>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad790>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x3cad110>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/pip/
  Could not find a version that satisfies the requirement pip (from versions: )
No matching distribution found for pip

The error shows some network issue, but I have full open internet access here.

How can I install pip?

I also tried yum, yum install python-pip but it gave the following message

[root@bigdatadev3 ~]# yum install python-pip
Loaded plugins: refresh-packagekit, security, ulninfo
Setting up Install Process
No package python-pip available.
Error: Nothing to do

Update 1:

I used the following command,

python get-pip.py --proxy="MY_PROXY"

I get the following error

DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
    Collecting pip
    Exception:
    Traceback (most recent call last):
      File "/tmp/tmpnz7ISh/pip.zip/pip/basecommand.py", line 215, in main
        status = self.run(options, args)
      File "/tmp/tmpnz7ISh/pip.zip/pip/commands/install.py", line 324, in run
        requirement_set.prepare_files(finder)
      File "/tmp/tmpnz7ISh/pip.zip/pip/req/req_set.py", line 380, in prepare_files
        ignore_dependencies=self.ignore_dependencies))
      File "/tmp/tmpnz7ISh/pip.zip/pip/req/req_set.py", line 554, in _prepare_file
        require_hashes
      File "/tmp/tmpnz7ISh/pip.zip/pip/req/req_install.py", line 278, in populate_link
        self.link = finder.find_requirement(self, upgrade)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 465, in find_requirement
        all_candidates = self.find_all_candidates(req.name)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 423, in find_all_candidates
        for page in self._get_pages(url_locations, project_name):
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 568, in _get_pages
        page = self._get_page(location)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 683, in _get_page
        return HTMLPage.get_page(link, session=self.session)
      File "/tmp/tmpnz7ISh/pip.zip/pip/index.py", line 792, in get_page
        "Cache-Control": "max-age=600",
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/sessions.py", line 488, in get
        return self.request('GET', url, **kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/download.py", line 386, in request
        return super(PipSession, self).request(method, url, *args, **kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/sessions.py", line 475, in request
        resp = self.send(prep, **send_kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/sessions.py", line 596, in send
        r = adapter.send(request, **kwargs)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/cachecontrol/adapter.py", line 47, in send
        resp = super(CacheControlAdapter, self).send(request, **kw)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 390, in send
        conn = self.get_connection(request.url, proxies)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 290, in get_connection
        proxy_manager = self.proxy_manager_for(proxy)
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
        **proxy_kwargs
      File "/tmp/tmpnz7ISh/pip.zip/pip/_vendor/requests/adapters.py", line 43, in SOCKSProxyManager
        raise InvalidSchema("Missing dependencies for SOCKS support.")
    InvalidSchema: Missing dependencies for SOCKS support.


问:
Clang-format line breaks
I'm looking for a clang-format setting to prevent the tool from removing line breaks.

For example, I have my ColumnLimit set to 120, and here's what happens when I reformat some sample code.

Before:

```<code>#include <vector>
#include <string>

std::vector<std::string> get_vec()
{
   return std::vector<std::string> {
      "this is a test",
      "some of the lines are longer",
      "than other, but I would like",
      "to keep them on separate lines"
   };
}

int main()
{
   auto vec = get_vec();
}
</code>```

After:

```<code>#include <vector>
#include <string>

std::vector<std::string> get_vec()
{
   return std::vector<std::string>{"this is a test", "some of the lines are longer", "than other, but I would like",
         "to keep them on separate lines"};
}

int main()
{
   auto vec = get_vec();
}
</code>```

What I would like is that the tool breaks lines that are over 120 characters, but doesn't decide to combine lines just because they are less than 120 characters.

Is there such an option?  Nothing in the docs stood out to me.

答:
Add a comma after the last string. This tells clang-format to format it vertically. Ex:
https://godbolt.org/z/bZxr__ Right click > format text</p>

```<code>#include <string>
#include <vector>

std::vector<std::string> get_vec() {
  return std::vector<std::string>{
      "this is a test",
      "some of the lines are longer",
      "than other, but I would like",
      "to keep them on separate lines", // comma here after last element
  };
}

int main() { auto vec = get_vec(); }
</code>```

Title: Clang-format line breaks

Body:
I'm looking for a clang-format setting to prevent the tool from removing line breaks.

For example, I have my ColumnLimit set to 120, and here's what happens when I reformat some sample code.

Before:

#include <vector>
#include <string>

std::vector<std::string> get_vec()
{
   return std::vector<std::string> {
      "this is a test",
      "some of the lines are longer",
      "than other, but I would like",
      "to keep them on separate lines"
   };
}

int main()
{
   auto vec = get_vec();
}

After:

#include <vector>
#include <string>

std::vector<std::string> get_vec()
{
   return std::vector<std::string>{"this is a test", "some of the lines are longer", "than other, but I would like",
         "to keep them on separate lines"};
}

int main()
{
   auto vec = get_vec();
}

What I would like is that the tool breaks lines that are over 120 characters, but doesn't decide to combine lines just because they are less than 120 characters.

Is there such an option?  Nothing in the docs stood out to me.

Body:
Add a comma after the last string. This tells clang-format to format it vertically. Ex:
https://godbolt.org/z/bZxr__ Right click > format text

#include <string>
#include <vector>

std::vector<std::string> get_vec() {
  return std::vector<std::string>{
      "this is a test",
      "some of the lines are longer",
      "than other, but I would like",
      "to keep them on separate lines", // comma here after last element
  };
}

int main() { auto vec = get_vec(); }


问:
Dynamic positioning of a Button [Android]
I have a RelativeLayout which holds an ImageView and an ImageButton. The ImageView serves as an container for a background image. Now I'm trying to set the button at a fixed position so that it always appears on the same position on the background image.

Here is the layout file I'm using:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1" android:layout_height="match_parent"
android:layout_width="match_parent" android:gravity="center_horizontal">

<ImageView android:src="@drawable/bg_1" android:id="@+id/imgView"
    android:adjustViewBounds="true" android:layout_height="match_parent"
    android:layout_width="match_parent" />

<ImageButton android:layout_width="120dp"
    android:background="@drawable/button_1" android:layout_height="30dp"
    android:id="@+id/imgButton" android:layout_marginLeft="100dp"
    android:layout_marginTop="170dp" />
</RelativeLayout>
</code>```

As you can see I've tried positioning the button with it's left-/top-margin using dp as unit, but this doesn't work. Since the background image is beeing scaled down/up, the position would have to be dynamic in some kind of way.

I understand that absolute positioning, with pixel-values for x-/y-position, is something that won't work on Android, like it is explained here. I still need to solve this and am not sure how.

Would I have to calculate the values for left-/top-margin (not sure how that would be) and then set them with something like this?

```<code>final float density = getResources().getDisplayMetrics().density;
int width = (int)((float)120 * density);
int height = (int)((float)120 * density);

RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(width, height);
rlp.leftMargin = newMargin;
rlp.topMargin = newTopMargin;

ImageButton imgButton = (ImageButton) findViewById(R.id.imgButton);
imgButton.setLayoutParams(rlp);
</code>```

Hope I didn't forget something ...

//EDIT:
I was thinking, the reason for the issue might be, that the scaled image has different "borders", depending on the screen size.
With an image at a 1:1.6 ratio on a HVGA screen I have black bars on the left and right, whereas on a WVGA screen the bars are on the left. Considering I'm using the default scaling. I will look into it and post again, if necessaray...

答: Why scaling happens? Because of different dpi on different devices? Do you have different drawabled for different dpi settings? If it isn't just dpi issue and you want to scale that background image freely then you can't do the job using standard layouts. You should implement a custom one.</p>

Body:
I have a RelativeLayout which holds an ImageView and an ImageButton. The ImageView serves as an container for a background image. Now I'm trying to set the button at a fixed position so that it always appears on the same position on the background image.

Here is the layout file I'm using:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1" android:layout_height="match_parent"
android:layout_width="match_parent" android:gravity="center_horizontal">

<ImageView android:src="@drawable/bg_1" android:id="@+id/imgView"
    android:adjustViewBounds="true" android:layout_height="match_parent"
    android:layout_width="match_parent" />

<ImageButton android:layout_width="120dp"
    android:background="@drawable/button_1" android:layout_height="30dp"
    android:id="@+id/imgButton" android:layout_marginLeft="100dp"
    android:layout_marginTop="170dp" />
</RelativeLayout>

As you can see I've tried positioning the button with it's left-/top-margin using dp as unit, but this doesn't work. Since the background image is beeing scaled down/up, the position would have to be dynamic in some kind of way.

I understand that absolute positioning, with pixel-values for x-/y-position, is something that won't work on Android, like it is explained here. I still need to solve this and am not sure how.

Would I have to calculate the values for left-/top-margin (not sure how that would be) and then set them with something like this?

final float density = getResources().getDisplayMetrics().density;
int width = (int)((float)120 * density);
int height = (int)((float)120 * density);

RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(width, height);
rlp.leftMargin = newMargin;
rlp.topMargin = newTopMargin;

ImageButton imgButton = (ImageButton) findViewById(R.id.imgButton);
imgButton.setLayoutParams(rlp);

Hope I didn't forget something ...

//EDIT:
I was thinking, the reason for the issue might be, that the scaled image has different "borders", depending on the screen size.
With an image at a 1:1.6 ratio on a HVGA screen I have black bars on the left and right, whereas on a WVGA screen the bars are on the left. Considering I'm using the default scaling. I will look into it and post again, if necessaray...


问:
Bootstrap loses layout printing portrait
I created what looked like a usable template from a web site, and happily started to use it. My printer was initially set to landscape when I printed the information, so everything looked fine and I got a pretty report neatly centred in the page. The following is a file I generated (I'm using jinja2 templating, but if I know what's wrong with the HTML/CSS I can fix the templates).

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap 4, from LayoutIt! -->
    <title>SPoE Testing</title>

    <meta name="description" content="Source code generated using layoutit.com">
    <meta name="author" content="LayoutIt!">

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

  </head>
  <body>
    <div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
            <div class="page-header">
                <h1>
                    Integrated Next-Generation Test System
                </h1>
                <hr>
            </div>
        </div>
        <div class="col-md-3">
        </div>
    </div>
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
            <div class="page-header">
                <h2>
                    Single PoE <small>Unit 0000000 at 2019-05-23 23:59:59</small>
                </h2>
                <hr>
            </div>
            <div class="row">
                <div class="col-md-4">
                <h3>#0000000</h3>
                </div>
                <div class="col-md-8">
                <h3>pass</h3>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                <h5>Step 1</h5>
                </div>
                <div class="col-md-8">
                <h5>pass</h5>
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                power
                </div>
                <div class="col-md-8">
                28.1
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                current
                </div>
                <div class="col-md-8">
                525
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                voltage
                </div>
                <div class="col-md-8">
                53.7
                </div>
            </div>

        </div>
        <div class="col-md-3">
        </div>
    </div>
</div>

    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/scripts.js"></script>
  <style type="text/css"> @page { size: auto } </style>
  </body>
</html>
</code>```

As you can see this prints fine in landscape:

Unfortunately when I try to print in portrait the output is rather less convincing:

The inline @page { size: auto } is something I added as a result of my researches - it was recommended in this question but alas it appears to make no difference. Interestingly, while I found several questions relating to inability to print in landscape, nobody else appears to have found portrait layout an issue.

As a designer I'm a pretty good bricklayer, so while software is no problem at all for me I find these design issues quite tortuous sometimes. What is going on here, and how do I fix it?

答:
You will need to write CSS for print media.

Here is a basic example based on your code

@media print and (max-width: 767px) {
  .row{
    display: flex;
    flex-direction: row;
  }
  .col-md-3{
    flex-basis: 25%;
  }
  .col-md-1{
    flex-basis: 8.33%;
  }
  .col-md-8{
    flex-basis: 66.67%;
  }
  .col-md-6{
    flex-basis: 50%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap 4, from LayoutIt! -->
    <title>SPoE Testing</title>

    <meta name="description" content="Source code generated using layoutit.com">
    <meta name="author" content="LayoutIt!">

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

  </head>
  <body>
    <div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
            <div class="page-header">
                <h1>
                    Integrated Next-Generation Test System
                </h1>
                <hr>
            </div>
        </div>
        <div class="col-md-3">
        </div>
    </div>
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
            <div class="page-header">
                <h2>
                    Single PoE <small>Unit 0000000 at 2019-05-23 23:59:59</small>
                </h2>
                <hr>
            </div>
            <div class="row">
                <div class="col-md-4">
                <h3>#0000000</h3>
                </div>
                <div class="col-md-8">
                <h3>pass</h3>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                <h5>Step 1</h5>
                </div>
                <div class="col-md-8">
                <h5>pass</h5>
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                power
                </div>
                <div class="col-md-8">
                28.1
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                current
                </div>
                <div class="col-md-8">
                525
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                voltage
                </div>
                <div class="col-md-8">
                53.7
                </div>
            </div>

        </div>
        <div class="col-md-3">
        </div>
    </div>
</div>

    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/scripts.js"></script>
  <style type="text/css"> @page { size: auto } </style>
  </body>
</html></code>```

Body:
I created what looked like a usable template from a web site, and happily started to use it. My printer was initially set to landscape when I printed the information, so everything looked fine and I got a pretty report neatly centred in the page. The following is a file I generated (I'm using jinja2 templating, but if I know what's wrong with the HTML/CSS I can fix the templates).

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>SPoE Testing</title>

    <meta name="description" content="Source code generated using layoutit.com">
    <meta name="author" content="LayoutIt!">

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

                    Integrated Next-Generation Test System

                    Single PoE Unit 0000000 at 2019-05-23 23:59:59

#0000000

pass

Step 1

pass

                power

                28.1

                current

                525

                voltage

                53.7

As you can see this prints fine in landscape:

Unfortunately when I try to print in portrait the output is rather less convincing:

The inline @page { size: auto } is something I added as a result of my researches - it was recommended in this question but alas it appears to make no difference. Interestingly, while I found several questions relating to inability to print in landscape, nobody else appears to have found portrait layout an issue.

As a designer I'm a pretty good bricklayer, so while software is no problem at all for me I find these design issues quite tortuous sometimes. What is going on here, and how do I fix it?

Body:
You will need to write CSS for print media.

Here is a basic example based on your code

@media print and (max-width: 767px) {
  .row{
    display: flex;
    flex-direction: row;
  }
  .col-md-3{
    flex-basis: 25%;
  }
  .col-md-1{
    flex-basis: 8.33%;
  }
  .col-md-8{
    flex-basis: 66.67%;
  }
  .col-md-6{
    flex-basis: 50%;
  }
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap 4, from LayoutIt! -->
    <title>SPoE Testing</title>

    <meta name="description" content="Source code generated using layoutit.com">
    <meta name="author" content="LayoutIt!">

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

  </head>
  <body>
    <div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
            <div class="page-header">
                <h1>
                    Integrated Next-Generation Test System
                </h1>
                <hr>
            </div>
        </div>
        <div class="col-md-3">
        </div>
    </div>
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
            <div class="page-header">
                <h2>
                    Single PoE <small>Unit 0000000 at 2019-05-23 23:59:59</small>
                </h2>
                <hr>
            </div>
            <div class="row">
                <div class="col-md-4">
                <h3>#0000000</h3>
                </div>
                <div class="col-md-8">
                <h3>pass</h3>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                <h5>Step 1</h5>
                </div>
                <div class="col-md-8">
                <h5>pass</h5>
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                power
                </div>
                <div class="col-md-8">
                28.1
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                current
                </div>
                <div class="col-md-8">
                525
                </div>
            </div>

            <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-3">
                voltage
                </div>
                <div class="col-md-8">
                53.7
                </div>
            </div>

        </div>
        <div class="col-md-3">
        </div>
    </div>
</div>

    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/scripts.js"></script>
  <style type="text/css"> @page { size: auto } </style>
  </body>
</html>


问:
Removing Element from Document Flow
I'm using a [type=checkbox] to record the user input for a custom dropdown menu that I created. I'm also using it for the required functionality in browsers too.

The issue I'm running into, however, is that the element seems to need at least 1px of height in order to trigger the browser warning message when a user tries to submit the form without filling out that part. This is an issue because the dropdown menu has a height of auto, so as soon as the browser warning message is displayed, it shifts everything up so that there is a 1px gap at the bottom.

Notably, the content only shifts if or once the warning message is displayed.

I know that I can fix this by positioning the element absolutely with JS, but I'm trying to use as little JS as possible. Hence I've given the container a position: relative, and positioned the element so that it always displays at the bottom center of the container element like all of the other fields.

```<code>#dropdown {
  position: relative;
}

#subject {
  width: 1px;
  height: 1px;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}
</code>```

As I stated above, I've already tried giving it a height of 0, but by doing this the warning message does not trigger. I've also tried a couple different display values (and I will be going through the rest of them once I finish positing this). I've also tried applying position: absolute; bottom: 0; to the last option in the list. None of this stuff works.

const
  option = document.querySelector('#option')

document.querySelector('#dropdown').addEventListener('click', function(){
  option.style.maxHeight = option.scrollHeight + 'px'
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdown {
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  border: solid red 3px;
}

#label {
  padding: 50px;
}

#option {
  max-height: 0;
  transition:
    .5s max-height;
}

#option:hover {
  background: skyblue;
}

#checkbox {
  width: 5px;
  height: 5px; /* added extra pixels to emphasize the issue */
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}</code>```

<form>

Subject

Last Option

    <input id='checkbox' type='checkbox' required />

  <input type='submit' />
</form>```

Does anybody have any ideas how I might be able to do this with CSS alone?

Is it even possible since the container has a height of auto?

答:
Major Changes

div#option is now label.option[for='checkbox']. If a label has a [for] attribute with its value of a checkbox or radio #id, they will be associated with one another so if a user clicks one the other is clicked as well. This association works as long as both are on the same page no matter how close, far apart, nested, or not nested.

label[for='checkbox'] has been assigned display:block because it replaced a div.

#checkbox is now entirely out of div,dropdown and assigned z-index:-1 and positioned with vh and vw units so it's position will responsively adjust to any window resizing. The form has it's background color set explicitly so that the checkbox is totally concealed but as far as the browser is concerned it's visible and so required will always work.

Minor Changes

Most of the #id were changed to classes isn't required, I just did it because I don't like #ids.

Also removed some other unnecessary styles that are no longer needed for at least the provided code.

const option = document.querySelector('.option');

document.querySelector('.dropdown').addEventListener('click', function() {
  option.style.maxHeight = option.scrollHeight + 'px';

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form {
  background: #fff
}

.dropdown {
  overflow: hidden;
  border: solid red 1px;
}

.label {
  display: block;
  padding: 50px;
}

.option {
  display: block;
  max-height: 0;
  transition: max-height 0.5s
}

.option:hover {
  background: skyblue;
}

#checkbox {
  display: block;
  position: relative;
  z-index: -1;
  left: 50vw;
  bottom: 10vh;
}</code>```

<form>

    Subject

    Last Option

  <input type='submit'>
  <input id='checkbox' type='checkbox' required>
</form>```

Title: Removing Element from Document Flow

Body:
I'm using a [type=checkbox] to record the user input for a custom dropdown menu that I created. I'm also using it for the required functionality in browsers too.

The issue I'm running into, however, is that the element seems to need at least 1px of height in order to trigger the browser warning message when a user tries to submit the form without filling out that part. This is an issue because the dropdown menu has a height of auto, so as soon as the browser warning message is displayed, it shifts everything up so that there is a 1px gap at the bottom.

Notably, the content only shifts if or once the warning message is displayed.

I know that I can fix this by positioning the element absolutely with JS, but I'm trying to use as little JS as possible. Hence I've given the container a position: relative, and positioned the element so that it always displays at the bottom center of the container element like all of the other fields.

#dropdown {
  position: relative;
}

#subject {
  width: 1px;
  height: 1px;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}

As I stated above, I've already tried giving it a height of 0, but by doing this the warning message does not trigger. I've also tried a couple different display values (and I will be going through the rest of them once I finish positing this). I've also tried applying position: absolute; bottom: 0; to the last option in the list. None of this stuff works.

const
  option = document.querySelector('#option')

document.querySelector('#dropdown').addEventListener('click', function(){
  option.style.maxHeight = option.scrollHeight + 'px'
})

#dropdown {
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  border: solid red 3px;
}

#label {
  padding: 50px;
}

#option {
  max-height: 0;
  transition:
    .5s max-height;
}

#option:hover {
  background: skyblue;
}

#checkbox {
  width: 5px;
  height: 5px; /* added extra pixels to emphasize the issue */
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}

<form>

Subject

Last Option

    <input id='checkbox' type='checkbox' required />

  <input type='submit' />
</form>

Does anybody have any ideas how I might be able to do this with CSS alone?

Is it even possible since the container has a height of auto?

Body:
Major Changes

div#option is now label.option[for='checkbox']. If a label has a [for] attribute with its value of a checkbox or radio #id, they will be associated with one another so if a user clicks one the other is clicked as well. This association works as long as both are on the same page no matter how close, far apart, nested, or not nested.

label[for='checkbox'] has been assigned display:block because it replaced a div.

#checkbox is now entirely out of div,dropdown and assigned z-index:-1 and positioned with vh and vw units so it's position will responsively adjust to any window resizing. The form has it's background color set explicitly so that the checkbox is totally concealed but as far as the browser is concerned it's visible and so required will always work.

Minor Changes

Most of the #id were changed to classes isn't required, I just did it because I don't like #ids.

Also removed some other unnecessary styles that are no longer needed for at least the provided code.

const option = document.querySelector('.option');

document.querySelector('.dropdown').addEventListener('click', function() {
  option.style.maxHeight = option.scrollHeight + 'px';

});

form {
  background: #fff
}

.dropdown {
  overflow: hidden;
  border: solid red 1px;
}

.label {
  display: block;
  padding: 50px;
}

.option {
  display: block;
  max-height: 0;
  transition: max-height 0.5s
}

.option:hover {
  background: skyblue;
}

#checkbox {
  display: block;
  position: relative;
  z-index: -1;
  left: 50vw;
  bottom: 10vh;
}

<form>

  <div class='dropdown'>

    <label class='label'>Subject</label>

    <label for='checkbox' class='option'>Last Option</label>
  </div>

  <input type='submit'>
  <input id='checkbox' type='checkbox' required>
</form>


问:
Getting values from time indexed pandas dataframe for a specific time within the two timestamps
I have the following pandas dataframe df:

```<code>                     C1  C2   C3
Date
2000-01-01 00:00:00   2  175  160
2000-01-01 01:00:00   4  192  164
2000-01-01 02:00:00   6  210  189
2000-01-01 03:00:00   8  217  199
2000-01-01 04:00:00  10  176  158
</code>```

from which I need to get the value of C1, C2 and C3 for a specific datetime:

```<code>import datetime
my_specific_time = str(datetime.datetime(2000, 1, 1, 1, 0, 0))
print(df['C1'].loc[mytime]) # prints 4
</code>```

The problem is that I can only get values for the dates stored in the df. For example, getting the value of C1 for time 2000-01-01 01:30:00 is not possible unless I resample my dataframe:

```<code>upsampled = df.resample('30min').ffill()
my_specific_time = str(datetime.datetime(2000, 1, 1, 1, 30, 0))
print(upsampled['C1'].loc[mytime]) # again prints 4
</code>```

Please note that all the value of C1 between timespan of 2000-01-01 01:00:00 and 2000-01-01 02:00:00 is 4. Now the problem is that my_specific_time can be any random time and I would need to resample df using small enough values to be able to get the value for. I think this is not the best solution for this problem.

While looking for possible solutions I only came across time spans in pandas but I did not quite understand how possibly I can use it in my problem.

答:
Use DataFrame.asof method:

```<code>print(df['C1'].asof(my_specific_time))

4
</code>```

Body:
I have the following pandas dataframe df:

                     C1  C2   C3
Date
2000-01-01 00:00:00   2  175  160
2000-01-01 01:00:00   4  192  164
2000-01-01 02:00:00   6  210  189
2000-01-01 03:00:00   8  217  199
2000-01-01 04:00:00  10  176  158

from which I need to get the value of C1, C2 and C3 for a specific datetime:

import datetime
my_specific_time = str(datetime.datetime(2000, 1, 1, 1, 0, 0))
print(df['C1'].loc[mytime]) # prints 4

The problem is that I can only get values for the dates stored in the df. For example, getting the value of C1 for time 2000-01-01 01:30:00 is not possible unless I resample my dataframe:

upsampled = df.resample('30min').ffill()
my_specific_time = str(datetime.datetime(2000, 1, 1, 1, 30, 0))
print(upsampled['C1'].loc[mytime]) # again prints 4

Please note that all the value of C1 between timespan of 2000-01-01 01:00:00 and 2000-01-01 02:00:00 is 4. Now the problem is that my_specific_time can be any random time and I would need to resample df using small enough values to be able to get the value for. I think this is not the best solution for this problem.

While looking for possible solutions I only came across time spans in pandas but I did not quite understand how possibly I can use it in my problem.

Body:
Use DataFrame.asof method:

print(df['C1'].asof(my_specific_time))

4


问:
Do I need to wait for Xcode 10.3 to test on iOS 12.3?
Currently iOS 12.3 is released and latest version of Xcode is 10.2.1

I want to know to test my app on my physical device with iOS 12.3 I need to wait for Xcode 10.3 or is it possible to deploy apps using Xcode 10.2 on iOS 12.3?

I did not update my phone iOS and keep its version 12.2 since I don't know the answer to this question.

答:
iOS 12.4 Beta 2 Release Notes

The iOS 12.2 SDK provides support for developing iOS apps for iPhone,
  iPad, or iPod touch devices running iOS 12.4. The SDK comes bundled
  with Xcode 10.2.1 available from the Mac App Store

iOS 12.3 Release Notes

The iOS 12.2 SDK provides support for developing iOS apps for iPhone,
  iPad, or iPod touch devices running iOS 12.3. The SDK comes bundled
  with Xcode 10.2.1 available from the Mac App Store.

Reference:

iOS 12.4 Beta 2 Release Notes

iOS 12.3 Release Notes


问:
How to step through Python code to help debug issues?
In Java/C# you can easily step through code to trace what might be going wrong, and IDE's make this process very user friendly.

Can you trace through python code in a similar fashion?

答:
There exist breakpoint() method nowadays, which replaces import pdb; pdb.set_trace().

It also has several new features, such as possible environment variables.


问:
Using custom SSL certificates in titanium web proxy
I have used Titanium web proxy for a windows forms application and there, I intercept https traffic and update it. I have first used titanium root certificate and it worked fine.

 when I was trying to use custom ssl certificate as below

```<code>proxyServer.CertificateManager.RootCertificate = new X509Certificate2("default.pfx",
                    "password",
                    X509KeyStorageFlags.MachineKeySet);

proxyServer.CertificateManager.TrustRootCertificate(true);
</code>```

but I couldn't able to decrypt the https traffic and it says

```<code>"The underlying connection was closed: An unexpected error occurred on a send." innerException says "
Authentication failed because the remote party has closed the transport stream."
</code>```

how to decrypt the https traffic using custom ssl certificate in titanium-web proxy.

答:
Issue was fixed when I add custom certification name and issuer name to proxyserver constructor and didn't needed any of above code. just fixed the issue by below code and certificate needs to installed in the machine</p>

```<code>ProxyServer proxyServer = new ProxyServer("certificate.pfx", "Issuer Name",true,true,true);
proxyServer.CertificateManager.PfxPassword = "Password";
</code>```

Body:
I have used Titanium web proxy for a windows forms application and there, I intercept https traffic and update it. I have first used titanium root certificate and it worked fine.

 when I was trying to use custom ssl certificate as below

proxyServer.CertificateManager.RootCertificate = new X509Certificate2("default.pfx",
                    "password",
                    X509KeyStorageFlags.MachineKeySet);

proxyServer.CertificateManager.TrustRootCertificate(true);

but I couldn't able to decrypt the https traffic and it says

"The underlying connection was closed: An unexpected error occurred on a send." innerException says "
Authentication failed because the remote party has closed the transport stream."

how to decrypt the https traffic using custom ssl certificate in titanium-web proxy.

Body:
Issue was fixed when I add custom certification name and issuer name to proxyserver constructor and didn't needed any of above code. just fixed the issue by below code and certificate needs to installed in the machine

ProxyServer proxyServer = new ProxyServer("certificate.pfx", "Issuer Name",true,true,true);
proxyServer.CertificateManager.PfxPassword = "Password";


问:
Array of custom object model won't save to shared preferences
I am trying to do a module where once I fetched the JSON from the API and I am loading it into RAM memory I immediately load it to Shared Prefs and also once I any change to the data (in the adapter onClick method) I re-save the new changed array into the shared preferences. Apparently it does not work and I can't figure out why.

Here is my activity containing all of the relevant code:

```<code>
package com.example.superheros.Controllers;

import android.content.SharedPreferences;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;

import com.example.superheros.Adapter.HeroesAdapter;
import com.example.superheros.Model.Hero;
import com.example.superheros.Networking.HttpRequest;
import com.example.superheros.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    //API constant -
    private static final String BASE_URL = "https://heroapps.co.il/employee-tests/android/androidexam.json";
    public static final String SAVED_HERO_LIST = "heroesList";
    // Recyclerview variables -
    private RecyclerView heroesRecylerView;
    private ArrayList<Hero> heroesArrayList;
    private RecyclerView.LayoutManager layoutManager;
    private HeroesAdapter heroesAdapter;
    //Toolbar variables -
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private ImageView toolbarImageView;
    //Persistence variables -
    private Hero selectedFavoriteHero;
    private SharedPreferences sharedPreferences;
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            heroesArrayList = loadFromLocal();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        if (heroesArrayList != null && heroesArrayList.size() > 0){
            initViews();
        } else {
            initNetworking();
        }

    }

    private void initNetworking() {
        HttpRequest httpRequest = new HttpRequest(this, BASE_URL, new HttpRequest.OnHttpCompleteListener() {
            @Override
            public void onComplete(String response) {
                dataToModel(response, false);
                initViews();
            }

            @Override
            public void onError(String error) {
                Log.d("error", error);
            }
        });
        httpRequest.request();
    }

    private void initViews() {
        heroesRecylerView = findViewById(R.id.herosRecyclerView);
        collapsingToolbarLayout = findViewById(R.id.collapsingHeroToolbarLayout);
        toolbarImageView = findViewById(R.id.toolbarImageview);
        heroesRecylerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        heroesRecylerView.setLayoutManager(layoutManager);
        heroesAdapter = new HeroesAdapter(heroesArrayList, new HeroesAdapter.OnHeroListClickListener() {
            @Override
            public void onListItemClicked(int position) {
                changeFavoriteHero(position);
            }
        });
        heroesRecylerView.setAdapter(heroesAdapter);

    }

    private void changeFavoriteHero(int position) {
        Hero pressedHeroRow = heroesArrayList.get(position);
        selectedFavoriteHero = pressedHeroRow;
        Picasso.get().load(pressedHeroRow.image)
                .fit()
                .centerCrop()
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_foreground)
                .into(toolbarImageView);
        collapsingToolbarLayout.setTitle(pressedHeroRow.title);
        pressedHeroRow.setFavorite(!pressedHeroRow.isFavorite());
        for (int i = 0; i < heroesArrayList.size(); i++) {
            if (i == position) continue;
            heroesArrayList.get(i).setFavorite(false);
        }
        saveToLocal(heroesArrayList);
        heroesAdapter.notifyDataSetChanged();
    }

    private ArrayList<Hero> dataToModel(String json, boolean isLocalInfo) {
        Gson gson = new Gson();
        Hero[] heroesList = gson.fromJson(json, Hero[].class);
        heroesArrayList = new ArrayList<>(Arrays.asList(heroesList));
        if (!isLocalInfo) {
            saveToLocal(heroesArrayList);
        }
        return heroesArrayList;
    }

    //Shared preferences load & save methods -

    private void saveToLocal(ArrayList<Hero> heroesArrayList) {
        sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        Gson gson = new Gson();
        String heroesList = gson.toJson(heroesArrayList);
        Log.d("heroArrayList", heroesList);
        prefsEditor.putString(SAVED_HERO_LIST, heroesList);
        prefsEditor.apply();
    }

    private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = gson.fromJson(SAVED_HERO_LIST, String.class);
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }
}

</code>```

I hope I can be pointed about what I was missing

答:
try this. </p>

```<code> private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = sharedPreferences.getString(SAVED_HERO_LIST, "null");
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }
</code>```

Body:
I am trying to do a module where once I fetched the JSON from the API and I am loading it into RAM memory I immediately load it to Shared Prefs and also once I any change to the data (in the adapter onClick method) I re-save the new changed array into the shared preferences. Apparently it does not work and I can't figure out why.

Here is my activity containing all of the relevant code:

package com.example.superheros.Controllers;

import android.content.SharedPreferences;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;

import com.example.superheros.Adapter.HeroesAdapter;
import com.example.superheros.Model.Hero;
import com.example.superheros.Networking.HttpRequest;
import com.example.superheros.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    //API constant -
    private static final String BASE_URL = "https://heroapps.co.il/employee-tests/android/androidexam.json";
    public static final String SAVED_HERO_LIST = "heroesList";
    // Recyclerview variables -
    private RecyclerView heroesRecylerView;
    private ArrayList<Hero> heroesArrayList;
    private RecyclerView.LayoutManager layoutManager;
    private HeroesAdapter heroesAdapter;
    //Toolbar variables -
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private ImageView toolbarImageView;
    //Persistence variables -
    private Hero selectedFavoriteHero;
    private SharedPreferences sharedPreferences;
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            heroesArrayList = loadFromLocal();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        if (heroesArrayList != null && heroesArrayList.size() > 0){
            initViews();
        } else {
            initNetworking();
        }

    }

    private void initNetworking() {
        HttpRequest httpRequest = new HttpRequest(this, BASE_URL, new HttpRequest.OnHttpCompleteListener() {
            @Override
            public void onComplete(String response) {
                dataToModel(response, false);
                initViews();
            }

            @Override
            public void onError(String error) {
                Log.d("error", error);
            }
        });
        httpRequest.request();
    }

    private void initViews() {
        heroesRecylerView = findViewById(R.id.herosRecyclerView);
        collapsingToolbarLayout = findViewById(R.id.collapsingHeroToolbarLayout);
        toolbarImageView = findViewById(R.id.toolbarImageview);
        heroesRecylerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        heroesRecylerView.setLayoutManager(layoutManager);
        heroesAdapter = new HeroesAdapter(heroesArrayList, new HeroesAdapter.OnHeroListClickListener() {
            @Override
            public void onListItemClicked(int position) {
                changeFavoriteHero(position);
            }
        });
        heroesRecylerView.setAdapter(heroesAdapter);

    }

    private void changeFavoriteHero(int position) {
        Hero pressedHeroRow = heroesArrayList.get(position);
        selectedFavoriteHero = pressedHeroRow;
        Picasso.get().load(pressedHeroRow.image)
                .fit()
                .centerCrop()
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_foreground)
                .into(toolbarImageView);
        collapsingToolbarLayout.setTitle(pressedHeroRow.title);
        pressedHeroRow.setFavorite(!pressedHeroRow.isFavorite());
        for (int i = 0; i < heroesArrayList.size(); i++) {
            if (i == position) continue;
            heroesArrayList.get(i).setFavorite(false);
        }
        saveToLocal(heroesArrayList);
        heroesAdapter.notifyDataSetChanged();
    }

    private ArrayList<Hero> dataToModel(String json, boolean isLocalInfo) {
        Gson gson = new Gson();
        Hero[] heroesList = gson.fromJson(json, Hero[].class);
        heroesArrayList = new ArrayList<>(Arrays.asList(heroesList));
        if (!isLocalInfo) {
            saveToLocal(heroesArrayList);
        }
        return heroesArrayList;
    }

    //Shared preferences load & save methods -

    private void saveToLocal(ArrayList<Hero> heroesArrayList) {
        sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        Gson gson = new Gson();
        String heroesList = gson.toJson(heroesArrayList);
        Log.d("heroArrayList", heroesList);
        prefsEditor.putString(SAVED_HERO_LIST, heroesList);
        prefsEditor.apply();
    }

    private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = gson.fromJson(SAVED_HERO_LIST, String.class);
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }
}

I hope I can be pointed about what I was missing

Body:
try this.

 private ArrayList<Hero> loadFromLocal(){
        sharedPreferences = getPreferences(MODE_PRIVATE);
        try {
            String fetchedHeroesJson = sharedPreferences.getString(SAVED_HERO_LIST, "null");
            ArrayList<Hero> heroArrayList = dataToModel(fetchedHeroesJson, true);
            return heroArrayList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }