问:
Can't Connect Spark with Hortonworks Sandbox from eclipse
I am not able to connect my spark Code which is written on eclipse.

Below is the code please guid me how I can do the same.
Anything would be helpful

```<code>>
>     import java.util.Arrays;
>
>     import org.apache.spark.SparkConf;
>     import org.apache.spark.api.java.JavaPairRDD;
>     import org.apache.spark.api.java.JavaRDD;
>     import org.apache.spark.api.java.JavaSparkContext;
>
>      public class SparkTest {
>
        public static void main(String[] args) {

>          SparkConf conf = new SparkConf()
              .setAppName("JD Word Counter").setMaster("local");

>
>          JavaSparkContext sc = new JavaSparkContext(conf);
>               //hdfs://localhost:8020/user/root/textfile/test.txt
           JavaRDD<String> inputFile = sc.textFile("hdfs://localhost:8020/user/root/textfile/test.txt");

>          System.out.println("Hello start");
>          System.out.println(inputFile.collect());
           JavaRDD<String> wordsFromFile = inputFile.flatMap(content ->
            Arrays.asList(content.split(" ")).iterator());

>          System.out.println("hello end");
>
>
>          //JavaPairRDD countData = wordsFromFile.mapToPair(t -> new Tuple2(t, 1)).reduceByKey((x, y) -> (int) x + (int) y);
          //wordsFromFile
           .saveAsTextFile("hdfs://localhost:8020/user/root/fileTest/");

>
>          System.out.println(" This java program is complete");

       }
>
>     }
>
</code>```

Error:

```<code>> I/O error constructing remote block reader.
> org.apache.hadoop.net.ConnectTimeoutException: 60000 millis timeout
> while waiting for  channel to be ready for connect. ch :
> java.nio.channels.SocketChannel[connection-pending
> remote=/172.18.0.2:50010] at org.apache.hadoop.net.NetUtils.c
</code>```

答: Change localhost to ip address of the hdp sandbox or put hdfs-site.xml file in your classpath & make sure all port are open & accessible from outside machine.

Body:
I am not able to connect my spark Code which is written on eclipse.

Below is the code please guid me how I can do the same.
Anything would be helpful

>
>     import java.util.Arrays;
>
>     import org.apache.spark.SparkConf;
>     import org.apache.spark.api.java.JavaPairRDD;
>     import org.apache.spark.api.java.JavaRDD;
>     import org.apache.spark.api.java.JavaSparkContext;
>
>      public class SparkTest {
>
        public static void main(String[] args) {

>          SparkConf conf = new SparkConf()
              .setAppName("JD Word Counter").setMaster("local");

>
>          JavaSparkContext sc = new JavaSparkContext(conf);
>               //hdfs://localhost:8020/user/root/textfile/test.txt
           JavaRDD<String> inputFile = sc.textFile("hdfs://localhost:8020/user/root/textfile/test.txt");

>          System.out.println("Hello start");
>          System.out.println(inputFile.collect());
           JavaRDD<String> wordsFromFile = inputFile.flatMap(content ->
            Arrays.asList(content.split(" ")).iterator());

>          System.out.println("hello end");
>
>
>          //JavaPairRDD countData = wordsFromFile.mapToPair(t -> new Tuple2(t, 1)).reduceByKey((x, y) -> (int) x + (int) y);
          //wordsFromFile
           .saveAsTextFile("hdfs://localhost:8020/user/root/fileTest/");

>
>          System.out.println(" This java program is complete");

       }
>
>     }
>

Error:

> I/O error constructing remote block reader.
> org.apache.hadoop.net.ConnectTimeoutException: 60000 millis timeout
> while waiting for  channel to be ready for connect. ch :
> java.nio.channels.SocketChannel[connection-pending
> remote=/172.18.0.2:50010] at org.apache.hadoop.net.NetUtils.c


来源: stackexchange

问:
Use python to identify elements at screen
I want to start a python project thats identify some elements in screen, like a square's size or all elements in screen with a certain color, and i don't even know from where should i start.

For example, all the top points above certain value at the graph.

Anyone could please give me a north?

答:
If you're looking to interact with elements inside a browser, look at Selenium. If you want to control the desktop itself, look into Sikuli.

In either case, you can use OpenCV to identify elements and do template matching.

Edit: more comments after more details from OP

If you're just looking to identify the peaks in the graph, you can take a screenshot of the display at regular intervals using Sikuli or PyScreenshot and then use template matching in OpenCV (either directly or using Sikuli) to get the coordinates of the peaks in the screenshot. The horizontal line across the graph might throw off some of the template matching, but you can play around with the various parameters to get the results you want.

Check out this tutorial for template matching.

ContentLicense: CC BY-SA 4.0


问:
How do I match numbers and create 2-dimensional array?
I have an array like so [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7]

How can I turn it into a 2-dimensional array that's based on matching numbers before the decimal?

ex.[[1.2, 1.3, 1.4], [2.2, 2.3], [3.0], [4.3, 4.4, 4.5, 4.6, 4.7]]

答:
use sort, then traverse using forEach and group based on Math.floor value.

const split = (data) => {
  const output = [];
  let temp = [];
  data
    .sort((a, b) => a - b)
    .forEach((num) => {
      const [first] = temp;
      if (first && Math.floor(num) > Math.floor(first)) {
        output.push([...temp]);
        temp = [];
      }
      temp.push(num);
    });
  if (temp.length > 0) {
    output.push([...temp]);
  }
  return output;
};

const data = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];

console.log(split(data));```


问:
Position absolute keeps pushing objects outside of the frame
Sorry, beginner in programming. but I am having an issue with some code.

I am trying to add a white background in the back of the text I, but there's a lot of empty white space in it. This: example 1

What i am trying to make is this: example 2

So, my approach for this is putting the paragraph in a div, and giving it the following code:

```<code>.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    margin-top: 30px;
}
</code>```

and the tittle to have its background white, position absolute and margin big enough that it will go under the text, giving it the feeling like its same pannel.
But the tittle goes automatically on top of the page.

Why's this happening?

Here's an example of the code for the block:

```<code><h2>The problem</h2>
<div class="i_box">
<p>test test test </p>
</div>
</code>```

any suggestion please?
can't seem to figure this out

答:
Here is the coding for something similar to what you asked for.

body {
  background-color: skyblue;
}

.i_box {
  background-color: rgb(245, 244, 244);
  border-radius: 7px;
  padding-left: 15px;
  padding-right: 15px;
  color: #1a1e23;
  padding-top: 0.2px;
  padding-bottom: 8px;
  margin-bottom: 30px;
  size: relative;
  /* margin-top: 30px; */
}

.wrapper {
  text-align: center;
}

.wrapper > h2 {
  display: inline-block;
  border-radius: 7px;
  background-color: white;
  padding: 10px 20px;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <h2>The problem</h2>
</div>
<div class="i_box">
  <p>test test test </p>
</div></code>```

Body:
Sorry, beginner in programming. but I am having an issue with some code.

I am trying to add a white background in the back of the text I, but there's a lot of empty white space in it. This: example 1

What i am trying to make is this: example 2

So, my approach for this is putting the paragraph in a div, and giving it the following code:

.i_box{
    background-color: rgb(245, 244, 244);
    border-radius: 7px;
    padding-left: 15px;
    padding-right: 15px;
    color: #1a1e23;
    padding-top: 0.2px;
    padding-bottom: 8px;
    margin-bottom: 30px;
    margin-top: 30px;
}

and the tittle to have its background white, position absolute and margin big enough that it will go under the text, giving it the feeling like its same pannel.
But the tittle goes automatically on top of the page.

Why's this happening?

Here's an example of the code for the block:

The problem

test test test

any suggestion please?
can't seem to figure this out

Body:
Here is the coding for something similar to what you asked for.

body {
  background-color: skyblue;
}

.i_box {
  background-color: rgb(245, 244, 244);
  border-radius: 7px;
  padding-left: 15px;
  padding-right: 15px;
  color: #1a1e23;
  padding-top: 0.2px;
  padding-bottom: 8px;
  margin-bottom: 30px;
  size: relative;
  /* margin-top: 30px; */
}

.wrapper {
  text-align: center;
}

.wrapper > h2 {
  display: inline-block;
  border-radius: 7px;
  background-color: white;
  padding: 10px 20px;
  margin: 0;
}

<div class="wrapper">
  <h2>The problem</h2>
</div>
<div class="i_box">
  <p>test test test </p>
</div>


问:
how to transpose a dataset from wide format to long format in R
The dataset is similar to the following:

```<code>ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150
</code>```

*There are over 200 variables

I want the output to be as following:

```<code>ID SEX n bloodpressure weight
1   1  1      90        100
1   1  2      100       105
1   1  3      NA        112
2   0  1      101       140
2   0  2      120       NA
2   0  3      115       150
</code>```

I tried solutions offered in this link:
Using Reshape from wide to long in R
but since the variable names in my dataset does not have '_' between the letter and the number, I don't how to separate the column name to make it work.

