问:
Set expand_alias when shopt not available?
I'm trying to use an alias in a shell script I'm writing, but it is not working.

The alias:

```<code>alias ts="awk '{ print strftime(\"[%Y-%m-%d %H:%M:%S]\"), \$0 }'"
</code>```

When I run the script, I get the following error:

```<code>./copyTask.sh: ts: not found
</code>```

Sooping around on the internet, it seems that I need to enable the expand_aliases shell option, but I don't have shopt installed... Is there any way I can enable alias expansion without using shopt or creating another rootfs image?

I'm using the ash shell. And awk is BusyBox v1.25.0 awk.

NOTE: The alias is an easy way to prepend a timestamp to a commmand:

```<code>$ echo "foo" | ts
[2005-06-23 11:52:32] foo
</code>```

EDIT: as some people are having trouble understanding what I mean, this answer  has an example.

答:
Don't use aliases in scripts. A function does the same job better.

```<code>ts() { gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }' "$@"; }
</code>```

This works with any POSIX shell, including ones that don't support aliases at all.

This works with noninteractive shells without needing to enable alias support explicitly.

This can be extended in ways that aliases can't (you can put conditional logic inside functions; you can put arguments in non-tail positions in functions; etc).

In bash, functions can be exported to the environment: export -f ts will make the ts command available to subprocesses (where the shell they run is also bash).

Body:
I'm trying to use an alias in a shell script I'm writing, but it is not working.

The alias:

alias ts="awk '{ print strftime(\"[%Y-%m-%d %H:%M:%S]\"), \$0 }'"

When I run the script, I get the following error:

./copyTask.sh: ts: not found

Sooping around on the internet, it seems that I need to enable the expand_aliases shell option, but I don't have shopt installed... Is there any way I can enable alias expansion without using shopt or creating another rootfs image?

I'm using the ash shell. And awk is BusyBox v1.25.0 awk.

NOTE: The alias is an easy way to prepend a timestamp to a commmand:

$ echo "foo" | ts
[2005-06-23 11:52:32] foo

EDIT: as some people are having trouble understanding what I mean, this answer  has an example.

Body:
Don't use aliases in scripts. A function does the same job better.

ts() { gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }' "$@"; }

This works with any POSIX shell, including ones that don't support aliases at all.

This works with noninteractive shells without needing to enable alias support explicitly.

This can be extended in ways that aliases can't (you can put conditional logic inside functions; you can put arguments in non-tail positions in functions; etc).

In bash, functions can be exported to the environment: export -f ts will make the ts command available to subprocesses (where the shell they run is also bash).


来源: stackexchange

问:
How to save the screenshot in particular folder using python
I have written the below script for taking a screenshot. Currently, it saves the file in the same directory as the python file is located. I want to save the screenshot in a particular folder.</p>

```<code>from selenium import webdriver
import option
import time

#PhantomJS
driver = webdriver.PhantomJS(executable_path=r'D:\PhantomJS\phantomjs-2.1.1-
windows\bin\phantomjs.exe')

#Selenium
#driver = webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe")

#Maximizes window to full screen
driver.maximize_window()

#Gets the URL for OMS
driver.get(option.OMS_QUERY)

#Gets the username & Password
driver.find_element_by_xpath(option.LOG_IN).click()
driver.find_element_by_id("username").send_keys(option.USERNAME)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(3)
driver.find_element_by_id("password").send_keys(option.PASSWORD)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(15)

#Saves the screenshot for OMS_SWR
driver.save_screenshot('oms_swr.png')

#Gets the URL for DMS
driver.get(option.DMS_QUERY)
time.sleep(15)

#Saves the screenshot for DMS_SWR
driver.save_screenshot('dms_swr.png')
driver.quit()
</code>```

答:
To save the screenshot in a particular folder you can use either of the following options :

Within your Project space :

```<code>driver.save_screenshot('./project_directory/save_screenshot.png')
</code>```

Within your System :

```<code>driver.save_screenshot('C:/system_directory/save_screenshot.png')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have written the below script for taking a screenshot. Currently, it saves the file in the same directory as the python file is located. I want to save the screenshot in a particular folder.

from selenium import webdriver
import option
import time

#PhantomJS
driver = webdriver.PhantomJS(executable_path=r'D:\PhantomJS\phantomjs-2.1.1-
windows\bin\phantomjs.exe')

#Selenium
#driver = webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe")

#Maximizes window to full screen
driver.maximize_window()

#Gets the URL for OMS
driver.get(option.OMS_QUERY)

#Gets the username & Password
driver.find_element_by_xpath(option.LOG_IN).click()
driver.find_element_by_id("username").send_keys(option.USERNAME)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(3)
driver.find_element_by_id("password").send_keys(option.PASSWORD)
driver.find_element_by_xpath(option.ENTER).click()
time.sleep(15)

#Saves the screenshot for OMS_SWR
driver.save_screenshot('oms_swr.png')

#Gets the URL for DMS
driver.get(option.DMS_QUERY)
time.sleep(15)

#Saves the screenshot for DMS_SWR
driver.save_screenshot('dms_swr.png')
driver.quit()

Body:
To save the screenshot in a particular folder you can use either of the following options :

Within your Project space :

driver.save_screenshot('./project_directory/save_screenshot.png')

Within your System :

driver.save_screenshot('C:/system_directory/save_screenshot.png')


问:
Why QMYSQL driver not loaded in QT5.2?
My program is write with QT5.2 and use mysql. I heared that QT5.2 contains MYSQL driver already. However, when I compile and run my program, it is compiled successfully but runned failed with error:

```<code>   QSqlDatabase: QMYSQL driver not loaded
   QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7
</code>```

My programe is like this:

```<code>     QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
     db.setHostName("localhost");
     db.setDatabaseName("tradingsystem");
     db.setUserName("root");
     db.setPassword("");
     if(!db.open())
     {
          //.....;
     }
</code>```

And in .pro I add this:

```<code>    QT += sql
</code>```

Mysql is provided by XAMPP.My OS is win7-x64-sp1-ultimate, and XAMPP Version 1.8.2.System Path is as follow:

```<code>    C:\Program Files (x86)\SepanderSoft;
    C:\Program Files (x86)\Intel\iCLS Client\;
    C:\Program Files\Intel\iCLS Client\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;
    C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;
    C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;
    C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;
    C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;
    C:\Program Files\Intel\WiFi\bin\;
    C:\Program Files\Common Files\Intel\WirelessCommon\;
    C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x86;
    C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x64;
    C:\Program Files\Microsoft\Web Platform Installer\;
    C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;
    C:\Program Files (x86)\Windows Kits\8.0\Windows Performance Toolkit\;
    C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;
    D:\Software\MySQL\MySQL Enterprise Backup 3.8.2\