Thank you in advance for any help!

答:
There are lots of examples on SO about reshaping. Probably the most common question. All you have to do is search.

```<code>reshape(data, direction="long", idvar="ID", varying=3:8, sep="")

    ID SEX time bloodpressure weight
1.1  1   1    1            90    100
2.1  2   0    1           101    140
1.2  1   1    2           100    105
2.2  2   0    2           120     NA
1.3  1   1    3            NA    112
2.3  2   0    3           115    150
</code>```

The help page of reshape clearly explains the use of the sep argument. You can also try using tidy's pivot_longer function. Read the docs. ;)

Data:

```<code>data <- read.table(text="ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150", header=TRUE)
</code>```

Body:
The dataset is similar to the following:

ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150

*There are over 200 variables

I want the output to be as following:

ID SEX n bloodpressure weight
1   1  1      90        100
1   1  2      100       105
1   1  3      NA        112
2   0  1      101       140
2   0  2      120       NA
2   0  3      115       150

I tried solutions offered in this link:
Using Reshape from wide to long in R
but since the variable names in my dataset does not have '_' between the letter and the number, I don't how to separate the column name to make it work.

Thank you in advance for any help!

Body:
There are lots of examples on SO about reshaping. Probably the most common question. All you have to do is search.

reshape(data, direction="long", idvar="ID", varying=3:8, sep="")

    ID SEX time bloodpressure weight
1.1  1   1    1            90    100
2.1  2   0    1           101    140
1.2  1   1    2           100    105
2.2  2   0    2           120     NA
1.3  1   1    3            NA    112
2.3  2   0    3           115    150

The help page of reshape clearly explains the use of the sep argument. You can also try using tidy's pivot_longer function. Read the docs. ;)

Data:

data <- read.table(text="ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150", header=TRUE)


问:
Change foreground color of calendar items
I'm customizing a calendar control in WPF and I'm able to adjust the background color, header foreground colors etc.. But I can't find how to edit the appearance of the 1-31 day calendar items. At the

Screenshot:

As you can see, the numbers are all dark grey and almost not readable. I would also like to get the rid of the blue-ish overlay on mouseover.

Code:

```<code><Window x:Class="WPFDatePickerSample.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window2" Height="500" Width="500"
    Background="#2F2F2F">

<Window.Resources>
    <Style TargetType="{x:Type CalendarItem}">
        <Setter Property="Margin" Value="50"/>

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CalendarItem}">
                    <ControlTemplate.Resources>
                        <DataTemplate x:Key="{x:Static CalendarItem.DayTitleTemplateResourceKey}">
                            <TextBlock Foreground="#FFA9C822" FontWeight="Normal" FontSize="12" HorizontalAlignment="Center" Margin="0,5,0,5" Text="{Binding}" VerticalAlignment="Center"/>
                        </DataTemplate>
                    </ControlTemplate.Resources>

                    <Grid x:Name="PART_Root">
                        <Grid.Resources>
                            <SolidColorBrush x:Key="DisabledColor" Color="#A5FFFFFF"/>
                        </Grid.Resources>

                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="PART_DisabledVisual"/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>

                        <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="1">
                            <Border BorderBrush="#FFFFFFFF" BorderThickness="0" CornerRadius="0">
                                <Grid>
                                    <Grid.Resources>
                                        <ControlTemplate x:Key="PreviousButtonTemplate" TargetType="{x:Type Button}">
                                            <Grid Cursor="Hand">
                                                <VisualStateManager.VisualStateGroups>
                                                    <VisualStateGroup x:Name="CommonStates">
                                                        <VisualState x:Name="Normal"/>
                                                        <VisualState x:Name="MouseOver">
                                                            <Storyboard>
                                                                <ColorAnimation Duration="0" To="#FFA9C822" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="path"/>
                                                            </Storyboard>
                                                        </VisualState>
                                                        <VisualState x:Name="Disabled">
                                                            <Storyboard>
                                                                <DoubleAnimation Duration="0" To=".5" Storyboard.TargetProperty="(Shape.Fill).(Brush.Opacity)" Storyboard.TargetName="path"/>
                                                            </Storyboard>
                                                        </VisualState>
                                                    </VisualStateGroup>
                                                </VisualStateManager.VisualStateGroups>

                                                <Rectangle Fill="Transparent" Opacity="1" Stretch="Fill"/>

                                                <Grid>
                                                    <Path x:Name="path" Data="M288.75,232.25 L288.75,240.625 L283,236.625 z" Fill="Silver" HorizontalAlignment="Left" Height="10" Margin="5,-6,0,0" Stretch="Fill" VerticalAlignment="Center" Width="6"/>
                                                </Grid>
                                            </Grid>
                                        </ControlTemplate>

                                        <ControlTemplate x:Key="NextButtonTemplate" TargetType="{x:Type Button}">
                                            <Grid Cursor="Hand">
                                                <VisualStateManager.VisualStateGroups>
                                                    <VisualStateGroup x:Name="CommonStates">
                                                        <VisualState x:Name="Normal"/>
                                                        <VisualState x:Name="MouseOver">
                                                            <Storyboard>
                                                                <ColorAnimation Duration="0" To="#FFA9C822" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="path"/>
                                                            </Storyboard>
                                                        </VisualState>

                                                        <VisualState x:Name="Disabled">
                                                            <Storyboard>
                                                                <DoubleAnimation Duration="0" To=".5" Storyboard.TargetProperty="(Shape.Fill).(Brush.Opacity)" Storyboard.TargetName="path"/>
                                                            </Storyboard>
                                                        </VisualState>
                                                    </VisualStateGroup>
                                                </VisualStateManager.VisualStateGroups>

                                                <Rectangle Fill="Transparent" Opacity="1" Stretch="Fill"/>

                                                <Grid>
                                                    <Path x:Name="path" Data="M282.875,231.875 L282.875,240.375 L288.625,236 z" Fill="Silver" HorizontalAlignment="Right" Height="10" Margin="0,-6,5,0" Stretch="Fill" VerticalAlignment="Center" Width="6"/>
                                                </Grid>
                                            </Grid>
                                        </ControlTemplate>

                                        <ControlTemplate x:Key="HeaderButtonTemplate" TargetType="{x:Type Button}">
                                            <Grid Cursor="Hand">
                                                <VisualStateManager.VisualStateGroups>
                                                    <VisualStateGroup x:Name="CommonStates">
                                                        <VisualState x:Name="Normal"/>
                                                        <VisualState x:Name="MouseOver">
                                                            <Storyboard>
                                                                <DoubleAnimation Duration="0" To=".7" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="buttonContent"/>
                                                            </Storyboard>
                                                        </VisualState>

                                                        <VisualState x:Name="Disabled">
                                                            <Storyboard>
                                                                <DoubleAnimation Duration="0" To=".5" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="buttonContent"/>
                                                            </Storyboard>
                                                        </VisualState>
                                                    </VisualStateGroup>
                                                </VisualStateManager.VisualStateGroups>

                                                <ContentPresenter x:Name="buttonContent" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" TextElement.Foreground="Silver" TextElement.FontFamily="Segoe UI" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="1,3,1,9" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                            </Grid>
                                        </ControlTemplate>
                                    </Grid.Resources>

                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="Auto"/>
                                    </Grid.ColumnDefinitions>

                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="*"/>
                                    </Grid.RowDefinitions>

                                    <Grid Grid.Row="0" Grid.ColumnSpan="4" Background="#3C3C3C" HorizontalAlignment="Stretch">
                                        <Button x:Name="PART_PreviousButton" Grid.Column="0" Focusable="False" HorizontalAlignment="Left" Height="20" Grid.Row="0" Template="{StaticResource PreviousButtonTemplate}" Width="28"/>
                                        <Button x:Name="PART_HeaderButton" Grid.Column="1" FontWeight="Normal" Focusable="False" FontSize="13" HorizontalAlignment="Center" Grid.Row="0" Template="{StaticResource HeaderButtonTemplate}" VerticalAlignment="Center" />
                                        <Button x:Name="PART_NextButton" Grid.Column="2" Focusable="False" HorizontalAlignment="Right" Height="20" Grid.Row="0" Template="{StaticResource NextButtonTemplate}" Width="28"/>
                                    </Grid>
                                    <Grid x:Name="PART_MonthView" Grid.ColumnSpan="3" HorizontalAlignment="Center" Margin="6,-1,6,6" Grid.Row="1" Visibility="Visible">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                        </Grid.RowDefinitions>
                                    </Grid>

                                    <Grid x:Name="PART_YearView" Grid.ColumnSpan="3" HorizontalAlignment="Center" Margin="6,-3,7,6" Grid.Row="1" Visibility="Hidden">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="Auto"/>
                                        </Grid.RowDefinitions>
                                    </Grid>
                                </Grid>
                            </Border>
                        </Border>

                        <Rectangle x:Name="PART_DisabledVisual" Fill="{StaticResource DisabledColor}" Opacity="0" RadiusY="2" RadiusX="2" Stretch="Fill" Stroke="{StaticResource DisabledColor}" StrokeThickness="1" Visibility="Collapsed"/>
                    </Grid>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Visibility" TargetName="PART_DisabledVisual" Value="Visible" />
                        </Trigger>

                        <DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Calendar}}}" Value="Year">
                            <Setter Property="Visibility" TargetName="PART_MonthView" Value="Hidden" />
                            <Setter Property="Visibility" TargetName="PART_YearView" Value="Visible" />
                        </DataTrigger>

                        <DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Calendar}}}" Value="Decade">
                            <Setter Property="Visibility" TargetName="PART_MonthView" Value="Hidden" />
                            <Setter Property="Visibility" TargetName="PART_YearView" Value="Visible" />
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style TargetType="{x:Type Calendar}">
        <Setter Property="Background" Value="#3C3C3C"/>

        <Setter Property="SnapsToDevicePixels" Value="True" />
        <Setter Property="BorderBrush" Value="Transparent" />
        <Setter Property="BorderThickness" Value="1" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Calendar}">
                    <StackPanel x:Name="PART_Root" HorizontalAlignment="Center">
                        <CalendarItem x:Name="PART_CalendarItem" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" />
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<Grid>
    <Calendar Width="400" Height="400"></Calendar>
</Grid>
</code>```