</code>```

XAMPP location is :

```<code>    D:\XAMPP
</code>```

QT location is:

```<code>    D:\Software\Qt
</code>```

I have installed mysql server-5.6-64bit in D:\Software\MySQL, and when it conflicted with mysql in XAMPP, I uninstalled mysql server-5.6-64bit.

答:
Adding post due to reputation deficit.

I was able to resolve my issue using a combination of Hồ Sĩ Sơn, Ram, and Sumanth's posts (Thank you both).

Here are my exact steps:

Checked the version of Qt Creator that I am running by visiting Help -> About Qt Creator.
I found that I am running the 32-bit version.

Now that I know what version I am running I navigated to the 32-bit version of the MySQL connector.
This was found in C:\Program Files (x86)\MySQL\MySQL Connector C 6.1\lib.

I copied the libmysql.dll file found in that folder, and pasted it into C:\Qt\5.9.2\mingw53_32\bin\ since I am compiling with MinGW.
Note that this is the 32-bit folder.

Restarted Qt Creator and rebuilt my project.

The steps that were challenging me were matching the x-bit version of Qt Creator, my compiler, and the driver, then restarting Qt Creator.

Hope this helps someone out there!

Title: Why QMYSQL driver not loaded in QT5.2?

Body:
My program is write with QT5.2 and use mysql. I heared that QT5.2 contains MYSQL driver already. However, when I compile and run my program, it is compiled successfully but runned failed with error:

   QSqlDatabase: QMYSQL driver not loaded
   QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7

My programe is like this:

     QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
     db.setHostName("localhost");
     db.setDatabaseName("tradingsystem");
     db.setUserName("root");
     db.setPassword("");
     if(!db.open())
     {
          //.....;
     }

And in .pro I add this:

    QT += sql

Mysql is provided by XAMPP.My OS is win7-x64-sp1-ultimate, and XAMPP Version 1.8.2.System Path is as follow:

    C:\Program Files (x86)\SepanderSoft;
    C:\Program Files (x86)\Intel\iCLS Client\;
    C:\Program Files\Intel\iCLS Client\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;
    C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;
    C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;
    C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;
    C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;
    C:\Program Files\Intel\WiFi\bin\;
    C:\Program Files\Common Files\Intel\WirelessCommon\;
    C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x86;
    C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x64;
    C:\Program Files\Microsoft\Web Platform Installer\;
    C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;
    C:\Program Files (x86)\Windows Kits\8.0\Windows Performance Toolkit\;
    C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;
    D:\Software\MySQL\MySQL Enterprise Backup 3.8.2\

XAMPP location is :

    D:\XAMPP

QT location is:

    D:\Software\Qt

I have installed mysql server-5.6-64bit in D:\Software\MySQL, and when it conflicted with mysql in XAMPP, I uninstalled mysql server-5.6-64bit.


问:
How can I change a background below date part and an icon of datepicker button?
Here is how it looks right now:

What I've tried here is to edit templates, on date and template on button also, and I get this code after I followed next steps:

Right click on DatePicker -> Edit Template -> Edit a copy

But I don't know where and what I should change to change an default icon and default background below date part...

```<code>

        <ControlTemplate x:Key="MyButtonTemplateDatePicker" TargetType="{x:Type Button}">
            <Grid>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CommonStates">
                        <VisualStateGroup.Transitions>
                            <VisualTransition GeneratedDuration="0"/>
                            <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                            <VisualTransition GeneratedDuration="0:0:0.1" To="Pressed"/>
                        </VisualStateGroup.Transitions>
                        <VisualState x:Name="Normal"/>
                        <VisualState x:Name="MouseOver">
                            <Storyboard>
                                <ColorAnimation Duration="0" To="#FF448DCA" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Background"/>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#7FFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#CCFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#F2FFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="Pressed">
                            <Storyboard>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Background">
                                    <SplineColorKeyFrame KeyTime="0" Value="#FF448DCA"/>
                                </ColorAnimationUsingKeyFrames>
                                <DoubleAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Highlight">
                                    <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                </DoubleAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#EAFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#C6FFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#6BFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[0].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#F4FFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="Disabled"/>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
                <Grid Background="#11FFFFFF" FlowDirection="LeftToRight" HorizontalAlignment="Center" Height="18" Margin="0" VerticalAlignment="Center" Width="19">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="20*"/>
                        <ColumnDefinition Width="20*"/>
                        <ColumnDefinition Width="20*"/>
                        <ColumnDefinition Width="20*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="23*"/>
                        <RowDefinition Height="19*"/>
                        <RowDefinition Height="19*"/>
                        <RowDefinition Height="19*"/>
                    </Grid.RowDefinitions>
                    <Border x:Name="Highlight" BorderBrush="#FF45D6FA" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius="0,0,1,1" Margin="-1" Opacity="0" Grid.Row="0" Grid.RowSpan="4"/>
                    <Border x:Name="Background" BorderBrush="#FFFFFFFF" BorderThickness="1" Background="#FF1F3B53" Grid.ColumnSpan="4" CornerRadius=".5" Margin="0,-1,0,0" Opacity="1" Grid.Row="1" Grid.RowSpan="3"/>
                    <Border x:Name="BackgroundGradient" BorderBrush="#BF000000" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius=".5" Margin="0,-1,0,0" Opacity="1" Grid.Row="1" Grid.RowSpan="3">
                        <Border.Background>
                            <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0">
                                <GradientStop Color="#FFFFFFFF" Offset="0"/>
                                <GradientStop Color="#F9FFFFFF" Offset="0.375"/>
                                <GradientStop Color="#E5FFFFFF" Offset="0.625"/>
                                <GradientStop Color="#C6FFFFFF" Offset="1"/>
                            </LinearGradientBrush>
                        </Border.Background>
                    </Border>
                    <Rectangle Grid.ColumnSpan="4" Grid.RowSpan="1" StrokeThickness="1">
                        <Rectangle.Fill>
                            <LinearGradientBrush EndPoint="0.3,-1.1" StartPoint="0.46,1.6">
                                <GradientStop Color="#FF4084BD"/>
                                <GradientStop Color="#FFAFCFEA" Offset="1"/>
                            </LinearGradientBrush>
                        </Rectangle.Fill>
                        <Rectangle.Stroke>
                            <LinearGradientBrush EndPoint="0.48,-1" StartPoint="0.48,1.25">
                                <GradientStop Color="#FF494949"/>
                                <GradientStop Color="#FF9F9F9F" Offset="1"/>
                            </LinearGradientBrush>
                        </Rectangle.Stroke>
                    </Rectangle>
                    <Path Grid.ColumnSpan="4" Grid.Column="0" Data="M11.426758,8.4305077 L11.749023,8.4305077 L11.749023,16.331387 L10.674805,16.331387 L10.674805,10.299648 L9.0742188,11.298672 L9.0742188,10.294277 C9.4788408,10.090176 9.9094238,9.8090878 10.365967,9.4510155 C10.82251,9.0929432 11.176106,8.7527733 11.426758,8.4305077 z M14.65086,8.4305077 L18.566387,8.4305077 L18.566387,9.3435936 L15.671368,9.3435936 L15.671368,11.255703 C15.936341,11.058764 16.27293,10.960293 16.681133,10.960293 C17.411602,10.960293 17.969301,11.178717 18.354229,11.615566 C18.739157,12.052416 18.931622,12.673672 18.931622,13.479336 C18.931622,15.452317 18.052553,16.438808 16.294415,16.438808 C15.560365,16.438808 14.951641,16.234707 14.468243,15.826504 L14.881817,14.929531 C15.368796,15.326992 15.837872,15.525723 16.289043,15.525723 C17.298809,15.525723 17.803692,14.895514 17.803692,13.635098 C17.803692,12.460618 17.305971,11.873379 16.310528,11.873379 C15.83071,11.873379 15.399232,12.079271 15.016094,12.491055 L14.65086,12.238613 z" Fill="#FF2F2F2F" HorizontalAlignment="Center" Margin="4,3,4,3" Grid.Row="1" Grid.RowSpan="3" RenderTransformOrigin="0.5,0.5" Stretch="Fill" VerticalAlignment="Center"/>
                    <Ellipse Grid.ColumnSpan="4" Fill="#FFFFFFFF" HorizontalAlignment="Center" Height="3" StrokeThickness="0" VerticalAlignment="Center" Width="3"/>
                    <Border x:Name="DisabledVisual" BorderBrush="#B2FFFFFF" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius="0,0,.5,.5" Opacity="0" Grid.Row="0" Grid.RowSpan="4"/>
                </Grid>
            </Grid>
        </ControlTemplate>
</code>```

Thanks guys and cheers!

答:
The calendar icon is defined in the "MyButtonTemplateDatePicker" ControlTemplate. It's made up by a bunch of Border elements, a Rectangle and a Path.

You change the icon by modifying this template. You may for example replace the Path with your own custom one. Of course this requires you to actually define an Path that displays your custom icon.

Body:
Here is how it looks right now:

What I've tried here is to edit templates, on date and template on button also, and I get this code after I followed next steps:

Right click on DatePicker -> Edit Template -> Edit a copy

But I don't know where and what I should change to change an default icon and default background below date part...

        <ControlTemplate x:Key="MyButtonTemplateDatePicker" TargetType="{x:Type Button}">
            <Grid>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CommonStates">
                        <VisualStateGroup.Transitions>
                            <VisualTransition GeneratedDuration="0"/>
                            <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                            <VisualTransition GeneratedDuration="0:0:0.1" To="Pressed"/>
                        </VisualStateGroup.Transitions>
                        <VisualState x:Name="Normal"/>
                        <VisualState x:Name="MouseOver">
                            <Storyboard>
                                <ColorAnimation Duration="0" To="#FF448DCA" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Background"/>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#7FFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#CCFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#F2FFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="Pressed">
                            <Storyboard>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Background">
                                    <SplineColorKeyFrame KeyTime="0" Value="#FF448DCA"/>
                                </ColorAnimationUsingKeyFrames>
                                <DoubleAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Highlight">
                                    <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                </DoubleAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#EAFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#C6FFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#6BFFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                                <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[0].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient">
                                    <SplineColorKeyFrame KeyTime="0" Value="#F4FFFFFF"/>
                                </ColorAnimationUsingKeyFrames>
                            </Storyboard>
                        </VisualState>
                        <VisualState x:Name="Disabled"/>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
                <Grid Background="#11FFFFFF" FlowDirection="LeftToRight" HorizontalAlignment="Center" Height="18" Margin="0" VerticalAlignment="Center" Width="19">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="20*"/>
                        <ColumnDefinition Width="20*"/>
                        <ColumnDefinition Width="20*"/>
                        <ColumnDefinition Width="20*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="23*"/>
                        <RowDefinition Height="19*"/>
                        <RowDefinition Height="19*"/>
                        <RowDefinition Height="19*"/>
                    </Grid.RowDefinitions>
                    <Border x:Name="Highlight" BorderBrush="#FF45D6FA" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius="0,0,1,1" Margin="-1" Opacity="0" Grid.Row="0" Grid.RowSpan="4"/>
                    <Border x:Name="Background" BorderBrush="#FFFFFFFF" BorderThickness="1" Background="#FF1F3B53" Grid.ColumnSpan="4" CornerRadius=".5" Margin="0,-1,0,0" Opacity="1" Grid.Row="1" Grid.RowSpan="3"/>
                    <Border x:Name="BackgroundGradient" BorderBrush="#BF000000" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius=".5" Margin="0,-1,0,0" Opacity="1" Grid.Row="1" Grid.RowSpan="3">
                        <Border.Background>
                            <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0">
                                <GradientStop Color="#FFFFFFFF" Offset="0"/>
                                <GradientStop Color="#F9FFFFFF" Offset="0.375"/>
                                <GradientStop Color="#E5FFFFFF" Offset="0.625"/>
                                <GradientStop Color="#C6FFFFFF" Offset="1"/>
                            </LinearGradientBrush>
                        </Border.Background>
                    </Border>
                    <Rectangle Grid.ColumnSpan="4" Grid.RowSpan="1" StrokeThickness="1">
                        <Rectangle.Fill>
                            <LinearGradientBrush EndPoint="0.3,-1.1" StartPoint="0.46,1.6">
                                <GradientStop Color="#FF4084BD"/>
                                <GradientStop Color="#FFAFCFEA" Offset="1"/>
                            </LinearGradientBrush>
                        </Rectangle.Fill>
                        <Rectangle.Stroke>
                            <LinearGradientBrush EndPoint="0.48,-1" StartPoint="0.48,1.25">
                                <GradientStop Color="#FF494949"/>
                                <GradientStop Color="#FF9F9F9F" Offset="1"/>
                            </LinearGradientBrush>
                        </Rectangle.Stroke>
                    </Rectangle>
                    <Path Grid.ColumnSpan="4" Grid.Column="0" Data="M11.426758,8.4305077 L11.749023,8.4305077 L11.749023,16.331387 L10.674805,16.331387 L10.674805,10.299648 L9.0742188,11.298672 L9.0742188,10.294277 C9.4788408,10.090176 9.9094238,9.8090878 10.365967,9.4510155 C10.82251,9.0929432 11.176106,8.7527733 11.426758,8.4305077 z M14.65086,8.4305077 L18.566387,8.4305077 L18.566387,9.3435936 L15.671368,9.3435936 L15.671368,11.255703 C15.936341,11.058764 16.27293,10.960293 16.681133,10.960293 C17.411602,10.960293 17.969301,11.178717 18.354229,11.615566 C18.739157,12.052416 18.931622,12.673672 18.931622,13.479336 C18.931622,15.452317 18.052553,16.438808 16.294415,16.438808 C15.560365,16.438808 14.951641,16.234707 14.468243,15.826504 L14.881817,14.929531 C15.368796,15.326992 15.837872,15.525723 16.289043,15.525723 C17.298809,15.525723 17.803692,14.895514 17.803692,13.635098 C17.803692,12.460618 17.305971,11.873379 16.310528,11.873379 C15.83071,11.873379 15.399232,12.079271 15.016094,12.491055 L14.65086,12.238613 z" Fill="#FF2F2F2F" HorizontalAlignment="Center" Margin="4,3,4,3" Grid.Row="1" Grid.RowSpan="3" RenderTransformOrigin="0.5,0.5" Stretch="Fill" VerticalAlignment="Center"/>
                    <Ellipse Grid.ColumnSpan="4" Fill="#FFFFFFFF" HorizontalAlignment="Center" Height="3" StrokeThickness="0" VerticalAlignment="Center" Width="3"/>
                    <Border x:Name="DisabledVisual" BorderBrush="#B2FFFFFF" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius="0,0,.5,.5" Opacity="0" Grid.Row="0" Grid.RowSpan="4"/>
                </Grid>
            </Grid>
        </ControlTemplate>

Thanks guys and cheers!


问:
Response code 500 in JMeter when running with threads
Getting the following error in JMeter while running the list of APIs (with no of threads:1-140 with ramp up period-1).

```<code>Response code:500
Response message: Internal Server Error
</code>```

How should I overcome this Error Response code in order to get the accurate response?
What should do to decrease amount of response with this response code?

答:
In general a 500 is an unhandled response on the part of a developer.  Usually on the backend but also on the performance testing tool front end.

Ask yourself, are you validating responses that come back from the server for appropriate content?  I am not just suggesting an HTTP200 is valid.  You need to check response content to ensure that it is what you expect is valid for the business process, for you can have a completely valid HTTP200 class page which contains a response which will send your business process off the rails.  If you do not handle the exception on the part of the unexpected response then you will find that one to two steps down the road in the business process then you are pretty much guaranteed that you will find a 500 as your request is completely out of context with the state of the application at that point.

Test101, for every step there is an expected and positive result which allows the business process to continue.  Check for that result and branch your code when you do not find that the result is true.

Or, if this is a single step business process then you are likely handing the service poor data and the developer has not fully fleshed out the graceful part of dealing with your poor data.

Body:
Getting the following error in JMeter while running the list of APIs (with no of threads:1-140 with ramp up period-1).

Response code:500
Response message: Internal Server Error

How should I overcome this Error Response code in order to get the accurate response?
What should do to decrease amount of response with this response code?


问:
Order of request.getParameterNames()
How do I get all the parameterNames in an HTML form in
the same sequence?

Example:

If the form contains FirstName, LastNameand Age

The output should appear exatcly in the same sequence

I have tried using the following but this shifts the
order of the output:

```<code>Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
    String paramName = (String) paramNames.nextElement();
    out.print(paramName);
}
</code>```

答:
request.getParameterNames () uses HashMap  internally to store the  name value pairs of form fields. There is no order maintained in this. if you need this in order then , some sort of naming convention for form parameters to control the order of retrieval.

```<code>SortedSet temp = new SortedSet();
Enumeration enumeration = request.getParameterNames();
while (enumeration.hasMoreElements())
{
        temp.add((String)enumeration.nextElement());
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Order of request.getParameterNames()

Body:
How do I get all the parameterNames in an HTML form in
the same sequence?

Example:

If the form contains FirstName, LastNameand Age

The output should appear exatcly in the same sequence

I have tried using the following but this shifts the
order of the output:

Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
    String paramName = (String) paramNames.nextElement();
    out.print(paramName);
}

Body:
request.getParameterNames () uses HashMap  internally to store the  name value pairs of form fields. There is no order maintained in this. if you need this in order then , some sort of naming convention for form parameters to control the order of retrieval.

SortedSet temp = new SortedSet();
Enumeration enumeration = request.getParameterNames();
while (enumeration.hasMoreElements())
{
        temp.add((String)enumeration.nextElement());
}

ContentLicense: CC BY-SA 2.5


问:
EF Core 2.0 Relation(Null Comig)
I am using asp.net core 2.0 and EF core 2.0.

I have 3 class for DbSet.

```<code>    public class Person
    {
        [Key]
        public int PersonId { get; set; }
        public string Name { get; set; }
     }

    public class Packet
    {
        [Key]
        public int PacketId { get; set; }
        public string Name{get;set;}
        public int Point{get;set;}

    }

    public class UserPacket
    {
       [Key]
        public int UserPacketId { get; set; }
        public int ParentPersonId { get; set; }
        public Person Parent { get; set; }
        public int PacketId { get; set; }
        public  Packet Packet { get; set; }
    }
</code>```

And

```<code> modelBuilder.Entity<UserPacket>().HasOne<Person>(a => a.Parent).WithMany().HasForeignKey(a=>a.ParentPersonId);
            modelBuilder.Entity<UserPacket>().HasOne<Person>(a => a.Owner).WithMany().HasForeignKey(a=>a.OwnerPersonId);
            modelBuilder.Entity<UserPacket>().HasOne<Packet>(a => a.Packet).WithMany().HasForeignKey(b=>b.PacketId);
</code>```

This is my design for table(Not include more detail.)
var person=blabla.....

```<code> var personPacket = _userPacketRepository.GetMany(a => a.OwnerPersonId == person.PersonId);
            double totalPacket = 0;
            foreach (var packet in personPacket)
            {
                totalPacket += packet.Packet.Point;
            }
</code>```

I can select packet but for the packet.Packet comes null. Anybody can help me ?

答:
Try to include it

```<code>_userPacketRepository.GetMany(a => a.OwnerPersonId == person.PersonId)
.Include(x => x.Packet);
</code>```

You can read more about EF and their roadmap and changes from Github wiki, it is very useful
https://github.com/aspnet/EntityFrameworkCore/wiki