答:
To style CalendarDayButton you could achieve the desired effect using VisualStateManager as shown in @Nemesis answer BUT doing that with VisualStateManager looks clumsy. For styling a simple Calendar in my recent application I've used Trigger instead of VisualStateManager:

```<code><Style TargetType="CalendarDayButton" x:Key="CalendarDayButtonStyle">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="CalendarDayButton">
                <Border x:Name="day" CornerRadius="5" Width="20" Height="20">
                    <ContentPresenter x:Name="presenter"
                                    HorizontalAlignment="Center"
                                    VerticalAlignment="Center"
                                    TextElement.FontSize="12"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="day" Property="Background" Value="LightBlue"/>
                    </Trigger>
                    <Trigger Property="IsToday" Value="True">
                        <Setter TargetName="day" Property="Background" Value="Bisque"/>
                    </Trigger>
                    <Trigger Property="IsInactive" Value="True">
                        <Setter TargetName="presenter" Property="TextElement.Foreground" Value="LightGray"/>
                        <Setter TargetName="presenter" Property="TextElement.FontStyle" Value="Italic"/>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsMouseOver" Value="True"/>
                            <Condition Property="IsInactive" Value="True"/>
                        </MultiTrigger.Conditions>
                        <Setter TargetName="presenter" Property="TextElement.Foreground" Value="Black"/>
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm customizing a calendar control in WPF and I'm able to adjust the background color, header foreground colors etc.. But I can't find how to edit the appearance of the 1-31 day calendar items. At the

Screenshot:

As you can see, the numbers are all dark grey and almost not readable. I would also like to get the rid of the blue-ish overlay on mouseover.

Code:

<Window x:Class="WPFDatePickerSample.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window2" Height="500" Width="500"
    Background="#2F2F2F">

<Window.Resources>

</Window.Resources>

<Grid>
    <Calendar Width="400" Height="400"></Calendar>
</Grid>

Body:
To style CalendarDayButton you could achieve the desired effect using VisualStateManager as shown in @Nemesis answer BUT doing that with VisualStateManager looks clumsy. For styling a simple Calendar in my recent application I've used Trigger instead of VisualStateManager:

<Style TargetType="CalendarDayButton" x:Key="CalendarDayButtonStyle">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="CalendarDayButton">
                <Border x:Name="day" CornerRadius="5" Width="20" Height="20">
                    <ContentPresenter x:Name="presenter"
                                    HorizontalAlignment="Center"
                                    VerticalAlignment="Center"
                                    TextElement.FontSize="12"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="day" Property="Background" Value="LightBlue"/>
                    </Trigger>
                    <Trigger Property="IsToday" Value="True">
                        <Setter TargetName="day" Property="Background" Value="Bisque"/>
                    </Trigger>
                    <Trigger Property="IsInactive" Value="True">
                        <Setter TargetName="presenter" Property="TextElement.Foreground" Value="LightGray"/>
                        <Setter TargetName="presenter" Property="TextElement.FontStyle" Value="Italic"/>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsMouseOver" Value="True"/>
                            <Condition Property="IsInactive" Value="True"/>
                        </MultiTrigger.Conditions>
                        <Setter TargetName="presenter" Property="TextElement.Foreground" Value="Black"/>
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


问:
Add of std::valarray got different sizes with different operand orders
Add of std::valarray got different sizes with different operand orders.

Code is as the following:

```<code>#include <iostream>
#include <valarray>
using namespace std;

int main() {
    std::valarray<float> v0{3.f, 0.f};
    std::valarray<float> v1{0.f};
    std::valarray<float> v2 = v0 + v1;
    std::valarray<float> v3 = v1 + v0;
    cout << v2.size() << endl; // 2
    cout << v3.size() << endl; // 1
}
</code>```

Compilers:

```<code>g++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0
clang version 9.0.0-2~ubuntu18.04.2 (tags/RELEASE_900/final)
</code>```

答:
operator+() does not perfom concatenation of two  std::valarray<float> objects,

```<code>std::valarray<float> v2 = v0 + v1;
</code>```

Here, since v1 is of size 1, it will add the only value in v1 to both the elements in v0, hence size stays 2.

```<code>std::valarray<float> v2 = v1 + v0;
</code>```

But here, v1 is of size 1, it will add the first element 3.f to the only element in v1 and second value of v0 is ignored.
This is what usually happens, but nevertheless the behaviour of binary operations on two valarrays are undefined.

Body:
Add of std::valarray got different sizes with different operand orders.

Code is as the following:

#include <iostream>
#include <valarray>
using namespace std;

int main() {
    std::valarray<float> v0{3.f, 0.f};
    std::valarray<float> v1{0.f};
    std::valarray<float> v2 = v0 + v1;
    std::valarray<float> v3 = v1 + v0;
    cout << v2.size() << endl; // 2
    cout << v3.size() << endl; // 1
}

Compilers:

g++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0
clang version 9.0.0-2~ubuntu18.04.2 (tags/RELEASE_900/final)

Body:
operator+() does not perfom concatenation of two  std::valarray<float> objects,

std::valarray<float> v2 = v0 + v1;

Here, since v1 is of size 1, it will add the only value in v1 to both the elements in v0, hence size stays 2.

std::valarray<float> v2 = v1 + v0;

But here, v1 is of size 1, it will add the first element 3.f to the only element in v1 and second value of v0 is ignored.
This is what usually happens, but nevertheless the behaviour of binary operations on two valarrays are undefined.


问:
How to change which option is selected based on user's previous input
Is there a way to change which <option> is selected based on what a user previously selected? I'm making a Flask app where users can input data into a form but if are not logged in, will need to log in and then be redirected back to the form. I want their previous input to be "stored" so they don't have to enter the info twice.

To store the information, I've used sessions and have tried something like <input value = {{session.email}}> This works for the <input> attribute but am wondering how to get the same effect with the <select> attribute.

答:
I understand that you have the selected option, something like session.selectedOption, you can set the attribute selected for the option you want

<select>
  <option>1</option>
  <option selected>2</option>
  <option>3</option>
  <option>4</option>
</select>
```


问:
How to pop a UIViewControllerRepresentable from a SwiftUI navigation stack programmatically
Here is my SwiftUI setup:

I have a SwiftUI view (called MapSearchView) that has a NavigationView that contains a NavigationLink.

```<code>    var body: some View {
    VStack {
        NavigationView {
            Form {
                Section (header: Text("Location")){
                    NavigationLink (locationString, destination: GooglePlacesViewController(mapTools: $mapTools))
                }...
</code>```

The NavigationLink's destination is a UIViewControllerRepresentable which wraps a GooglePlacesViewController. When I am done with my GooglePlaces search (either because I made a selection or I cancelled the search), I want to programmatically pop back to the MapSearchView.

I have tried adding the following in the UIViewControllerRepresentable (GooglePlacesViewController):

```<code>    @Environment(\.presentationMode) var presentationMode

var popToPrevious : Bool = false {
    didSet {
        if popToPrevious == true {
            self.presentationMode.wrappedValue.dismiss()
        }
    }
}
</code>```

and setting the popToPrevious to true in my Coordinator using

```<code>parent.popToPrevious = true
</code>```

It does get called, but does nothing.

I have also tried in the Coordinator to call

view.viewController().navigationController.popViewController(animated: true)

(viewController() is an extension that gets the viewController for any view)

This also does nothing.

Ideas?

答:
If you create Coordinator with owner view (ie. your representable), then try to call directly when needed</p>

```<code>ownerView.presentationMode.wrappedValue.dismiss()
</code>```

Body:
Here is my SwiftUI setup:

I have a SwiftUI view (called MapSearchView) that has a NavigationView that contains a NavigationLink.

    var body: some View {
    VStack {
        NavigationView {
            Form {
                Section (header: Text("Location")){
                    NavigationLink (locationString, destination: GooglePlacesViewController(mapTools: $mapTools))
                }...

The NavigationLink's destination is a UIViewControllerRepresentable which wraps a GooglePlacesViewController. When I am done with my GooglePlaces search (either because I made a selection or I cancelled the search), I want to programmatically pop back to the MapSearchView.

I have tried adding the following in the UIViewControllerRepresentable (GooglePlacesViewController):

    @Environment(\.presentationMode) var presentationMode

var popToPrevious : Bool = false {
    didSet {
        if popToPrevious == true {
            self.presentationMode.wrappedValue.dismiss()
        }
    }
}

and setting the popToPrevious to true in my Coordinator using

parent.popToPrevious = true

It does get called, but does nothing.

I have also tried in the Coordinator to call

view.viewController().navigationController.popViewController(animated: true)

(viewController() is an extension that gets the viewController for any view)

This also does nothing.

Ideas?

Body:
If you create Coordinator with owner view (ie. your representable), then try to call directly when needed

ownerView.presentationMode.wrappedValue.dismiss()


问:
Does the png file contain string `0.0.0.0`?
I had upload the png file into my dropbox,you can download as /tmp/mount.png to reproduce my output.

mount.png in my dropbox

man grep :

```<code> -a, --text
          Process a binary file as if it were text
</code>```

Search '0.0.0.0' in a png file with grep.

```<code>grep -a  "0.0.0.0"  /tmp/mount.png
</code>```

I have never seen 0.0.0.0 by eye.

Does the png file contains string 0.0.0.0 really?

The hex value of 0.0.0.0 is :

```<code>echo -n '0.0.0.0' |xxd
00000000: 302e 302e 302e 30                        0.0.0.0
</code>```

Let's search it with hex value:

```<code>xxd  /tmp/mount.png |grep '302e302e302e30'
</code>```

Nothing you can get.

```<code>xxd  /tmp/mount.png |grep '302e'
</code>```

Nothing you can get too.

Does the png file contain string 0.0.0.0 ?

答:
It contains the string 00000008 part of which matches the regex 0.0.0.0. In a regex . matches any character, including 0.

To match the literal string 0.0.0.0 you can use fgrep or the -F argument to grep.

Body:
I had upload the png file into my dropbox,you can download as /tmp/mount.png to reproduce my output.

mount.png in my dropbox

man grep :

 -a, --text
          Process a binary file as if it were text

Search '0.0.0.0' in a png file with grep.

grep -a  "0.0.0.0"  /tmp/mount.png

I have never seen 0.0.0.0 by eye.

Does the png file contains string 0.0.0.0 really?

The hex value of 0.0.0.0 is :

echo -n '0.0.0.0' |xxd
00000000: 302e 302e 302e 30                        0.0.0.0

Let's search it with hex value:

xxd  /tmp/mount.png |grep '302e302e302e30'

Nothing you can get.

xxd  /tmp/mount.png |grep '302e'

Nothing you can get too.

Does the png file contain string 0.0.0.0 ?


问:
Popping elements from array efficiently
Consider an array which we know will have integers from 0 to n in sequence, starting at 0. For example:

```<code>a=[0,1,2]
</code>```

Now, we pop the element at position 1.

```<code>a.pop(1)
</code>```

The array we are left with:

```<code>[0,2]
</code>```

And we have a[0]=0, a[1]=2.
Let's pop the element at position 0.

```<code>a.pop(0)
</code>```

We are left with:

```<code>[2]
</code>```

Now, referencing a[0] will yield 2.

This is the behavior I want, except that the pop operations are O(n) in time since the entire array needs to be copied over to the left. Is there a way to do this more efficiently so that each pop (or equivalent) operation is no more than O(log(n))? It's okay to take another O(n) of space if required.

After the sequence of operations shown above, querying for index 0 in the end should still return 2. I tried storing the popped elements in a binary search tree (without actually popping), but the logic became too convoluted.

答:
You seem to be asking for an alternative data structure. Linked lists are good at insertion and deletion from an arbitrary position, but you need to have a reference to the location where you want to insert or delete; otherwise, you'll be spending O(n) scanning to the location that you want to insert or delete from.

As far as I know, there is no linked list in Python's standard library, but you could implement your own.

At the end of the day, you can't do "the exact same thing" in less time; something has to give. You need to relax one of your requirements (e.g. that the list type be used).

An alternative requirement you might be able to relax is "the existing elements need to remain in the same order". If you don't mind a little re-ordering, you can swap lst[i] with lst[-1]. Then, pop from the end (which is efficient for lists). This can be done pretty easily using Python's tuple assignment. Like so:

```<code>lst[i], lst[-1] = lst[-1], lst[i]  # swap
lst.pop()  # Now, the item that you wanted removed is gone,
           # but the remaining elements are not
           # all in the same order as before,
           # but they mostly are.
</code>```

This is often a viable alternative, because you don't always care about the order of a list.

Title: Popping elements from array efficiently

Body:
Consider an array which we know will have integers from 0 to n in sequence, starting at 0. For example:

a=[0,1,2]

Now, we pop the element at position 1.

a.pop(1)

The array we are left with:

[0,2]

And we have a[0]=0, a[1]=2.
Let's pop the element at position 0.

a.pop(0)

We are left with:

[2]

Now, referencing a[0] will yield 2.

This is the behavior I want, except that the pop operations are O(n) in time since the entire array needs to be copied over to the left. Is there a way to do this more efficiently so that each pop (or equivalent) operation is no more than O(log(n))? It's okay to take another O(n) of space if required.

After the sequence of operations shown above, querying for index 0 in the end should still return 2. I tried storing the popped elements in a binary search tree (without actually popping), but the logic became too convoluted.

Body:
You seem to be asking for an alternative data structure. Linked lists are good at insertion and deletion from an arbitrary position, but you need to have a reference to the location where you want to insert or delete; otherwise, you'll be spending O(n) scanning to the location that you want to insert or delete from.

As far as I know, there is no linked list in Python's standard library, but you could implement your own.

At the end of the day, you can't do "the exact same thing" in less time; something has to give. You need to relax one of your requirements (e.g. that the list type be used).

An alternative requirement you might be able to relax is "the existing elements need to remain in the same order". If you don't mind a little re-ordering, you can swap lst[i] with lst[-1]. Then, pop from the end (which is efficient for lists). This can be done pretty easily using Python's tuple assignment. Like so:

lst[i], lst[-1] = lst[-1], lst[i]  # swap
lst.pop()  # Now, the item that you wanted removed is gone,
           # but the remaining elements are not
           # all in the same order as before,
           # but they mostly are.

This is often a viable alternative, because you don't always care about the order of a list.


问:
How to target child element in css within a div?
I have a
 parent element with the id="workflow". For the .active styling, may I know how to target the li element within it in the html? I have no issue with the first few blocks of the css with div#workflow.

```<code>        div#workflow li {
            width: 5em;
            height: 5em;
            text-align: center;
            line-height: 5em;
            border-radius: 5em;
            background: dodgerblue;
            margin: 0 1.8em;
            display: inline-block;
            color: white;
            position: relative;
        }

        div#workflow li::before {
            content: '';
            position: absolute;
            top: 2.5em;
            left: -4em;
            width: 4em;
            height: .2em;
            background: dodgerblue;
            z-index: 1;
        }

        div#workflow li:first-child::before {
            display: none;
        }

        .active {
          background: dodgerblue;
        }

        .active ~ li {
          background: lightblue;
        }

        .active ~ li::before {
          background: lightblue;
        }

   <div id="workflow">
            <ul style="font-size:12px;">
              <li >Create</li>
              <li>Submitted</li>
              <li>In Process</li>
              <li class="active">Complete</li>
              <li>Closed</li>
            </ul>
        </div>
</code>```

答:
Try the below selector.</p>

```<code>#workflow > li {
      #your styling here
    }
</code>```

Body:
I have a
 parent element with the id="workflow". For the .active styling, may I know how to target the li element within it in the html? I have no issue with the first few blocks of the css with div#workflow.

        div#workflow li {
            width: 5em;
            height: 5em;
            text-align: center;
            line-height: 5em;
            border-radius: 5em;
            background: dodgerblue;
            margin: 0 1.8em;
            display: inline-block;
            color: white;
            position: relative;
        }

        div#workflow li::before {
            content: '';
            position: absolute;
            top: 2.5em;
            left: -4em;
            width: 4em;
            height: .2em;
            background: dodgerblue;
            z-index: 1;
        }

        div#workflow li:first-child::before {
            display: none;
        }

        .active {
          background: dodgerblue;
        }

        .active ~ li {
          background: lightblue;
        }

        .active ~ li::before {
          background: lightblue;
        }

Create

Submitted

In Process

Complete

Closed

Body:
Try the below selector.

#workflow > li {
      #your styling here
    }


问:
Print specific "columns" of text file that has a somewhat inconsistent format
I'm trying to extract three columns from a text file that looks like this:

```<code><Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael’s Apple Watch" sourceVersion="6.2.5" device="<<HKDevice: 0x2877dc870>, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D>" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72">
<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>
</code>```

This is the information I'd like to extract:

```<code>sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39", "72"
"Wahoo", "2020-05-30 07:37:05", "83"
</code>```

So I basically need the source name, full creationDate and value in a comma-separated format.

The issue I'm having is that sourceName itself has multiple nested "fields" and creationDate has spaces. So my previous attempts using grep and awk all failed :)

Any help would be greatly appreciated.

答:
Whenever you have "tag=value" data, its best to first create an array indexed by tags (names) and then you can just test or print whatever you you want in whatever order you want. Assuming your input is a regular as the sample you posted and you can't use an XML parser then using GNU awk for the 3rd arg to match():

```<code>$ cat tst.awk
BEGIN {
    OFS = ", "
    numTags = split("sourceName creationDate value",tags)
    for (tagNr=1; tagNr<=numTags; tagNr++) {
        tag = tags[tagNr]
        printf "%s%s", tag, (tagNr<numTags ? OFS : ORS)
    }
}
{
    delete tag2val
    while ( match($0,/([^=[:space:]]+)=("[^"]+")/,a) ) {
        tag = a[1]
        val = a[2]
        tag2val[tag] = val
        $0 = substr($0,RSTART+RLENGTH)
    }
    for (tagNr=1; tagNr<=numTags; tagNr++) {
        tag = tags[tagNr]
        val = tag2val[tag]
        printf "%s%s", val, (tagNr<numTags ? OFS : ORS)
    }
}
</code>```

.

```<code>$ awk -f tst.awk file
sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39 -0400", "72"
"Wahoo", "2020-05-30 07:37:05 -0400", "83"
</code>```

Body:
I'm trying to extract three columns from a text file that looks like this:

<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael’s Apple Watch" sourceVersion="6.2.5" device="<<HKDevice: 0x2877dc870>, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D>" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72">
<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>

This is the information I'd like to extract:

sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39", "72"
"Wahoo", "2020-05-30 07:37:05", "83"

So I basically need the source name, full creationDate and value in a comma-separated format.

The issue I'm having is that sourceName itself has multiple nested "fields" and creationDate has spaces. So my previous attempts using grep and awk all failed :)

Any help would be greatly appreciated.

Body:
Whenever you have "tag=value" data, its best to first create an array indexed by tags (names) and then you can just test or print whatever you you want in whatever order you want. Assuming your input is a regular as the sample you posted and you can't use an XML parser then using GNU awk for the 3rd arg to match():

$ cat tst.awk
BEGIN {
    OFS = ", "
    numTags = split("sourceName creationDate value",tags)
    for (tagNr=1; tagNr<=numTags; tagNr++) {
        tag = tags[tagNr]
        printf "%s%s", tag, (tagNr<numTags ? OFS : ORS)
    }
}
{
    delete tag2val
    while ( match($0,/([^=[:space:]]+)=("[^"]+")/,a) ) {
        tag = a[1]
        val = a[2]
        tag2val[tag] = val
        $0 = substr($0,RSTART+RLENGTH)
    }
    for (tagNr=1; tagNr<=numTags; tagNr++) {
        tag = tags[tagNr]
        val = tag2val[tag]
        printf "%s%s", val, (tagNr<numTags ? OFS : ORS)
    }
}

.

$ awk -f tst.awk file
sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39 -0400", "72"
"Wahoo", "2020-05-30 07:37:05 -0400", "83"


问:
sample from two unique categories in R
I have 100 unique IDs and 8 unique weeks. I want to sample such that I want one sample with unique ID and unique week. For example ID 1 was sampled 8 times at each week ID 2 was sampled 8 times and so on. I thus have now 800 rows.

答: df %>% group_bt(ID, category) %>% sample_n(1) will sample one row from each unique ID:category combination.

Title: sample from two unique categories in R


问:
EventListener(ended) firing more than once
I am trying to make a music-app, so what I want to do is when the current music ends, it will automatically plays the next song in line, but what happens is, the EventListener get triggered by times 2, firstly it is triggered one time, and then 2 time, and then 4, and the number keeps increasing every time the EventListener gets triggered, I've tried searching for solutions in other websites but I just can't seem to find the answer, hope anyone can help

By the way I am using vue js

these are my data

```<code>data () {
return {
  current: {},
  index: 0,
  isPlaying: false,
  api_key: '4f40bf40b2msh6d957020229b6c6p1fe925jsn4ef16ee46284',
  url_base: 'https://deezerdevs-deezer.p.rapidapi.com',
  songs: [],
  query:'',
  player: new Audio()
}
},
</code>```

and this is my method for playing the music

```<code>play (song) {
  if (typeof song.title != "undefined") {
    this.current = song;
    this.player.src = this.current.preview;
  }

  this.player.play();
  //console.log(this.player);
  this.player.addEventListener('ended', function () {
    console.log(this.index);
    //this.index++;
    if (this.index > this.songs.length - 1) {
      this.index = 0;
    }
    this.current = this.songs[this.index];
    this.play(this.current);
  }.bind(this));

  this.isPlaying = true;
},
</code>```

if anyone has better suggestion for me to make this will also be a huge favour

答:
The symptoms are caused by adding the event listener multiple times without removing it. Solutions include

adding the event listener once, outside the operational loop of play(), raising an ended event, handling the ended event, and calling play again (from within the listener).

removing the previous event handler, if one was added, from within the ended handler before adding a new handler. Not recommended because of the additional complexity of maintaining a reference to the function returned by bind in order to remove it later.

have the browser remove the handler for you after calling it, by including  {once: true} as the third argument of addEventListener when adding the event handler:

```<code>this.player.addEventListener('ended', function () {
    // handler to play once, loop, loop to end, shuffle or whatever
}.bind(this), {once: true});
</code>```

Check the browser compatibility section of the MDN documentation however - using the option effectively means dropping for support for IE.

Body:
I am trying to make a music-app, so what I want to do is when the current music ends, it will automatically plays the next song in line, but what happens is, the EventListener get triggered by times 2, firstly it is triggered one time, and then 2 time, and then 4, and the number keeps increasing every time the EventListener gets triggered, I've tried searching for solutions in other websites but I just can't seem to find the answer, hope anyone can help

By the way I am using vue js

these are my data

data () {
return {
  current: {},
  index: 0,
  isPlaying: false,
  api_key: '4f40bf40b2msh6d957020229b6c6p1fe925jsn4ef16ee46284',
  url_base: 'https://deezerdevs-deezer.p.rapidapi.com',
  songs: [],
  query:'',
  player: new Audio()
}
},

and this is my method for playing the music

play (song) {
  if (typeof song.title != "undefined") {
    this.current = song;
    this.player.src = this.current.preview;
  }

  this.player.play();
  //console.log(this.player);
  this.player.addEventListener('ended', function () {
    console.log(this.index);
    //this.index++;
    if (this.index > this.songs.length - 1) {
      this.index = 0;
    }
    this.current = this.songs[this.index];
    this.play(this.current);
  }.bind(this));

  this.isPlaying = true;
},

if anyone has better suggestion for me to make this will also be a huge favour

Body:
The symptoms are caused by adding the event listener multiple times without removing it. Solutions include

adding the event listener once, outside the operational loop of play(), raising an ended event, handling the ended event, and calling play again (from within the listener).

removing the previous event handler, if one was added, from within the ended handler before adding a new handler. Not recommended because of the additional complexity of maintaining a reference to the function returned by bind in order to remove it later.

have the browser remove the handler for you after calling it, by including  {once: true} as the third argument of addEventListener when adding the event handler:

this.player.addEventListener('ended', function () {
    // handler to play once, loop, loop to end, shuffle or whatever
}.bind(this), {once: true});

Check the browser compatibility section of the MDN documentation however - using the option effectively means dropping for support for IE.


问:
How can I create a RoI pooling layer in tensorlfow/keras?
I've programmed a VGG16 based CNN and now I want to create a faster R-CNN from it. In all the architecture photos I've seen it is needed to have a RoI pooling layer but I don't know how to implement one. Is there an function to do this?</p>

答:
Keras/Tensorflow does not provide an implementation of ROI Pooling Layer, so you need to code it yourself.

You can have code reference from this repository


问:
How to Get and Manipulate Elements Inside an iframe from a Relative Path in Angular
So I have two components (Preview component and an app component) in an angular project. I displayed one of the components (preview Component) inside the other(app component) through a relative path in an iframe:

app.component.html

```<code> <iframe
               src="/pagepreview"
               width="478"
               height="926"
               id="iframeId"
               #previewFrame
               >Alternative text
 </iframe>

</code>```

Now, In the app.component.ts file, I want to access the elements of the preview template, so I did this:

```<code> @ViewChild(`previewFrame`,{ static: true }) previewFrame: ElementRef;

  onLoad()  {
  let frameEl: HTMLIFrameElement = this.previewFrame.nativeElement;
  let showTemplate = frameEl.innerHTML
     console.log(showTemplate )

}
</code>```

The result I got was the Alternative text word inside the iframe tag.

Does anyone have an idea how I can get to access the HTML tags in the preview component page? I need to do this so I can do some DOM manipulation of the page preview component on the app component page. Thanks.

答:
Apparently the page renders faster than the function that calls the DOM object, despite calling it inside an ngAfterViewInit life cycle hook. I added a setTimeout() function and now I'm able to get the DOM elements I want.

This answer provided the context to my solution.

Body:
So I have two components (Preview component and an app component) in an angular project. I displayed one of the components (preview Component) inside the other(app component) through a relative path in an iframe:

app.component.html

 Alternative text

Now, In the app.component.ts file, I want to access the elements of the preview template, so I did this:

 @ViewChild(`previewFrame`,{ static: true }) previewFrame: ElementRef;

  onLoad()  {
  let frameEl: HTMLIFrameElement = this.previewFrame.nativeElement;
  let showTemplate = frameEl.innerHTML
     console.log(showTemplate )

}

The result I got was the Alternative text word inside the iframe tag.

Does anyone have an idea how I can get to access the HTML tags in the preview component page? I need to do this so I can do some DOM manipulation of the page preview component on the app component page. Thanks.


答:
Sure, lets say you only want to target "submitted"

Simply do it like this:

```<code>#workflow > ul ::nth-child(2) {}
</code>```

See here. I made only "submitted" red text.

        div#workflow li {
            width: 5em;
            height: 5em;
            text-align: center;
            line-height: 5em;
            border-radius: 5em;
            background: dodgerblue;
            margin: 0 1.8em;
            display: inline-block;
            color: white;
            position: relative;
        }

        div#workflow li::before {
            content: '';
            position: absolute;
            top: 2.5em;
            left: -4em;
            width: 4em;
            height: .2em;
            background: dodgerblue;
            z-index: 1;
        }

        div#workflow li:first-child::before {
            display: none;
        }

        .active {
          background: dodgerblue;
        }

        .active ~ li {
          background: lightblue;
        }

        .active ~ li::before {
          background: lightblue;
        }

        #workflow > ul :nth-child(2) {
          color: red;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div id="workflow">
            <ul style="font-size:12px;">
              <li >Create</li>
              <li>Submitted</li>
              <li>In Process</li>
              <li class="active">Complete</li>
              <li>Closed</li>
            </ul>
        </div></code>```

Title: How to target child element in css within a div?

Body:
Sure, lets say you only want to target "submitted"

Simply do it like this:

#workflow > ul ::nth-child(2) {}

See here. I made only "submitted" red text.

        div#workflow li {
            width: 5em;
            height: 5em;
            text-align: center;
            line-height: 5em;
            border-radius: 5em;
            background: dodgerblue;
            margin: 0 1.8em;
            display: inline-block;
            color: white;
            position: relative;
        }

        div#workflow li::before {
            content: '';
            position: absolute;
            top: 2.5em;
            left: -4em;
            width: 4em;
            height: .2em;
            background: dodgerblue;
            z-index: 1;
        }

        div#workflow li:first-child::before {
            display: none;
        }

        .active {
          background: dodgerblue;
        }

        .active ~ li {
          background: lightblue;
        }

        .active ~ li::before {
          background: lightblue;
        }

        #workflow > ul :nth-child(2) {
          color: red;
        }

   <div id="workflow">
            <ul style="font-size:12px;">
              <li >Create</li>
              <li>Submitted</li>
              <li>In Process</li>
              <li class="active">Complete</li>
              <li>Closed</li>
            </ul>
        </div>


问:
How can I generate a random sample of bin counts given a sequence of bin probabilities?
I have a integer that needs to be split up in to bins according to a probability distribution. For example, if I had N=100 objects going into [0.02, 0.08, 0.16, 0.29, 0.45] then you might get [1, 10, 20, 25, 44].

```<code>import numpy as np
# sample distribution
d = np.array([x ** 2 for x in range(1,6)], dtype=float)
d = d / d.sum()
dcs = d.cumsum()
bins = np.zeros(d.shape)
N = 100
for roll in np.random.rand(N):
    # grab the first index that the roll satisfies
    i = np.where(roll < dcs)[0][0]
    bins[i] += 1