Title: EF Core 2.0 Relation(Null Comig)

Body:
I am using asp.net core 2.0 and EF core 2.0.

I have 3 class for DbSet.

    public class Person
    {
        [Key]
        public int PersonId { get; set; }
        public string Name { get; set; }
     }

    public class Packet
    {
        [Key]
        public int PacketId { get; set; }
        public string Name{get;set;}
        public int Point{get;set;}

    }

    public class UserPacket
    {
       [Key]
        public int UserPacketId { get; set; }
        public int ParentPersonId { get; set; }
        public Person Parent { get; set; }
        public int PacketId { get; set; }
        public  Packet Packet { get; set; }
    }

And

 modelBuilder.Entity<UserPacket>().HasOne<Person>(a => a.Parent).WithMany().HasForeignKey(a=>a.ParentPersonId);
            modelBuilder.Entity<UserPacket>().HasOne<Person>(a => a.Owner).WithMany().HasForeignKey(a=>a.OwnerPersonId);
            modelBuilder.Entity<UserPacket>().HasOne<Packet>(a => a.Packet).WithMany().HasForeignKey(b=>b.PacketId);

This is my design for table(Not include more detail.)
var person=blabla.....

 var personPacket = _userPacketRepository.GetMany(a => a.OwnerPersonId == person.PersonId);
            double totalPacket = 0;
            foreach (var packet in personPacket)
            {
                totalPacket += packet.Packet.Point;
            }

I can select packet but for the packet.Packet comes null. Anybody can help me ?

Body:
Try to include it

_userPacketRepository.GetMany(a => a.OwnerPersonId == person.PersonId)
.Include(x => x.Packet);

You can read more about EF and their roadmap and changes from Github wiki, it is very useful
https://github.com/aspnet/EntityFrameworkCore/wiki


问:
Why does mktime() need to know about daylight saving time?
So mktime() returns a time_t value which is defined as "an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC" (source). I can convert a date to a time_t value by using mktime(). For example, to convert the date 10-Sep-2017 08:34:56 to a time_t I'd do the following:

```<code>struct tm tm;
time_t tv;

tm.tm_sec = 56;
tm.tm_min = 34;
tm.tm_hour = 8;
tm.tm_mday = 10;
tm.tm_mon = 8;
tm.tm_year = 117;
tm.tm_isdst = ????;

tv = mktime(&tm);
</code>```

Now what I don't understand is the idea behind the tm_isdst parameter: It is described as "a flag that indicates whether daylight saving time is in effect at the time described" (source).

This description is somewhat confusing me because I'm of the opinion that the time I'm describing in struct tm is in fact already a UTC time and the time_t value I want to have from mktime() is UTC as well. But UTC time doesn't change with a change of seasons, so why does mktime() need to bother with daylight saving time at all? Isn't the advantage of using UTC instead of local time that I won't have to bother with daylight saving time? So why do I have to set tm_isdst then?

I'm sure the answer is really simple but at the moment I'm failing to see it. Could somebody please provide a simple example that illustrates why mktime() needs the tm_isdst parameter to convert a certain date and time to a time_t value?

答:
struct tm can be thought of as a timestamp.

Example: When a timezone goes from daylight time to standard time, the "day" has 25 hours and struct tm needs more info than just "Y-M-D h:m:s".

The local time may be 2:30 AM daylight time and then 1 hour later it is 2:30 AM standard time.  .tm_isdst is especially useful to distinguish that case.  Note that .tm_isdst is relevant in all timestamps.

As struct tm itself does not contain the timezone (that info exist elsewhere), .tm_isdst is designed to provide time stamps indication of  standard time or daylight time (or even unknown standard/daylight).

If the .tm_isdst is set to -1 (unknown)  and the timezone is UTC, then the expectation is that, for all timestamps, it is as if .tm_isdst == 0.

Body:
So mktime() returns a time_t value which is defined as "an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC" (source). I can convert a date to a time_t value by using mktime(). For example, to convert the date 10-Sep-2017 08:34:56 to a time_t I'd do the following:

struct tm tm;
time_t tv;

tm.tm_sec = 56;
tm.tm_min = 34;
tm.tm_hour = 8;
tm.tm_mday = 10;
tm.tm_mon = 8;
tm.tm_year = 117;
tm.tm_isdst = ????;

tv = mktime(&tm);

Now what I don't understand is the idea behind the tm_isdst parameter: It is described as "a flag that indicates whether daylight saving time is in effect at the time described" (source).

This description is somewhat confusing me because I'm of the opinion that the time I'm describing in struct tm is in fact already a UTC time and the time_t value I want to have from mktime() is UTC as well. But UTC time doesn't change with a change of seasons, so why does mktime() need to bother with daylight saving time at all? Isn't the advantage of using UTC instead of local time that I won't have to bother with daylight saving time? So why do I have to set tm_isdst then?

I'm sure the answer is really simple but at the moment I'm failing to see it. Could somebody please provide a simple example that illustrates why mktime() needs the tm_isdst parameter to convert a certain date and time to a time_t value?


问:
Output empty elements
I have a Object with two fields "name" and "address". JAXB ignores the empty elements while transforming the object into XMl.

For ex: if I have name="xyz" and address=null then out will be

```<code><name>xyz</name>
</code>```

but what I want as an output as

```<code><name>xyz</name>
<address></address>
</code>```

I have seen the option @XmlElement(nillable="true") but this gives the output as

```<code><name>xyz</name>
<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</code>```

Please help me getting the desired output.

Thanks in advance.

答:
Simply set an empty string default value on the field.

```<code>@XmlElement(required="true")
private String address = "";
</code>```

and you will get

```<code><address></address>
</code>```

Title: Output empty elements

Body:
I have a Object with two fields "name" and "address". JAXB ignores the empty elements while transforming the object into XMl.

For ex: if I have name="xyz" and address=null then out will be

<name>xyz</name>

but what I want as an output as

<name>xyz</name>
<address></address>

I have seen the option @XmlElement(nillable="true") but this gives the output as

<name>xyz</name>
<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

Please help me getting the desired output.

Thanks in advance.

Body:
Simply set an empty string default value on the field.

@XmlElement(required="true")
private String address = "";

and you will get

<address></address>


问:
How to produce list of words from the text file in scala
I have a text file named shakespeare.txt which contains certain portions of shakespeare novel

```<code>val list1 = scala.io.Source.fromFile("shakespeare.txt")
  .getLines
  .flatMap(_.split("\\W+"))
</code>```

I am expexting the result :

```<code>list1=(hamlet,the,efficient,...etc)
</code>```

but this code didnt produce the list of word after seperation

答:
You can find the list like this:

```<code>scala> val list1 = scala.io.Source.fromFile("/home/anurag/test.txt").getLines.flatMap(_.split("\\W+")).toList
list1: List[String] = List(Hello, this, is, an, testing, file, Hello2)
</code>```

Thanks.

Body:
I have a text file named shakespeare.txt which contains certain portions of shakespeare novel

val list1 = scala.io.Source.fromFile("shakespeare.txt")
  .getLines
  .flatMap(_.split("\\W+"))

I am expexting the result :

list1=(hamlet,the,efficient,...etc)

but this code didnt produce the list of word after seperation

Body:
You can find the list like this:

scala> val list1 = scala.io.Source.fromFile("/home/anurag/test.txt").getLines.flatMap(_.split("\\W+")).toList
list1: List[String] = List(Hello, this, is, an, testing, file, Hello2)

Thanks.


问:
I am getting errors trying to use INSERT INTO using VBA in Access, and can't fix it
With the following code I get

error 3061 (Too few parameters.  Expected 2)

```<code>Option Compare Database

Private Sub Command0_Click()
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet

    Set xls = New Excel.Application

    xls.Visible = True
    xls.UserControl = True

    Set wkb = xls.Workbooks.Open("link\Reliability Projects v5.xlsm", ReadOnly:=True, UpdateLinks:=False)
    Set wks = wkb.Worksheets("Projects")

    Dim RWPTitle As String 'there may be a better type to use here
    RWPTitle = wks.Range("E10").Value
    Text1.Value = RWPTitle
    Dim EstimatedCapital As Currency 'there may be a better type to use here
    EstimatedCapital = wks.Range("J10").Value
    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost) Values (RWPTitle, EstimatedCapital)"

    wkb.Close False 'Close workbook.  False is so that it doesn't save

    Set wks = Nothing
    Set wkb = Nothing

    xls.Quit

    Set xls = Nothing
End Sub
</code>```

*When I try to use the INSERT INTO directly (No CurrentDb.EXECUTE) I get a

Compile Error - Expected:end of statement

and it highlights the Table name used.

Any ideas as to why this is happening to me?

Additionally, I am very new to VBA & Access.  Any good references for functions / calls used to deal with databse and with excel files / info?