</code>```

In reality, N and my number of bins are very large, so looping isn't really a viable option. Is there any way I can vectorize this operation to speed it up?

答:
One more way to do this:

```<code>import numpy as np

p = [0.02, 0.08, 0.16, 0.29, 0.45]
np.bincount(np.random.choice(range(len(p)), size=100, p=p), minlength=len(p))
# array([ 1,  6, 16, 25, 52])
</code>```

It seems like allocating a length-100 array should be unnecessary but I haven't seen a way in numpy to avoid it.

Body:
I have a integer that needs to be split up in to bins according to a probability distribution. For example, if I had N=100 objects going into [0.02, 0.08, 0.16, 0.29, 0.45] then you might get [1, 10, 20, 25, 44].

import numpy as np
# sample distribution
d = np.array([x ** 2 for x in range(1,6)], dtype=float)
d = d / d.sum()
dcs = d.cumsum()
bins = np.zeros(d.shape)
N = 100
for roll in np.random.rand(N):
    # grab the first index that the roll satisfies
    i = np.where(roll < dcs)[0][0]
    bins[i] += 1

In reality, N and my number of bins are very large, so looping isn't really a viable option. Is there any way I can vectorize this operation to speed it up?

Body:
One more way to do this:

import numpy as np

p = [0.02, 0.08, 0.16, 0.29, 0.45]
np.bincount(np.random.choice(range(len(p)), size=100, p=p), minlength=len(p))
# array([ 1,  6, 16, 25, 52])

It seems like allocating a length-100 array should be unnecessary but I haven't seen a way in numpy to avoid it.


问:
Is there a better way to check if a number is range of two numbers
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

```<code>def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000
</code>```

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

答:
If there are many ranges your solution becomes very verbose. You may want to give this (simpler) code a try:

limits = (0, 5500, 9500, 14500, 19500, 24500, 29500, 34500, 39500, 44500)

def checkRange(number):
    for i, (low, high) in enumerate(zip(limits[:-1], limits[1:]), 1):
        if low <= number < high:
            return 5000*i
    return 0  # when the passed number is out of range
```

<p>It is worth pointing out that your logic has an off-by-one error, whereas in my implementation this issue is fixed.</p>

<p>Demo:</p>

```In [188]: checkRange(5499)
Out[188]: 5000

In [189]: checkRange(5500)
Out[189]: 10000

In [190]: checkRange(24872)
Out[190]: 30000
```

Body:
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

Body:
If there are many ranges your solution becomes very verbose. You may want to give this (simpler) code a try:

limits = (0, 5500, 9500, 14500, 19500, 24500, 29500, 34500, 39500, 44500)

def checkRange(number):
    for i, (low, high) in enumerate(zip(limits[:-1], limits[1:]), 1):
        if low <= number < high:
            return 5000*i
    return 0  # when the passed number is out of range

It is worth pointing out that your logic has an off-by-one error, whereas in my implementation this issue is fixed.

Demo:

In [188]: checkRange(5499)
Out[188]: 5000

In [189]: checkRange(5500)
Out[189]: 10000

In [190]: checkRange(24872)
Out[190]: 30000


问:
ValueError: Grouper for 'C' not 1-dimensional
Using this dataframe

```<code>df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two"],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large"],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                   "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
'''
     A    B      C  D  E
0  foo  one  small  1  2
1  foo  one  large  2  4
2  foo  one  large  2  5
3  foo  two  small  3  5
4  foo  two  small  3  6
5  bar  one  large  4  6
6  bar  one  small  5  8
7  bar  two  small  6  9
8  bar  two  large  7  9
'''
</code>```

When I run

```<code>print(pd.pivot_table(df, values='C', index=['A', 'B'],
                    columns=['C'], aggfunc='count'))
</code>```

To count the number of small/large according to columns A and B (say, for A,B=(foo,one) we have 1 small, and 2 large in column C)

it gives me error

```<code>ValueError: Grouper for 'C' not 1-dimensional
</code>```

What's the problem and how to resolve it?

答:
It sounds like what you're after is actually a groupby:

```<code>df.groupby(['A', 'B', 'C']).size()

A    B    C
bar  one  large    1
          small    1
     two  large    1
          small    1
foo  one  large    2
          small    1
     two  small    2
dtype: int64
</code>```

If you want to then place 'C' back in the columns, you can unstack:

```<code>df.groupby(['A', 'B', 'C']).size().unstack().fillna(0)

C        large  small
A   B
bar one    1.0    1.0
    two    1.0    1.0
foo one    2.0    1.0
    two    0.0    2.0
</code>```