答:
Here is how I like to handle inserts in vba.  I can then trace any values that are in error.  </p>

```<code>With rstTable1

  .AddNew
    !PlanTitle,  = "Text Field Here"
    !EstimatedCapitalCost = $value here
  .Update

End With
</code>```

Body:
With the following code I get

error 3061 (Too few parameters.  Expected 2)

Option Compare Database

Private Sub Command0_Click()
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet

    Set xls = New Excel.Application

    xls.Visible = True
    xls.UserControl = True

    Set wkb = xls.Workbooks.Open("link\Reliability Projects v5.xlsm", ReadOnly:=True, UpdateLinks:=False)
    Set wks = wkb.Worksheets("Projects")

    Dim RWPTitle As String 'there may be a better type to use here
    RWPTitle = wks.Range("E10").Value
    Text1.Value = RWPTitle
    Dim EstimatedCapital As Currency 'there may be a better type to use here
    EstimatedCapital = wks.Range("J10").Value
    CurrentDb.Execute "INSERT INTO Table1 (PlanTitle, EstimatedCapitalCost) Values (RWPTitle, EstimatedCapital)"

    wkb.Close False 'Close workbook.  False is so that it doesn't save

    Set wks = Nothing
    Set wkb = Nothing

    xls.Quit

    Set xls = Nothing
End Sub

*When I try to use the INSERT INTO directly (No CurrentDb.EXECUTE) I get a

Compile Error - Expected:end of statement

and it highlights the Table name used.

Any ideas as to why this is happening to me?

Additionally, I am very new to VBA & Access.  Any good references for functions / calls used to deal with databse and with excel files / info?

Body:
Here is how I like to handle inserts in vba.  I can then trace any values that are in error.

With rstTable1

  .AddNew
    !PlanTitle,  = "Text Field Here"
    !EstimatedCapitalCost = $value here
  .Update

End With


问:
PHP/Laravel Google APi w/ Calendar - Response Empty
I am running the following code as a Laravel command...

```<code>$cfg = Config::get('calendar');
$client = new \Google_Client();
$client->setApplicationName('Test Application');
$client->addScope(\Google_Service_Calendar::CALENDAR);
$client->setAuthConfig($cfg['authConfig']);
$service = new \Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
while (true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {
        echo $calendarListEntry->getSummary();
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}
</code>```

Authentication is fine, everything seems to work, but I get back an empty array for getItems()

Not sure what I am missing. Let me know if you need more info, I am getting a response, it is always just "itemless". I have 4 test calendars on the account.

答:
I discovered what the issue was. What google neglects to document is that, regardless of the fact that you can use all their test APIs in the developer console with the owner account, you must add the @web-calendar-******.iam.gserviceaccount.com and add a share it with the proper permissions to the calendar you wish to manage.

Another thing to note is that when you share it, even though you give it the proper permissions when adding the share, it will downgrade the permissions to read only. I had to alter and save it 3 times to get it to stick.

Body:
I am running the following code as a Laravel command...

$cfg = Config::get('calendar');
$client = new \Google_Client();
$client->setApplicationName('Test Application');
$client->addScope(\Google_Service_Calendar::CALENDAR);
$client->setAuthConfig($cfg['authConfig']);
$service = new \Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
while (true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {
        echo $calendarListEntry->getSummary();
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}

Authentication is fine, everything seems to work, but I get back an empty array for getItems()

Not sure what I am missing. Let me know if you need more info, I am getting a response, it is always just "itemless". I have 4 test calendars on the account.


问:
On what objects are variables within local scope of functions defined on?
So in this code below, on what object is y defined on? It outputs to three as seen below; of course var y is locally scoped, so I thought of the variable y as scoped to the object s or x. but still gives me undefined.. I know that alert(y) will give me three but that is not my question. I'm wondering on what object it is defined on if it is locally scoped in a function like the code below.

```<code>var s = function x() {
    var y = 3;
    alert(y); // y is defined on what object? //results 3
    alert(window.y); //local scope so obviously this won't be true
    alert(s.y); //undefined? why //expected 3
    alert(x.y); //undefined? why //expexted 3
}
s();
</code>```

答:
You can think of it like this - every time you call a function, a new anonymous object is created containing all of the local variables of the function.

When you say s.x, it refers to the function s (which is also its own object), but not to the anonymous object from the previous paragraph.. Note how there is only one s function, but it can be called many times, each time creating a new anonymous object.

Here's how your code actually looks* behind the scenes:

```<code>var s = function x(_ctx) {
   _ctx.y = 3;
   alert(_ctx.y); // locals are looked up in _ctx
   alert(window.y); //
   alert(s.y); // not looking in _ctx, but in s
   alert(x.y); // ditto, as x === s
}

s({});
</code>```

*) well, in a way..

Body:
So in this code below, on what object is y defined on? It outputs to three as seen below; of course var y is locally scoped, so I thought of the variable y as scoped to the object s or x. but still gives me undefined.. I know that alert(y) will give me three but that is not my question. I'm wondering on what object it is defined on if it is locally scoped in a function like the code below.

var s = function x() {
    var y = 3;
    alert(y); // y is defined on what object? //results 3
    alert(window.y); //local scope so obviously this won't be true
    alert(s.y); //undefined? why //expected 3
    alert(x.y); //undefined? why //expexted 3
}
s();

Body:
You can think of it like this - every time you call a function, a new anonymous object is created containing all of the local variables of the function.

When you say s.x, it refers to the function s (which is also its own object), but not to the anonymous object from the previous paragraph.. Note how there is only one s function, but it can be called many times, each time creating a new anonymous object.

Here's how your code actually looks* behind the scenes:

var s = function x(_ctx) {
   _ctx.y = 3;
   alert(_ctx.y); // locals are looked up in _ctx
   alert(window.y); //
   alert(s.y); // not looking in _ctx, but in s
   alert(x.y); // ditto, as x === s
}

s({});

*) well, in a way..


答: y in declared in the scope of function x. It is not related to any object. s is the same x. It refers to a function. Functions are callable objects which can have it's own properties assigning via s.y or x.y, but everything which is declared in it via var, const, let or function is not related to its object itself, but it's context. So the y is a simple variable, just scoped in the context of the function.

Title: On what objects are variables within local scope of functions defined on?


问:
How to combine values of objects with common key in JavaScript?
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

```<code>let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];
</code>```

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

```<code>let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]
</code>```

答:
Even though @Grégory's answer is quite elegant, it doesn't output the correct form. data contains an key/value object instead of an array of 2 elements with 1 key and 1 value.

Try this instead:

```<code>let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

let charDataTmp = {}
let chartData = []

//uniqueify
sourceData.forEach(block => {
  if (!charDataTmp[block.metric])
  {
    charDataTmp[block.metric]={rounded_counts:{}}
  }
  block.rounded_counts.forEach(roundedCount => {
    let key = Object.keys(roundedCount)[0]
    if (!charDataTmp[block.metric].rounded_counts[key])
    {
      charDataTmp[block.metric].rounded_counts[key] = 0
    }
    charDataTmp[block.metric].rounded_counts[key] += roundedCount[key]
  })
})

//unfold
Object.keys(charDataTmp).forEach(nameGroup => {
  chartData.push({
    name: nameGroup,
    data: Object.keys(charDataTmp[nameGroup].rounded_counts).map(counts => {
      return [
        counts,
        charDataTmp[nameGroup].rounded_counts[counts]
      ]
    })
  })
})

console.log(JSON.stringify(chartData, null, 4))
</code>```

Body:
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]

Body:
Even though @Grégory's answer is quite elegant, it doesn't output the correct form. data contains an key/value object instead of an array of 2 elements with 1 key and 1 value.

Try this instead:

let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

let charDataTmp = {}
let chartData = []

//uniqueify
sourceData.forEach(block => {
  if (!charDataTmp[block.metric])
  {
    charDataTmp[block.metric]={rounded_counts:{}}
  }
  block.rounded_counts.forEach(roundedCount => {
    let key = Object.keys(roundedCount)[0]
    if (!charDataTmp[block.metric].rounded_counts[key])
    {
      charDataTmp[block.metric].rounded_counts[key] = 0
    }
    charDataTmp[block.metric].rounded_counts[key] += roundedCount[key]
  })
})

//unfold
Object.keys(charDataTmp).forEach(nameGroup => {
  chartData.push({
    name: nameGroup,
    data: Object.keys(charDataTmp[nameGroup].rounded_counts).map(counts => {
      return [
        counts,
        charDataTmp[nameGroup].rounded_counts[counts]
      ]
    })
  })
})

console.log(JSON.stringify(chartData, null, 4))


问:
Soundcloud API Returning 403 on Some Tracks
I'm developing a site using the soundcloud API but it is giving me some troubles.

For some odd reason some tracks are returning a 403 forbidden error, whilst others are not. Does anybody know the cause of this issue?