Body:
Using this dataframe

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two"],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large"],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                   "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
'''
     A    B      C  D  E
0  foo  one  small  1  2
1  foo  one  large  2  4
2  foo  one  large  2  5
3  foo  two  small  3  5
4  foo  two  small  3  6
5  bar  one  large  4  6
6  bar  one  small  5  8
7  bar  two  small  6  9
8  bar  two  large  7  9
'''

When I run

print(pd.pivot_table(df, values='C', index=['A', 'B'],
                    columns=['C'], aggfunc='count'))

To count the number of small/large according to columns A and B (say, for A,B=(foo,one) we have 1 small, and 2 large in column C)

it gives me error

ValueError: Grouper for 'C' not 1-dimensional

What's the problem and how to resolve it?

Body:
It sounds like what you're after is actually a groupby:

df.groupby(['A', 'B', 'C']).size()

A    B    C
bar  one  large    1
          small    1
     two  large    1
          small    1
foo  one  large    2
          small    1
     two  small    2
dtype: int64

If you want to then place 'C' back in the columns, you can unstack:

df.groupby(['A', 'B', 'C']).size().unstack().fillna(0)

C        large  small
A   B
bar one    1.0    1.0
    two    1.0    1.0
foo one    2.0    1.0
    two    0.0    2.0


问:
ERROR: Could not build wheels for pendulum which use PEP 517 and cannot be installed directly
Please help. Tried most of the solutions I could find online, and as the last resort, posting it on stackoverflow.

The error I get while trying to install the Pendulum package is as below:

```<code>C:\WINDOWS\system32>pip install pendulum Collecting pendulum   Using cached pendulum-2.1.0.tar.gz (80 kB)   Installing build dependencies ... done   Getting requirements to build wheel ... done
    Preparing wheel metadata ... done Collecting pytzdata>=2018.3   Using cached pytzdata-2019.3-py2.py3-none-any.whl (489 kB) Requirement already satisfied: python-dateutil<3.0,>=2.6 in c:\python\python38-32\lib\site-packages (from pendulum) (2.8.1) Requirement already satisfied: six>=1.5 in c:\users\cuser\appdata\roaming\python\python38\site-packages (from python-dateutil<3.0,>=2.6->pendulum) (1.14.0) Building wheels for collected packages: pendulum   Building wheel for pendulum (PEP 517) ... error   ERROR: Command errored out with exit status 1:    command: 'c:\python\python38-32\python.exe' 'c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py' build_wheel 'C:\Users\cuser\AppData\Local\Temp\tmpkbrn91g9'
       cwd: C:\Users\cuser\AppData\Local\Temp\pip-install-q2vfs50o\pendulum   Complete output (24 lines):   Traceback (most recent call last):
    File "setup.py", line 2, in <module>
      from setuptools import setup   ModuleNotFoundError: No module named 'setuptools'   Traceback (most recent call last):
    File "c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 257, in <module>
      main()
    File "c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 240, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 181, in build_wheel
      return _build_backend().build_wheel(wheel_directory, config_settings,
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\api.py", line 57, in build_wheel
      return unicode(WheelBuilder.make_in(poetry, Path(wheel_directory)))
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 56, in make_in
      wb.build()
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 82, in build
      self._build(zip_file)
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 102, in _build
      self._run_build_command(setup)
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 130, in _run_build_command
      subprocess.check_call(
    File "c:\python\python38-32\lib\subprocess.py", line 364, in check_call
      raise CalledProcessError(retcode, cmd)   subprocess.CalledProcessError: Command '['c:\\python\\python38-32\\python.exe', 'setup.py', 'build', '-b', 'build']' returned non-zero exit status 1.
----------------------------------------   ERROR: Failed building wheel for pendulum Failed to build pendulum ERROR: Could not build wheels for pendulum which use PEP 517 and cannot be installed directly

The current python version and package versions are as below:

    Python 3.8.2

    Package           Version
    ----------------- -------
    astroid           2.3.3
    colorama          0.4.3
    cx-Oracle         7.3.0
    ez-setup          0.9
    isort             4.3.21
    lazy-object-proxy 1.4.3
    mccabe            0.6.1
    numpy             1.18.2
    pandas            1.0.3
    pip               20.0.2
    pylint            2.4.4
    python-dateutil   2.8.1
    pytz              2019.3
    setuptools        46.1.3
    six               1.14.0
    SQLAlchemy        1.3.15
    wheel             0.34.2
    wrapt             1.11.2

OS version:

    OS Name:                   Microsoft Windows 10 Enterprise
    OS Version:                10.0.17763 N/A Build 17763
</code>```

答:
Downgrade to pip version 18.1 then install pendulum

pip install pip==18.1 && pip install pendulum
```

Body:
Please help. Tried most of the solutions I could find online, and as the last resort, posting it on stackoverflow.

The error I get while trying to install the Pendulum package is as below:

C:\WINDOWS\system32>pip install pendulum Collecting pendulum   Using cached pendulum-2.1.0.tar.gz (80 kB)   Installing build dependencies ... done   Getting requirements to build wheel ... done
    Preparing wheel metadata ... done Collecting pytzdata>=2018.3   Using cached pytzdata-2019.3-py2.py3-none-any.whl (489 kB) Requirement already satisfied: python-dateutil<3.0,>=2.6 in c:\python\python38-32\lib\site-packages (from pendulum) (2.8.1) Requirement already satisfied: six>=1.5 in c:\users\cuser\appdata\roaming\python\python38\site-packages (from python-dateutil<3.0,>=2.6->pendulum) (1.14.0) Building wheels for collected packages: pendulum   Building wheel for pendulum (PEP 517) ... error   ERROR: Command errored out with exit status 1:    command: 'c:\python\python38-32\python.exe' 'c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py' build_wheel 'C:\Users\cuser\AppData\Local\Temp\tmpkbrn91g9'
       cwd: C:\Users\cuser\AppData\Local\Temp\pip-install-q2vfs50o\pendulum   Complete output (24 lines):   Traceback (most recent call last):
    File "setup.py", line 2, in <module>
      from setuptools import setup   ModuleNotFoundError: No module named 'setuptools'   Traceback (most recent call last):
    File "c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 257, in <module>
      main()
    File "c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 240, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "c:\python\python38-32\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 181, in build_wheel
      return _build_backend().build_wheel(wheel_directory, config_settings,
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\api.py", line 57, in build_wheel
      return unicode(WheelBuilder.make_in(poetry, Path(wheel_directory)))
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 56, in make_in
      wb.build()
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 82, in build
      self._build(zip_file)
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 102, in _build
      self._run_build_command(setup)
    File "C:\Users\cuser\AppData\Local\Temp\pip-build-env-nvwxlarh\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 130, in _run_build_command
      subprocess.check_call(
    File "c:\python\python38-32\lib\subprocess.py", line 364, in check_call
      raise CalledProcessError(retcode, cmd)   subprocess.CalledProcessError: Command '['c:\\python\\python38-32\\python.exe', 'setup.py', 'build', '-b', 'build']' returned non-zero exit status 1.
----------------------------------------   ERROR: Failed building wheel for pendulum Failed to build pendulum ERROR: Could not build wheels for pendulum which use PEP 517 and cannot be installed directly

The current python version and package versions are as below:

    Python 3.8.2

    Package           Version
    ----------------- -------
    astroid           2.3.3
    colorama          0.4.3
    cx-Oracle         7.3.0
    ez-setup          0.9
    isort             4.3.21
    lazy-object-proxy 1.4.3
    mccabe            0.6.1
    numpy             1.18.2
    pandas            1.0.3
    pip               20.0.2
    pylint            2.4.4
    python-dateutil   2.8.1
    pytz              2019.3
    setuptools        46.1.3
    six               1.14.0
    SQLAlchemy        1.3.15
    wheel             0.34.2
    wrapt             1.11.2

OS version:

    OS Name:                   Microsoft Windows 10 Enterprise
    OS Version:                10.0.17763 N/A Build 17763


答:
```<code>#workflow li {
      #your normal style
    }

#workflow li.active {
      #your active style
    }
</code>```


问:
How can I define a function in django so that stays active in background?
How can I define a function that stays active in the background?

For example, I want to press a button in the admin panel and then, Django starts updating all of the movies in the database using IMDB information.

If there are too many movies in the database, It can take too long for Django to update them. So I want the process of updating to stay active in the background and don't stop if I close the web browser.

1) How is this possible?

2) Can I add a progress bar to see how many movies are updated so far?

答:
```<code>First Way:- You can start a thread on the click of button

import threading

# define your function to start updating the data through thread

def update_data(data):
    ....
    ....

# On the click of button, start thread

try:
    your_thread = threading.Thread(
        target=update_data,
        args=(data)
    )
    your_thread.start()
except Exception as ex:
    print("The exception is {}".format(ex))

Second Way:- You can configure celery and start celery task on the click of button

1. Install Celery