For example, this works perfectly:
https://api.soundcloud.com/tracks/334511096.json?client_id=REDACTED_CLIENT_ID

Whilst this gives the 403 forbidden error:
https://api.soundcloud.com/tracks/328406416.json?client_id=REDACTED_CLIENT_ID

Any suggestions would be great, thanks!

答:
This question was answered here: SoundCloud API URLs timing out and then returning error 403 on about 50% of tracks

TL;RD SoundCloud API return 403 if they think that the track should not be available via API.


问:
best solution for make a ranged search on 2( or N) sorted set based on their score on Redis
i have some index(sorted set) containing key name sorted with timestamp as score, these index are for searching purpose , for example one index apple and one index red , apple contain all key name referencing an apple and red all key referencing a red thing.

All this is sorted with the timestamp of the creation of the main key, so i want to do search with that.

For one fild it's not a problem , with pagination i do zrange on apple for example to get all apple within range of pagination sorted by date, but my problem are when i want to combine 2 field.

For example if want all red apple, i can do it sure, but i must use a zunionstore and zrange(too long) or get all of the 2 index to perform a filter based on date, and i search the fastest solution to do that.

thank you for reading :)

答: The approach you described - ZUNIONSTORE followed by a ZRANGE is the most efficient within Redis core. Alternatively, you could use RediSearch for robuster indexing and searching abilities.


问:
how to merge a collection of Maps using streams
I have a collection of maps:

```<code>Collection<Map<String,Double>> myCol = table.values();
</code>```

I would like to transform this into a Map

```<code>Map<String, Double>
</code>```

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

```<code>Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}
</code>```

and mergeMaps() is defined as

```<code>mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}
</code>```

However, I would like to use streams to get a map from collection. I have tried as follows:

```<code>Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;
</code>```

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?

答:
From your input, you can fetch the stream of maps and then flatmap it to have a Stream<Map.Entry<String, Double>>. From there, you collect them into a new map, specifying that you want to sum the values mapped to the same key.

```<code>import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.toMap;

....

Map<String, Double> outMap =
    myCol.stream()
         .flatMap(m -> m.entrySet().stream())
         .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Double::sum));
</code>```

Alternatively, you can use groupingBy instead of toMap:

```<code>.collect(groupingBy(Map.Entry::getKey, summingDouble(Map.Entry::getValue)));
</code>```

Body:
I have a collection of maps:

Collection<Map<String,Double>> myCol = table.values();

I would like to transform this into a Map

Map<String, Double>

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}

and mergeMaps() is defined as

mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}

However, I would like to use streams to get a map from collection. I have tried as follows:

Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?

Body:
From your input, you can fetch the stream of maps and then flatmap it to have a Stream<Map.Entry<String, Double>>. From there, you collect them into a new map, specifying that you want to sum the values mapped to the same key.

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.toMap;

....

Map<String, Double> outMap =
    myCol.stream()
         .flatMap(m -> m.entrySet().stream())
         .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Double::sum));

Alternatively, you can use groupingBy instead of toMap:

.collect(groupingBy(Map.Entry::getKey, summingDouble(Map.Entry::getValue)));


问:
How to add custom logo, social media, contact us, local business schema in joomla, virtuemart?
I need to add below listed schema tags in my website, developed in joomla virtuemart.

Is there a way to add these schema tags dynamically?

My code example...

```<code>Logo schema – Home Page
{
  "@context": "http://schema.org",
  "@type": "Organization",
  "url": "http://www.domainname.com/",
  "logo": "http://www.domainname.com/images/logo.png"
}

Socail Media Schema -

<span itemscope itemtype="http://schema.org/Organization">
  <link itemprop="url" href="http://www.domainname.com/">
  <a itemprop="sameAs" href="https://www.facebook.com/PageName/">FB</a>
  <a itemprop="sameAs" href="https://twitter.com/PageName">Twitter</a>
  <a itemprop="sameAs" href="https://www.instagram.com/PageName/">Instagram</a>
</span>

 Contact Us Schema

{
  "@context": "http://schema.org",
  "@type": "Organization",
  "url": "http://www.domainname.com",
  "contactPoint": [
    { "@type": "ContactPoint",
      "telephone": "+91 10000 10000",
      "contactType": "customer service"
    }
  ]
}
</code>```

Please reply

Thanks

答:
I highly recommend Google Structured Data plugin from Tassos Marinos.  It has most of the major structured data types and he releases a new update with more about every month.  I use it on all my sites.

https://www.tassos.gr/joomla-extensions/google-structured-data-markup

Body:
I need to add below listed schema tags in my website, developed in joomla virtuemart.

Is there a way to add these schema tags dynamically?

My code example...

Logo schema – Home Page
{
  "@context": "http://schema.org",
  "@type": "Organization",
  "url": "http://www.domainname.com/",
  "logo": "http://www.domainname.com/images/logo.png"
}

Socail Media Schema -

  <link itemprop="url" href="http://www.domainname.com/">
  FB
  Twitter
  Instagram

 Contact Us Schema

{
  "@context": "http://schema.org",
  "@type": "Organization",
  "url": "http://www.domainname.com",
  "contactPoint": [
    { "@type": "ContactPoint",
      "telephone": "+91 10000 10000",
      "contactType": "customer service"
    }
  ]
}

Please reply

Thanks


问:
PHP: associate an array with another array both taken from curl
I have the following code that fetches arrays from a cURL.

```<code>$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
    $codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
    $codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);
</code>```

The code returns these values:

```<code>**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"

**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".
</code>```

I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:

1074d0 -> 160.16;

19f726 -> 234.32;

1072ba -> 256.88;

etc...

It's possible?

Thank you

Body:
I have the following code that fetches arrays from a cURL.

$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
    $codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
    $codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);

The code returns these values:

**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"

**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".

I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:

1074d0 -> 160.16;

19f726 -> 234.32;

1072ba -> 256.88;

etc...

It's possible?

Thank you

Body:
If I don't misunderstood your requirement then this should work. Remove extra imploding and try to array_combine() the two corresponding arrays.

  // Your initial code, after removing imploding
  $codici_hotel_arr = $codici_price_arr = [];
  foreach($data_destin['results'] as $key=>$val) {
       $codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
       $codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
  }

 // I assume your array structure will be after looping curl response
 $codici_hotel_arr = ["1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"];
 $codici_price_arr = ["160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63"];

 $result = array_combine($codici_hotel_arr,$codici_price_arr);
 print '<pre>';
 print_r($result);
 print '</pre>';

Result:

Array (
    [1074d0] => 160.16
    [19f726] => 234.32
    [1072ba] => 256.88
    [183444] => 325.42
    [1071bf] => 342.22
    [112438] => 353.30
    [1b326e] => 365.78
    [15d8ab] => 372.84
    [19d885] => 395.72
    [193e61] => 478.75
    [10aab2] => 503.36
    [107155] => 543.39
    [110669] => 584.61
    [189b95] => 584.61
    [16d78f] => 597.70
    [18dd7d] => 601.63
)

Edit: Because I don't understand your expected result that's why I post it also.If you want it on string format then try like this,

function print_string($v, $k) {
   echo "$k->$v\n";
}

array_walk($result, "print_string");


问:
in linux kernel, the data structure thread_struct contains both field esp0 and esp, what is the difference?
This is my guess:

esp0 is initialized with the kernel stack top addr. when the kernel stack is allocated, and it is used, during process switch, to initialize tss->esp0, so that when context switches from user mode to kernel mode, the kernel stack can be located; while esp is used to save the kernel stack top of the process that is to be scheduled out during process switch.

So esp0 in a thread_struct doesn't change once initialized, while esp changes.

Is my guess right?

答:
The thread_struct structure contains two of these ESP fields, those being esp0 and esp. However, they relate to the four fields in the tss_segment_32 structure, those being esp0, esp1, esp2 and esp.

These actually exist in the TSS so it's very much something from Intel rather than something from Linus et al.