pip install Celery

2. Installing RabbitMQ

apt-get install -y erlang

apt-get install rabbitmq-server

3. Enable and start the RabbitMQ service

systemctl enable rabbitmq-server

systemctl start rabbitmq-server

4. Check the status of rabbitmq server

systemctl status rabbitmq-server

5. Add the CELERY_BROKER_URL configuration to the settings.py file

settings.py

CELERY_BROKER_URL = 'amqp://localhost'

6. Alongside with the settings.py and urls.py files, Create a new file named celery.py

celery.py

import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname,.settings')

app = Celery('projectname')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

7. Edit the __init__.py file in the project root

__init__.py

from .celery import app as celery_app
__all__ = ['celery_app']
8. create tasks.py inside any django app

tasks.py

import string

from django.contrib.auth.models import User
from django.utils.crypto import get_random_string

from celery import shared_task

@shared_task
def create_random_user_accounts(total):
    for i in range(total):
        username = 'user_{}'.format(get_random_string(10, string.ascii_letters))
        email = '{}@abc.com'.format(username)
        password = get_random_string(50)
        User.objects.create_user(username=username, email=email, password=password)
    return '{} random users created with success!'.format(total)
9. create forms.py inside that app

forms.py

from django import forms
from django.core.validators import MinValueValidator, MaxValueValidator

class GenerateRandomUserForm(forms.Form):
    total = forms.IntegerField(
        validators=[
            MinValueValidator(50),
            MaxValueValidator(500)
        ]
    )
10. Views in the same app

views.py

from django.contrib.auth.models import User
from django.contrib import messages
from django.views.generic.edit import FormView
from django.shortcuts import redirect

from .forms import GenerateRandomUserForm
from .tasks import create_random_user_accounts

class GenerateRandomUserView(FormView):
    template_name = 'generate_random_users.html'
    form_class = GenerateRandomUserForm

    def form_valid(self, form):
        total = form.cleaned_data.get('total')
        create_random_user_accounts.delay(total)
        messages.success(self.request, 'We are generating your random users! Wait a moment and refresh this page.')
        return redirect('users_list')
11. now in the template

generate_random_users.html

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type=submit value="Submit" />
</form>

{% if messages %}
    {% for message in messages %}
        {{ message }}
    {% endfor %}
{% endif %}
12. start the work process

celery -A projectname worker -l info
</code>```


问:
C pointer to array/array of pointers disambiguation
What is the difference between the following declarations:

```<code>int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
</code>```

What is the general rule for understanding more complex declarations?

答:
```<code>int *arr1[5]
</code>```

In this declaration, arr1 is an array of 5 pointers to integers.
Reason: Square brackets have higher precedence over * (dereferncing operator).
And in this type, number of rows are fixed (5 here), but number of columns is variable.

```<code>int (*arr2)[5]
</code>```

In this declaration, arr2 is a pointer to an integer array of 5 elements.
Reason: Here, () brackets have higher precedence than [].
And in this type, number of rows is variable, but the number of columns is fixed (5 here).

ContentLicense: CC BY-SA 2.5

Body:
What is the difference between the following declarations:

int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);

What is the general rule for understanding more complex declarations?

Body:
int *arr1[5]

In this declaration, arr1 is an array of 5 pointers to integers.
Reason: Square brackets have higher precedence over * (dereferncing operator).
And in this type, number of rows are fixed (5 here), but number of columns is variable.

int (*arr2)[5]

In this declaration, arr2 is a pointer to an integer array of 5 elements.
Reason: Here, () brackets have higher precedence than [].
And in this type, number of rows is variable, but the number of columns is fixed (5 here).


答:
The below selector will work:</p>

```<code>div#workflow > ul > li.active {
  /* Styling */
}
</code>```

Body:
I have a
 parent element with the id="workflow". For the .active styling, may I know how to target the li element within it in the html? I have no issue with the first few blocks of the css with div#workflow.

        div#workflow li {
            width: 5em;
            height: 5em;
            text-align: center;
            line-height: 5em;
            border-radius: 5em;
            background: dodgerblue;
            margin: 0 1.8em;
            display: inline-block;
            color: white;
            position: relative;
        }

        div#workflow li::before {
            content: '';
            position: absolute;
            top: 2.5em;
            left: -4em;
            width: 4em;
            height: .2em;
            background: dodgerblue;
            z-index: 1;
        }

        div#workflow li:first-child::before {
            display: none;
        }

        .active {
          background: dodgerblue;
        }

        .active ~ li {
          background: lightblue;
        }

        .active ~ li::before {
          background: lightblue;
        }

Create

Submitted

In Process

Complete

Closed

Body:
The below selector will work:

div#workflow > ul > li.active {
  /* Styling */
}


问:
Class inheriting from several Interfaces having same method signature
1) How to solve this problem in Java?

2) What if only the return types are different in the interfaces?

答:
1) How to solve this problem in Java?

Essentially, the different "versions" of the method in the respective interfaces all bind to the same implementation method.

If that's what you want, fine.

If you actually want a different version of the method for each interface then you are stuck.  You can't do that in Java.

2) What if only the return types are different in the interfaces?

If the return types are incompatible, you cannot write a class that implements all of the interfaces.  Compilation error.

So when are return types compatible?

Prior to Java 5.0, the return type of an overriding or implementing method had to be the same as the return of the overridden or implemented method.

In Java 5.0, the language was modified to allow you to override / implement a method with a return type that is a subclass of the return type of the overridden / implemented method.

So ... if you are using Java 5.0 or later ... you need to implement using a return type that is the same type or a subclass of all of the return types of all versions of the method.  If there is no such type, then the class is not implementable.  And obviously, this doesn't work for primitive return types, because no subclass relationship exists between primitive types.

(Note: in Java 5.0 +, we are talking about a subclass relationship between the declared return types ... not the runtime types of the returned objects.)


问:
How to clone github private repository in cpanel (shared host without terminal or ssh)?
I have a shared host and they don't give me ssh or terminal for it.
I've tried to clone my private repos from git by Git™ Version Control so I am using ssh link because they need permission. I don't know how to make ssh key on cpanel so I can make it from my mac and upload to cpanel and also add to Github.

But when running, they give me error: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists..

I'm a beginner for using Git & StackOverflow, so please let me know if there's anything wrong with the question I've asked. Thanks!

Tried Url with password
Cloning a private Github repo and
having a response "The clone URL cannot include a password."

答:
This is different than what worked for the OP (hopefully they put their solution in an answer here).

I was able to solve this problem by installing an external SSH client (like PuTTY for Windows) and then SSH into my website using its IP address. Then I followed these steps from cPanel to connect the private repository.


问:
Rails routing for multiple domains
I want to use one rails application to serve multiple sites.

Sites have approximately the same functionality, but I have different url paths.

Is it possible to register different routes for different domains in rails?

Now my application is on php and I connected routing like this

```<code>if ($domain == 'domain1.com') {
    include_once 'domain1.com_router.php';
} elseif ($domain == 'domain2.com') {
    include_once 'domain2.com_router.php';
}
</code>```

答:
You should be able to use constraint blocks for this

```<code>constraints domain: 'domain1.com' do
  ...
end

constraints domain: 'domain2.com' do
  ...
end
</code>```

You can also apply constraints to individual routes like so

```<code>root :to => "static#home", :constraints => { :domain => "domain1.com" }
</code>```

Title: Rails routing for multiple domains

Body:
I want to use one rails application to serve multiple sites.

Sites have approximately the same functionality, but I have different url paths.

Is it possible to register different routes for different domains in rails?

Now my application is on php and I connected routing like this

if ($domain == 'domain1.com') {
    include_once 'domain1.com_router.php';
} elseif ($domain == 'domain2.com') {
    include_once 'domain2.com_router.php';
}

Body:
You should be able to use constraint blocks for this

constraints domain: 'domain1.com' do
  ...
end

constraints domain: 'domain2.com' do
  ...
end

You can also apply constraints to individual routes like so

root :to => "static#home", :constraints => { :domain => "domain1.com" }


答:
You can not have C column as both values and columns.
Probably you should change to:

```<code>print(pd.pivot_table(df, index=['A', 'B'], columns=['C'], aggfunc='count'))
</code>```

Then the result is:

```<code>            D           E
C       large small large small
A   B
bar one   1.0   1.0   1.0   1.0
    two   1.0   1.0   1.0   1.0
foo one   2.0   1.0   2.0   1.0
    two   NaN   2.0   NaN   2.0
</code>```

Title: ValueError: Grouper for 'C' not 1-dimensional

Body:
You can not have C column as both values and columns.
Probably you should change to:

print(pd.pivot_table(df, index=['A', 'B'], columns=['C'], aggfunc='count'))

Then the result is:

            D           E
C       large small large small
A   B
bar one   1.0   1.0   1.0   1.0
    two   1.0   1.0   1.0   1.0
foo one   2.0   1.0   2.0   1.0
    two   NaN   2.0   NaN   2.0