As to why the TSS contains them, the numbers are logical if you know how the protection model works under x86. They are, in fact, the ring levels (except for esp which is for ring level 3 despite the fact it's not actually called esp3).

In other words, they contain the stack pointer to be used in the ring that you're executing in.  Since Linux only uses ring 0 (kernel mode) and ring 3 (user mode), esp0 and esp are the only ones that need to be saved.

As an aside, I think the only OS I've ever seen use another ring was OS/2 which used ring 2 for certain I/O operations. Processes that were allowed to perform those operations had to be specially marked and the OS would run them in ring 2 to allow unfettered I/O access, without being allowed to bring down the kernel.


问:
What is the recommended way to show a badge (a number) on the Application Icon?
I am creating a messaging mobile app using Xamarin. The app is expected to run on both Android and IOS. I need to implement notifications for this app in order to to show total number of unread messages over the application icon.

I am thinking of the following options:

Should I create a Background Service to do long pooling and call the
server to get the total number of unread messages and show over the
app icon?

Or create a Push Notification Service which pushes the total number of unread
messages to the clients?

Please advise if there is any other recommended approach to accomplish this.

Thanks,

Arfan

答:
Its called Badges for what you are taking about.

For your kind information, it is facility provided by manufacturer in Android,

It may not show in many devices.

Please read article provided by WhatsApp


问:
How to replace all elements in vector by the sum of element digits?
I have trouble understanding how to replace all elements in vector by the sum of element digits. For example if i have sequence of such digits 9 22 54 981 my output has to be 9 4 9 18.I know how to count the sum. I have this vector called file_numbers .But I am stuck at this point. Thanks for the help.

```<code>   int SumOfDigits(int digit)
{

    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}
void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
        file_numbers.end(),
        file_numbers.begin(),SumOfDigits);
}
</code>```

答: Convert the element to string, then loop for each character, convert character to int and add it up to previous character's sum..</p>

Body:
I have trouble understanding how to replace all elements in vector by the sum of element digits. For example if i have sequence of such digits 9 22 54 981 my output has to be 9 4 9 18.I know how to count the sum. I have this vector called file_numbers .But I am stuck at this point. Thanks for the help.

   int SumOfDigits(int digit)
{

    int sum = 0;
    while (digit > 0)
    {
        sum += digit % 10;
        digit /= 10;
    }
    return sum;
}
void FourthTask(vector<int>& file_numbers)
{
    std::transform(file_numbers.begin(),
        file_numbers.end(),
        file_numbers.begin(),SumOfDigits);
}


问:
Incorrect stacktrace by rethrow
I rethrow an exception with "throw;", but the stacktrace is incorrect:

```<code>static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}
</code>```

The right stacktrace should be:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12
</code>```

But I get:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15
</code>```

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

答:
Edit/Replace

The behavior is actually different, but subtilely so. As for why the behavior if different, I'll need to defer to a CLR expert.

EDIT: AlexD's answer seems to indicate that this is by design.

Throwing the exception in the same method that catches it confuses the situation a little, so let's throw an exception from another method:

```<code>class Program
{
    static void Main(string[] args)
    {
        try
        {
            Throw();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static void Throw()
    {
        int a = 0;
        int b = 10 / a;
    }
}
</code>```

If throw; is used, the callstack is (line numbers replaced with code):

```<code>at Throw():line (int b = 10 / a;)
at Main():line (throw;) // This has been modified
</code>```

If throw ex; is used, the callstack is:

```<code>at Main():line (throw ex;)
</code>```

If exception is not caught, the callstack is:

```<code>at Throw():line (int b = 10 / a;)
at Main():line (Throw())
</code>```

Tested in .NET 4 / VS 2010

Title: Incorrect stacktrace by rethrow

Body:
I rethrow an exception with "throw;", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}

The right stacktrace should be:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12

But I get:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

Body:
Edit/Replace

The behavior is actually different, but subtilely so. As for why the behavior if different, I'll need to defer to a CLR expert.

EDIT: AlexD's answer seems to indicate that this is by design.

Throwing the exception in the same method that catches it confuses the situation a little, so let's throw an exception from another method:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Throw();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static void Throw()
    {
        int a = 0;
        int b = 10 / a;
    }
}

If throw; is used, the callstack is (line numbers replaced with code):

at Throw():line (int b = 10 / a;)
at Main():line (throw;) // This has been modified

If throw ex; is used, the callstack is:

at Main():line (throw ex;)

If exception is not caught, the callstack is:

at Throw():line (int b = 10 / a;)
at Main():line (Throw())

Tested in .NET 4 / VS 2010


问:
Django - Model.py
Just a simple question.

After I connect my django app to a remote database, I don't need to use Model.py to create tables in the database, then what is the function for Model.py at that moment?

答:
As you said after running migrations all tables in models.py file will be created. Later on, if you want to do some database operations, you may be using Django ORM. If you don't have models.py you won't be able to do such operations.

For example:
To create an entry to the table MyModel.

```<code>from your_app.models import MyModel
MyModel.objects.create(<field_name>=<value>)
</code>```

I hope this gives you some idea.

Title: Django - Model.py

Body:
As you said after running migrations all tables in models.py file will be created. Later on, if you want to do some database operations, you may be using Django ORM. If you don't have models.py you won't be able to do such operations.

For example:
To create an entry to the table MyModel.

from your_app.models import MyModel
MyModel.objects.create(<field_name>=<value>)

I hope this gives you some idea.


问:
Date substraction why don't I get hh:mm:ss in Rebol / Red?
1°) I get only the number of days, how to also get the hh:mm:ss ?

```<code>diff: (now - (10-Nov-2017/15:00:00))
</code>```

6

2°) What's the most elegant way to get the number of minutes ?

答:
1°) I get only the number of days, how to also get the hh:mm:ss ?

Use difference function for that:

```<code>>> difference now 10-Nov-2017/15:00:00
== 145:19:24
</code>```

2°) What's the most elegant way to get the number of minutes ?

The same way as for any other date value:

```<code>>> d: difference now 10-Nov-2017/15:00:00
>> d/minute
== 21
</code>```

Alternatively, you can use pick to avoid setting the intermediary date to a word:

```<code>>> pick (difference now 10-Nov-2017/15:00:00) 2  ; Red and Rebol2/3
== 21
>> pick (difference now 10-Nov-2017/15:00:00) 'minute ; Rebol3, not yet implemented in Red
== 21
</code>```

Body:
1°) I get only the number of days, how to also get the hh:mm:ss ?

diff: (now - (10-Nov-2017/15:00:00))

6

2°) What's the most elegant way to get the number of minutes ?

Body:
1°) I get only the number of days, how to also get the hh:mm:ss ?

Use difference function for that:

>> difference now 10-Nov-2017/15:00:00
== 145:19:24

2°) What's the most elegant way to get the number of minutes ?

The same way as for any other date value:

>> d: difference now 10-Nov-2017/15:00:00
>> d/minute
== 21

Alternatively, you can use pick to avoid setting the intermediary date to a word:

>> pick (difference now 10-Nov-2017/15:00:00) 2  ; Red and Rebol2/3
== 21
>> pick (difference now 10-Nov-2017/15:00:00) 'minute ; Rebol3, not yet implemented in Red
== 21


问:
Empty DataFrame doesn't admit its empty
I must not understand something about emptiness when it comes to pandas DataFrames. I have a DF with empty rows but when I isolate one of these rows its not empty.

Here I've made a dataframe:

```<code>>>> df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
>>> df
     1    2    3
0  1.0  2.0  3.0
1  1.0  NaN  3.0
2  NaN  NaN  NaN
3  3.0  2.0  1.0
4  4.0  5.0  6.0
5  NaN  NaN  NaN
6  NaN  NaN  NaN
</code>```

Then I know row '2' is full of  nothing so I check for that...

```<code>>>> df[2:3].empty
    False
</code>```

Odd. So I split it out into its own dataframe:

```<code>>>> df1 = df[2:3]
>>> df1
    1   2   3
2 NaN NaN NaN

>>> df1.empty
False
</code>```

How do I check for emptiness (all the elements in a row being None or NaN?)

http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.empty.html

答:
You can drop all null values from your selection and check if the result is empty:</p>

```<code>>>> df[5:].dropna(how='all').empty
True
</code>```

Title: Empty DataFrame doesn't admit its empty

Body:
I must not understand something about emptiness when it comes to pandas DataFrames. I have a DF with empty rows but when I isolate one of these rows its not empty.

Here I've made a dataframe:

>>> df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
>>> df
     1    2    3
0  1.0  2.0  3.0
1  1.0  NaN  3.0
2  NaN  NaN  NaN
3  3.0  2.0  1.0
4  4.0  5.0  6.0
5  NaN  NaN  NaN
6  NaN  NaN  NaN

Then I know row '2' is full of  nothing so I check for that...

>>> df[2:3].empty
    False

Odd. So I split it out into its own dataframe:

>>> df1 = df[2:3]
>>> df1
    1   2   3
2 NaN NaN NaN

>>> df1.empty
False

How do I check for emptiness (all the elements in a row being None or NaN?)

http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.empty.html

Body:
You can drop all null values from your selection and check if the result is empty:

>>> df[5:].dropna(how='all').empty
True


问:
Remove the last line from a file in Bash
I have a file, foo.txt, containing the following lines:

```<code>a
b
c
</code>```

I want a simple command that results in the contents of foo.txt being:

```<code>a
b
</code>```

答:
Both of these solutions are here in other forms. I found these a little more practical, clear, and useful:

Using dd:

```<code>BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
dd if=${ORIGINALFILE} of=${ORIGINALFILE}.tmp status=none bs=1 count=$(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc )
/bin/mv -f ${ORIGINALFILE}.tmp ${ORIGINALFILE}
</code>```

Using truncate:

```<code>BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
truncate -s $(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc ) ${ORIGINALFILE}
</code>```

Body:
I have a file, foo.txt, containing the following lines:

a
b
c

I want a simple command that results in the contents of foo.txt being:

a
b

Body:
Both of these solutions are here in other forms. I found these a little more practical, clear, and useful:

Using dd:

BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
dd if=${ORIGINALFILE} of=${ORIGINALFILE}.tmp status=none bs=1 count=$(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc )
/bin/mv -f ${ORIGINALFILE}.tmp ${ORIGINALFILE}

Using truncate:

BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
truncate -s $(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc ) ${ORIGINALFILE}


问:
Sum list of Option[Int] Scala using fold
I was trying to sum all elements in a list, they are of type Option[Int], if any of them are None, the whole result is None, if all are Some(value), I want the sum of all of them:

```<code>val ls = List(Some(2), Some(5), Some(4), Some(1))

ls.fold(None)((rs,x) => for(n <- x; m <- rs) yield {n+m})
</code>```

but I always get None, no matter what.

答:
Try this also:

```<code>val ls = List(Some(2), Some(5), Some(4), Some(1))
val sum = ls.foldLeft(Option(0))((so, io) => so.flatMap(s => io.map(s + _)))
</code>```

If any single value in the list is None, then sum is reported as None; otherwise - if all values are defined - you get a Some containing the sum of elements. If the list is empty, then you'd get Some(0) as the result.

Body:
I was trying to sum all elements in a list, they are of type Option[Int], if any of them are None, the whole result is None, if all are Some(value), I want the sum of all of them:

val ls = List(Some(2), Some(5), Some(4), Some(1))

ls.fold(None)((rs,x) => for(n <- x; m <- rs) yield {n+m})

but I always get None, no matter what.

Body:
Try this also:

val ls = List(Some(2), Some(5), Some(4), Some(1))
val sum = ls.foldLeft(Option(0))((so, io) => so.flatMap(s => io.map(s + _)))

If any single value in the list is None, then sum is reported as None; otherwise - if all values are defined - you get a Some containing the sum of elements. If the list is empty, then you'd get Some(0) as the result.


问:
How to add html title attribute to jquery ui date picker widget?
In an ASP.NET MVC 5 project,How do I add a html title attribute to jquery ui date picker widget? I have tried adding it directly to the HTML element and also using JQuery. I have also tried using .prop from one of the answers below.

HTML from the Index page

```<code><input class="form-control" type="text" id="datepicker1" title="Enter Date"/>
<input class="form-control" type="text" id="datepicker2"/>
<input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />
</code>```

Jquery from the _Layoyut.cshtml

```<code>$("#datepicker1").attr("title", "Enter Start Date");
$("#datepicker2").attr("title", "Enter End Date");
</code>```

_Layout.cshtml

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body id="bgrnd">
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink(" EDI", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "Home" ? "active" : "")">
                    @Html.ActionLink("Home", "Index", "Home")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "Error_Summaries" ? "active" : "")">
                    @Html.ActionLink("BOL-Errors", "Index", "Error_Summaries")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_TMS" ? "active" : "")">
                    @Html.ActionLink("BOL-", "Index", "web_BOL_Summary_TMS")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_Ext" ? "active" : "")">
                    @Html.ActionLink("BOL-Partners", "Index", "web_BOL_Summary_Ext")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "Utilities" ? "active" : "")">
                    @Html.ActionLink("Utilities", "Index", "Utilities")</li>
                </ul>
                <p class="nav navbar-text navbar-right">@User.Identity.Name</p>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - Company Name</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/jqueryuicss")
    @RenderSection("scripts", required: false)

    @*Datepicker for BOL- Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_TMS")
    {
        <script>
            $(function ()
            {
                $('#datepicker1').prop('title', 'Enter Start Date');
                $("#datepicker2").prop("title", "Enter End Date");
                //$("#datepicker1").datepicker({});
                //$("#datepicker2").datepicker({});

            });

        </script>
    }

    @*Background picture for Home Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "Home")
    { <script>document.getElementById("bgrnd").className+="bgrnd"</script>
    }

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

Index.html

```<code>@{
    ViewBag.Title = "EDI_";

}
    <div class="container">
    <div class="row">
        <div class="col-lg-12 text-center">
            <h2>Bill of Ladings from  TMS</h2>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 text-center"></div>
        <div class="col-md-4 text-center">
            <ul class="list-group">
                <li class="list-group-item ">
                    <p class="h4">PD5200 Truck Loads Report</p>

                        @Html.ActionLink("This Week", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null) |
                        @Html.ActionLink("Last Week", "pd5200", "web_BOL_Summary_TMS", new { week = 0 }, null) <br />
                    <div class="h5">Enter Dates</div>
                    <div class="form-group-sm form-horizontal">
                        @using (Html.BeginForm("pd5200", "web_BOL_Summary_TMS", FormMethod.Post))                        {
                            <input class="form-control" type="text" id="datepicker1" title="Enter Date"/> <input class="form-control" type="text" id="datepicker2"/>
                            <input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />
                        }
                   </div>
</li>
                <li class="list-group-item">
                    <p class="h4">View  BOL</p>
                    <div class="form-group-sm form-horizontal">
                        @using (Html.BeginForm("ViewBol", "web_BOL_Summary_TMS"))
                        {
                            <input class="form-control" name="bolnumber" type="number" placeholder="Enter  BOL Number" title="Enter  BOL Number" />
                            <input id="btnViewBol" class="btn" type="submit" value="View" required="required" />
                        }
                    </div>
                </li>
                <li class="list-group-item">
                    <p class="h4">View Midnight Cut-offs</p>
                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                <span> | </span>
                            }
                        }

                    }
                </li>
                <li class="list-group-item">
                    <p class="h4">View Missing BOLS</p>
                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                <span> | </span>
                            }
                        }

                        @Html.ActionLink("Custom", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null) <span> | </span>
                        @Html.ActionLink("All", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null)
                    }
                </li>
            </ul>
        </div>
        <div class="col-md-4 text-center">
        </div>
    </div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

答:
```<code>$('#id').prop('title','your new title');
</code>```

<p>you can also use this attribute. </p>

Body:
In an ASP.NET MVC 5 project,How do I add a html title attribute to jquery ui date picker widget? I have tried adding it directly to the HTML element and also using JQuery. I have also tried using .prop from one of the answers below.

HTML from the Index page

<input class="form-control" type="text" id="datepicker1" title="Enter Date"/>
<input class="form-control" type="text" id="datepicker2"/>
<input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />

Jquery from the _Layoyut.cshtml

$("#datepicker1").attr("title", "Enter Start Date");
$("#datepicker2").attr("title", "Enter End Date");

_Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                @Html.ActionLink(" EDI", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

                    @Html.ActionLink("Home", "Index", "Home")

                    @Html.ActionLink("BOL-Errors", "Index", "Error_Summaries")

                    @Html.ActionLink("BOL-", "Index", "web_BOL_Summary_TMS")

                    @Html.ActionLink("BOL-Partners", "Index", "web_BOL_Summary_Ext")

                    @Html.ActionLink("Utilities", "Index", "Utilities")

@User.Identity.Name

        @RenderBody()

© @DateTime.Now.Year - Company Name

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/jqueryuicss")
    @RenderSection("scripts", required: false)

    @*Datepicker for BOL- Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_TMS")
    {

    }

    @*Background picture for Home Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "Home")
    {
    }

Index.html

@{
    ViewBag.Title = "EDI_";

}

Bill of Ladings from  TMS

PD5200 Truck Loads Report

                        @Html.ActionLink("This Week", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null) |
                        @Html.ActionLink("Last Week", "pd5200", "web_BOL_Summary_TMS", new { week = 0 }, null)

Enter Dates

                        @using (Html.BeginForm("pd5200", "web_BOL_Summary_TMS", FormMethod.Post))                        {
                            <input class="form-control" type="text" id="datepicker1" title="Enter Date"/> <input class="form-control" type="text" id="datepicker2"/>
                            <input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />
                        }

View  BOL

                        @using (Html.BeginForm("ViewBol", "web_BOL_Summary_TMS"))
                        {
                            <input class="form-control" name="bolnumber" type="number" placeholder="Enter  BOL Number" title="Enter  BOL Number" />
                            <input id="btnViewBol" class="btn" type="submit" value="View" required="required" />
                        }

View Midnight Cut-offs

                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                 |
                            }
                        }

                    }

View Missing BOLS

                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                 |
                            }
                        }

                        @Html.ActionLink("Custom", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null)  |
                        @Html.ActionLink("All", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null)
                    }

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Body:
$('#id').prop('title','your new title');

you can also use this attribute.