text:
Q: Default font family in .NET MAUI Is there a way to simultaneously set the default font family to all text controls? The idea is not to specify a font family for each control separately.

A: You could set a variable inside the styles.xaml and set all FontFamilys to that variable
For example:

    <System:String x:Key="StrFontFamily">Times New Roman</System:String>

...

    <Style TargetType="Label">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

The be fair, you still set it for each control separately, but all at once with one variable.
If this seems like something that would work for you then the below code is the whole Styles.xaml with the variable defined in it.
Copy it from here into {Project}/Resources/Styles/Styles.xaml to test it.
<?xml version="1.0" encoding="UTF-8" ?>
<?xaml-comp compile="true" ?>
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:System="clr-namespace:System;assembly=mscorlib">

    <System:String x:Key="StrFontFamily">Times New Roman</System:String>

    <Style TargetType="ActivityIndicator">
        <Setter Property="Color" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
    </Style>

    <Style TargetType="IndicatorView">
        <Setter Property="IndicatorColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}"/>
        <Setter Property="SelectedIndicatorColor" Value="{AppThemeBinding Light={StaticResource Gray950}, Dark={StaticResource Gray100}}"/>
    </Style>

    <Style TargetType="Border">
        <Setter Property="Stroke" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
        <Setter Property="StrokeShape" Value="Rectangle"/>
        <Setter Property="StrokeThickness" Value="1"/>
    </Style>

    <Style TargetType="BoxView">
        <Setter Property="Color" Value="{AppThemeBinding Light={StaticResource Gray950}, Dark={StaticResource Gray200}}" />
    </Style>

    <Style TargetType="Button">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource Primary}}" />
        <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="CornerRadius" Value="8"/>
        <Setter Property="Padding" Value="14,10"/>
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray950}, Dark={StaticResource Gray200}}" />
                            <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="CheckBox">
        <Setter Property="Color" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="Color" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="DatePicker">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
        <Setter Property="BackgroundColor" Value="Transparent" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="Editor">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
        <Setter Property="BackgroundColor" Value="Transparent" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="Entry">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
        <Setter Property="BackgroundColor" Value="Transparent" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="Frame">
        <Setter Property="HasShadow" Value="False" />
        <Setter Property="BorderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray950}}" />
        <Setter Property="CornerRadius" Value="8" />
    </Style>

    <Style TargetType="ImageButton">
        <Setter Property="Opacity" Value="1" />
        <Setter Property="BorderColor" Value="Transparent"/>
        <Setter Property="BorderWidth" Value="0"/>
        <Setter Property="CornerRadius" Value="0"/>
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="Opacity" Value="0.5" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="Label">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="ListView">
        <Setter Property="SeparatorColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
        <Setter Property="RefreshControlColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray200}}" />
    </Style>

    <Style TargetType="Picker">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
        <Setter Property="TitleColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray200}}" />
        <Setter Property="BackgroundColor" Value="Transparent" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                            <Setter Property="TitleColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="ProgressBar">
        <Setter Property="ProgressColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="ProgressColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="RadioButton">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="RefreshView">
        <Setter Property="RefreshColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray200}}" />
    </Style>

    <Style TargetType="SearchBar">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
        <Setter Property="PlaceholderColor" Value="{StaticResource Gray500}" />
        <Setter Property="CancelButtonColor" Value="{StaticResource Gray500}" />
        <Setter Property="BackgroundColor" Value="Transparent" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                            <Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="SearchHandler">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
        <Setter Property="PlaceholderColor" Value="{StaticResource Gray500}" />
        <Setter Property="BackgroundColor" Value="Transparent" />
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                            <Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="Shadow">
        <Setter Property="Radius" Value="15" />
        <Setter Property="Opacity" Value="0.5" />
        <Setter Property="Brush" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource White}}" />
        <Setter Property="Offset" Value="10,10" />
    </Style>

    <Style TargetType="Slider">
        <Setter Property="MinimumTrackColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="MaximumTrackColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray600}}" />
        <Setter Property="ThumbColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="MinimumTrackColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}"/>
                            <Setter Property="MaximumTrackColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}"/>
                            <Setter Property="ThumbColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}"/>
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="SwipeItem">
        <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource Black}}" />
    </Style>

    <Style TargetType="Switch">
        <Setter Property="OnColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="ThumbColor" Value="{StaticResource White}" />
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="OnColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                            <Setter Property="ThumbColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                    <VisualState x:Name="On">
                        <VisualState.Setters>
                            <Setter Property="OnColor" Value="{AppThemeBinding Light={StaticResource Secondary}, Dark={StaticResource Gray200}}" />
                            <Setter Property="ThumbColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
                        </VisualState.Setters>
                    </VisualState>
                    <VisualState x:Name="Off">
                        <VisualState.Setters>
                            <Setter Property="ThumbColor" Value="{AppThemeBinding Light={StaticResource Gray400}, Dark={StaticResource Gray500}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="TimePicker">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="FontFamily" Value="{StaticResource StrFontFamily}"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Disabled">
                        <VisualState.Setters>
                            <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray300}, Dark={StaticResource Gray600}}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

    <Style TargetType="Page" ApplyToDerivedTypes="True">
        <Setter Property="Padding" Value="0"/>
        <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource Black}}" />
    </Style>

    <Style TargetType="Shell" ApplyToDerivedTypes="True">
        <Setter Property="Shell.BackgroundColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Gray950}}" />
        <Setter Property="Shell.ForegroundColor" Value="{OnPlatform WinUI={StaticResource Primary}, Default={StaticResource White}}" />
        <Setter Property="Shell.TitleColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource White}}" />
        <Setter Property="Shell.DisabledColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray950}}" />
        <Setter Property="Shell.UnselectedColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray200}}" />
        <Setter Property="Shell.NavBarHasShadow" Value="False" />
        <Setter Property="Shell.TabBarBackgroundColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource Black}}" />
        <Setter Property="Shell.TabBarForegroundColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="Shell.TabBarTitleColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="Shell.TabBarUnselectedColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray200}}" />
    </Style>

    <Style TargetType="NavigationPage">
        <Setter Property="BarBackgroundColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Gray950}}" />
        <Setter Property="BarTextColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource White}}" />
        <Setter Property="IconColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource White}}" />
    </Style>

    <Style TargetType="TabbedPage">
        <Setter Property="BarBackgroundColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource Gray950}}" />
        <Setter Property="BarTextColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource White}}" />
        <Setter Property="UnselectedTabColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray950}}" />
        <Setter Property="SelectedTabColor" Value="{AppThemeBinding Light={StaticResource Gray950}, Dark={StaticResource Gray200}}" />
    </Style>

</ResourceDictionary>


text:
Q: Limit action in comment according to IP I've been trying to set something that might be really easy (but I never had to do this before) :
add_filter('pre_comment_user_ip', 'limit_commentator');
function limit_commentator( $comment ) {
    $comment_field_value = get_comment_meta( $comment->comment_ID, 'some_custom_field', true );
    //my code

}

I think this is the right hook but how can I limit the ability for commentators to post comment WITH this custom field? Actually I just want one value per IP.
Got another question : Is it really worthy to limit per IP? I've been thinking about a limit on a daily basis. What do you think about this?

A: That hook won't do it. It is a filter. You can alter the IP data but unless you are willing to kill (die; or exit; or wp_die()) the whole script you aren't going to be able to stop the comment posting. I tested by hooking return false; to the filter. Nothing.
You can kill comment submission by hooking return false; to pre_comment_approved though, and you do have the IP data in the second parameter.
add_filter('pre_comment_approved', 'limit_commentator', 1, 2);
function limit_commentator( $approved, $commentdata ) {
  var_dump($approved,$commentdata);
  die;
}

You can check the $wpdb->comments table for that IP (in the comment_author_IP column) and return false if you get a match. It should be easy, but I wouldn't do it. Many residential internet connections share the same external IP. If you limit by IP you may be limiting comments to one per neighborhood. Plus, residential IPs change. This is not reliable.
Rate limiting (per day / per hour) based on IP is a much better idea only because the odds are in your favor, and the implementation would be pretty similar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Actionscript 3 :Simple Drag Question., I am trying to create a scroller...The videoSlider is my scrollBar and I want to drag it so my secondMC will move....everything works fine in my code but if I mouse down in my videoSlider and up outside of it....The drag state still apply and it's not what I desire....any ideas?? Thanks...
      videoSlider.addEventListener(MouseEvent.MOUSE_DOWN, scrollMC);
        videoSlider.addEventListener(MouseEvent.MOUSE_UP, stopScrollMC);

var eventTarget:Object; // to allow more global access to the dragged object

    function scrollMC(event:MouseEvent):void{
          eventTarget = Object(event.currentTarget);
          eventTarget.startDrag(false,new Rectangle(0,0,500,0));
          stage.addEventListener(MouseEvent.MOUSE_MOVE, adjust2ndX);
    }

    function stopScrollMC(event:MouseEvent):void{
          eventTarget.stopDrag();
          stage.removeEventListener(MouseEvent.MOUSE_MOVE, adjust2ndX);
    }

    function adjust2ndX(evt:MouseEvent):void {
          secondMC.x = eventTarget.x;
    }

A: Listen for MouseUp on the stage. Your object isn't going to get a MouseUp event if the mouseup occurs somewhere else.


text:
Q: python arma fitting running too slow? I am doing this assignment where I am trying to run this program 5000 times and do an AR(1) and AR(2) fit to the model.  First I defined a function that generated a time series as follows:
def ts_gen_ar1(size,sigma,alpha1):
    wt = np.random.normal(0,sigma**2,size=size)
    x = np.zeros(size)
    for i in np.arange(1,size):
        x[i] = 0.2 + alpha1*x[i-1] + wt[i]
return x

Then i executed the following statements thats taking extremely long time to work
sample_ar1 = []
sample_ar2 = []
for i in range(0,5000):
    rt = ts_gen_ar1(2500,1,0.8)
    coeff_ar1 = sm.tsa.ARMA(rt,order=(1,0)).fit().params[1]
    coeff_ar2 = sm.tsa.ARMA(rt,order=(2,0)).fit().params[1:]
    sample_ar1.append(coeff_ar1)
    sample_ar2.append(coeff_ar2)

can someone suggest how to speed this up?  I am also getting fitting errors where my program says MLE failed to converge for certain iterations.
Thanks

A: Recursive loops for time series analysis in plain Python are slow.
The easiest solution in this case for generating the sample is to use scipy.signal.lfilter or the wrapper for it in statsmodels arma_generate_sample http://statsmodels.sourceforge.net/devel/generated/statsmodels.tsa.arima_process.arma_generate_sample.html
Another possibility to speed up the random number generation is to run it vectorized for many samples, e.g. run it over blocks of 100 processes. You still have the time loop, but you can reduce the number of replication loops at the cost of using more memory.
sm.tsa.ARMA uses a Kalman Filter written in cython and runs fast, but it is for a general ARMA process which does more work than is needed for estimating a AR model.
sm.ts.AR estimates the parameters of a AR process by full maximum likelihood under stationarity assumption (by default).
The simplest and fastest is to estimate the AR process by OLS, which doesn't require non-linear optimization, or use Yule-Walker statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.yule_walker.html
The last two can estimated the parameters conditional on the initial observations, but will not have the full post-estimation features, like forecasting, that the AR and ARMA models have.


text:
Q: A specific format for nice tables With this code:

\documentclass[a4paper,12pt]{article}
\usepackage{mathtools,amssymb}
\usepackage{booktabs, isotope}
\begin{document}
\begin{center}
\begin{tabular}{lcc}
\toprule
\textbf{Osservabile} & \textbf{Simbolo} & \textbf{Operatore associato} \\
\toprule
Posizione & $\bar{r}$ & $\bar{r}$ \\
Momento & $\bar{p}$ & $-i\hslash \overline \nabla$ \\
Energia potenziale & $  \mathcal{U}$ &  $\mathcal{U}(r)$ \\
Energia cinetica & $\mathcal{K}$ &  $-\dfrac{\hslash^2}{2m}\nabla^2$ \\
Hamiltoniana & $H$ & $-\dfrac{\hslash^2}{2m}\nabla^2+\mathcal{U}(r)$\\
Energia totale & $E$ & $-i\hslash\dfrac{\partial}{\partial t}$\\
\bottomrule
\end{tabular}
\end{center}
\vskip 1cm
\begin{center}
\begin{tabular}{cccc}
\toprule
\textbf{Numeri di massa} & \textbf{Elemento chimico} & \textbf{Prodotto iniziale} & \textbf{Prodotto finale}\\
\midrule
$4n$ &  Torio   &   \isotope[232][90]{Th} &   \isotope[208][82]{Pb} \\
$4n+1$ &  Neptunio   &  \isotope[237][93]{Np}  &  \isotope[209][83]{Bi}  \\
$4n+2$ &  Uranio   &  \isotope[238][92]{U}  & \isotope[206][82]{Pb}  \\
$4n+3$ &  Attinio   &  \isotope[235][92]{U}  &  \isotope[207][82]{Pb} \\
\bottomrule
\end{tabular}
\end{center}
\end{document}

I'm finding to create two tables that they have the same structure of the below picture:

1. I would like to create as the upper image, the label (same color) of the table in upper case with a different character (I use into my book URW Classic as Sans Serif character (\fontfamily) and by default as normal text character is newtxtext, the clone of Times).
See this example for the figure below:

2. A thicker line with the same color as the image if possible;
3. The comment of the table must be with the character newtxtext;
4. A slightly larger space between rows in my second table. Precisely between one chemical element and the other below.
Thank you very much.

A: see, if the following solution is close to what you after:
\documentclass[a4paper,12pt]{article} % <---
\usepackage{mathtools,amssymb}                % <---
\usepackage{booktabs,
            makecell}                         % <---
\setcellgapes{3pt}                            % <---
\usepackage{isotope}
\usepackage[table]{xcolor}                    % <---
\arrayrulecolor{teal}                         % <---

\usepackage[skip=1ex]{caption}                % <---
    \DeclareCaptionFont{teal}{\color{teal}}   % <---
    \captionsetup[table]{font=bf,             % <---
                         labelfont={teal,bf},
                         singlelinecheck=off}

\begin{document}
    \begin{table}[htb]              % <---
    \makegapedcells                 % <---
    \caption{My fancy table}        % <---
\begin{tabular}{l*{2}{>{$}c<{$}}}   % <---
    \toprule[2pt]                   % toprule thickens you can change according
                                    % to your taste, for example to 3pt or more
\textbf{Osservabile} & \textbf{Simbolo} & \textbf{Operatore associato}  \\
    \midrule
Posizione           & \bar{r}       & \bar{r}                           \\
Momento             & \bar{p}       & -i\hslash \overline \nabla        \\
Energia potenziale  & \mathcal{U}   & \mathcal{U}(r)                    \\
Energia cinetica    & \mathcal{K}   & -\dfrac{\hslash^2}{2m}\nabla^2    \\
Hamiltoniana        & H             & -\dfrac{\hslash^2}{2m}\nabla^2+\mathcal{U}(r) \\
Energia totale      & E             & -i\hslash\dfrac{\partial}{\partial t}         \\
    \bottomrule
\end{tabular}
    \end{table}

    \begin{table}[htb]
    \caption{My another fancy table}
\makegapedcells
\begin{tabular}{cccc}
    \toprule[2pt]      % <---
\thead{Numeri\\ di massa}
        & \thead{Elemento\\ chimico}
                        & \thead{Prodotto\\ iniziale}
                                                    & \thead{Prodotto\\ finale}\\   % <---
    \midrule
$4n$    &  Torio        &   \isotope[232][90]{Th}   &   \isotope[208][82]{Pb}   \\
$4n+1$  &  Neptunio     &   \isotope[237][93]{Np}   &   \isotope[209][83]{Bi}   \\
$4n+2$  &  Uranio       &   \isotope[238][92]{U}    &   \isotope[206][82]{Pb}   \\
$4n+3$  &  Attinio      &   \isotope[235][92]{U}    &   \isotope[207][82]{Pb}   \\
    \bottomrule
\end{tabular}
    \end{table}

\end{document}

so far i consider only tables in your mwe (it not contain your table 13.1, if you will provide code for this table content, i will show solution example for it too)
edit:
differences between above and your mwe are indicated by % <---. as you can see, above are added packages xcolor for coloring table rules as well font for tables' labels, makecell for adding more vertical spaces around cells contents and for macro \thead, which enable to write column heads in two (or more, if necessary) lines, caption for defining caption style (font family and color, positioning of caption).
in above mwe tables are not horizontally centered. if you like to have them centered, just add \centering after \begin{table}[...]. but in this case the caption will be aligned with left text border. for aligning it width beginning of table, you should use threeparttable as shown in mwe below. in it is also added a way how to select font used in caption and have upper case font in caption label (indicaed by % <===). so far i select iwona, but you can replace it with font of your wish. also the thikness of rules are defined globally.
\documentclass[a4paper,12pt,italian]{article}
\usepackage{babel}
\usepackage{mathtools,amssymb}
\usepackage{booktabs, makecell,
            threeparttable}       % <---
\setlength\heavyrulewidth{2pt}    % <---
\setlength\lightrulewidth{1.2pt}  % <---

\setcellgapes{3pt}
\renewcommand\theadfont{\normalsize\bfseries}
\renewcommand\theadgape{}

\usepackage{isotope}
\usepackage[table]{xcolor}
\arrayrulecolor{teal}
\usepackage[skip=0.5ex]{caption}
    \DeclareCaptionLabelFormat{uc}{\MakeUppercase{#1}~#2}                % <===
    \DeclareCaptionFont{teal}{\color{teal}\fontfamily{iwona}\selectfont} % <===
    \captionsetup[table]{font={large,teal,bf},
                         labelformat=uc,                                 % <===
                         singlelinecheck=off}

%---------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%

\begin{document}
    \begin{table}[htb]
    \centering                  % <---
   \begin{threeparttable}       % <---
    \caption{My fancy table}
\makegapedcells
\begin{tabular}{l*{2}{>{$}c<{$}}}
    \toprule
\textbf{Osservabile} & \textbf{Simbolo} & \textbf{Operatore associato}  \\
    \midrule
Posizione           & \bar{r}       & \bar{r}                           \\
Momento             & \bar{p}       & -i\hslash \overline \nabla        \\
Energia potenziale  & \mathcal{U}   & \mathcal{U}(r)                    \\
Energia cinetica    & \mathcal{K}   & -\dfrac{\hslash^2}{2m}\nabla^2    \\
Hamiltoniana        & H             & -\dfrac{\hslash^2}{2m}\nabla^2+\mathcal{U}(r) \\
Energia totale      & E             & -i\hslash\dfrac{\partial}{\partial t}         \\
    \bottomrule
\end{tabular}
    \end{threeparttable}        % <---
    \end{table}

    \begin{table}[htb]
    \centering                  % <---
   \begin{threeparttable}       % <---
    \caption{My another fancy table}
\makegapedcells
\begin{tabular}{cccc}
    \toprule
\thead{Numeri\\ di massa}
        & \thead{Elemento\\ chimico}
                        & \thead{Prodotto\\ iniziale}
                                                    & \thead{Prodotto\\ finale}\\
    \midrule
$4n$    &  Torio        &   \isotope[232][90]{Th}   &   \isotope[208][82]{Pb}   \\
$4n+1$  &  Neptunio     &   \isotope[237][93]{Np}   &   \isotope[209][83]{Bi}   \\
$4n+2$  &  Uranio       &   \isotope[238][92]{U}    &   \isotope[206][82]{Pb}   \\
$4n+3$  &  Attinio      &   \isotope[235][92]{U}    &   \isotope[207][82]{Pb}   \\
    \bottomrule
\end{tabular}
    \end{threeparttable}        % <---
    \end{table}
\end{document}

which gives:

(red lines indicate page borders)

A: *

*\arrayrulecolor from the colortbl package for the rule color

*captionsetep and captionof commands from the caption package for the caption settings

*toprule[3pt] for a top rule 3pt thick

*\renewcommand{\arraystretch}{1.5}  for increasing row size by a factor of 1.5

*To get the table centered and the caption starting at the table left limit:  Put the table content inside a minipage environment of width equal to the table width then put the minipage inside a center environment

!
\documentclass[a4paper,12pt]{article}
\usepackage{mathtools,amssymb}
\usepackage{booktabs, isotope,colortbl,caption}

\arrayrulecolor{cyan}
\captionsetup[table]{labelfont={color=cyan,sc},justification=RaggedRight,singlelinecheck=false,skip=2pt}

\newlength{\mytablewidth}
\newsavebox{\mytablebox}

 \renewcommand{\arraystretch}{1.5}

\begin{document}
\begin{center}
\savebox{\mytablebox}
{\begin{tabular}{lcc}
\toprule[3pt]
\textbf{Osservabile} & \textbf{Simbolo} & \textbf{Operatore associato} \\
\toprule
Posizione & $\bar{r}$ & $\bar{r}$ \\
Momento & $\bar{p}$ & $-i\hslash \overline \nabla$ \\
Energia potenziale & $  \mathcal{U}$ &  $\mathcal{U}(r)$ \\
Energia cinetica & $\mathcal{K}$ &  $-\dfrac{\hslash^2}{2m}\nabla^2$ \\
Hamiltoniana & $H$ & $-\dfrac{\hslash^2}{2m}\nabla^2+\mathcal{U}(r)$\\
Energia totale & $E$ & $-i\hslash\dfrac{\partial}{\partial t}$\\
\bottomrule
\end{tabular}}
\settowidth{\mytablewidth}{\usebox{\mytablebox}}
\begin{minipage}{\mytablewidth}
\captionof{table}{my first table}
\usebox{\mytablebox}
\end{minipage}
\end{center}
\vskip 1cm
\begin{center}
\savebox{\mytablebox}{\begin{tabular}{cccc}
\toprule[3pt]
\textbf{Numeri di massa} & \textbf{Elemento chimico} & \textbf{Prodotto iniziale} & \textbf{Prodotto finale}\\
\midrule
$4n$ &  Torio   &   \isotope[232][90]{Th} &   \isotope[208][82]{Pb} \\
$4n+1$ &  Neptunio   &  \isotope[237][93]{Np}  &  \isotope[209][83]{Bi}  \\
$4n+2$ &  Uranio   &  \isotope[238][92]{U}  & \isotope[206][82]{Pb}  \\
$4n+3$ &  Attinio   &  \isotope[235][92]{U}  &  \isotope[207][82]{Pb} \\
\bottomrule
\end{tabular}}

\settowidth{\mytablewidth}{\usebox{\mytablebox}}
\begin{minipage}{\mytablewidth}
\captionof{table}{my second table}
\usebox{\mytablebox}
\end{minipage}

\end{center}
\end{document}


text:
Q: Data is not populating in ListView I am working on a screen in which i want to show data from the SQlite table.
While debugging what can i see is, data is coming in adapter but not populating in listview when it comes to listView.setAdapter(adapter). (I am using custom adapter, custom list item)
Any error is also not showing up.
Please help. I am posting my code below.
place_list_item :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="1.0">

    <TextView
        android:id="@+id/serial_number_textview_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:padding="5dp"
        android:text="1"
        android:textColor="@color/common_signin_btn_default_background"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/duration_textview_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.4"
        android:padding="5dp"
        android:text="hello"
        android:textColor="@color/common_signin_btn_default_background"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/distance_textview_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.4"
        android:padding="5dp"
        android:text="hello"
        android:textColor="@color/common_signin_btn_default_background"
        android:textSize="16sp" />

</LinearLayout>

trip_history_screen:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dbeaf8"
    android:orientation="vertical"
    android:weightSum="1.0">

    <LinearLayout
        android:id="@+id/heading_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="#000000"
        android:gravity="center_horizontal">

        <TextView
            android:id="@+id/header_label_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="Trip Histroy"
            android:textColor="@android:color/white"
            android:textSize="18dp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/titles_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/heading_layout"
        android:orientation="horizontal"
        android:weightSum="1.0">

        <TextView
            android:id="@+id/serial_number_title_textview_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:padding="5dp"
            android:text="No."
            android:textSize="16sp" />

        <TextView
            android:id="@+id/duration_title_textview_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.4"
            android:padding="5dp"
            android:text="Duration"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/distance_title_textview_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.4"
            android:padding="5dp"
            android:text="Distance"
            android:textSize="16sp" />

    </LinearLayout>

    <ListView
        android:id="@+id/trip_history_listview_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/titles_layout"
        android:layout_marginBottom="50dp"
        android:cacheColorHint="#00000000"
        android:divider="@drawable/listview_devider_dockets"
        android:dividerHeight="2dp"
        android:paddingTop="10dp" />
</LinearLayout>

Adapter:
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.RareMediaCompany.MuditaMileage.DataClasses.ListData;
import com.RareMediaCompany.MuditaMileage.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SANGEETA on 17-08-2015.
 */
public class TripHistoryDataAdapter extends ArrayAdapter {
    List list = new ArrayList();
    private Typeface typeface;
    Context mContext;
    int resource;
//public TripHistoryDataAdapter(Context context, int resource, Typeface typeface) {
//    this.mContext = context;
//    this.resource = resource;
//    this.typeface = typeface;
//
//    // super(context, resource);
//}

    public TripHistoryDataAdapter(Context context, int resource) {
        super(context, resource);
    }

    static class DataHandler {
        TextView number;
        TextView duration;
        TextView distanceCovered;
    }

    @Override
    public void add(Object object) {
        super.add(object);
        list.add(object);
    }

    @Override
    public int getCount() {
        return this.list.size();
    }

    @Override
    public Object getItem(int position) {
        return this.list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row;
        row = convertView;
        DataHandler handler;
        Log.i("LstAdapter", "Inside getView");
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.place_list_item, parent, false);
            handler = new DataHandler();
            handler.number = (TextView) row.findViewById(R.id.serial_number_textview_id);
            handler.duration = (TextView) row.findViewById(R.id.duration_textview_id);
            handler.distanceCovered = (TextView) row.findViewById(R.id.distance_textview_id);
            row.setTag(handler);
        } else {
            handler = (DataHandler) row.getTag();
        }

        ListData historyDataProvider;
        historyDataProvider = (ListData) this.getItem(position);
        handler.number.setText(historyDataProvider.getNumber());
        handler.duration.setText(historyDataProvider.getTime());
        handler.distanceCovered.setText(historyDataProvider.getDistance());
        return row;
    }
}

fragment:
public class TripHistoryFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//    private static final String ARG_PARAM1 = "param1";
//    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private MyDbHelper helper;
    private ListView listView;
    private TextView serialNumberTitle, timeTitle, distanceCoveredTitle;
    private TextView headerTextView;
    private List<ListData> dataList;
    private TripHistoryDataAdapter adapter;
    private Typeface typeface;
    private GetDataTask getDataTaskObj;
    // private OnFragmentInteractionListener mListener;

    public TripHistoryFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.trip_history_screen, container, false);
        typeface = Typeface.createFromAsset(getActivity().getAssets(),
                "fonts/AvantGarde.ttf");
        listView = (ListView) rootView.findViewById(R.id.trip_history_listview_id);
        serialNumberTitle = (TextView) rootView.findViewById(R.id.serial_number_title_textview_id);
        timeTitle = (TextView) rootView.findViewById(R.id.duration_title_textview_id);
        distanceCoveredTitle = (TextView) rootView.findViewById(R.id.distance_title_textview_id);
        headerTextView = (TextView) rootView.findViewById(R.id.header_label_id);
        adapter = new TripHistoryDataAdapter(getActivity(), R.layout.place_list_item);
        serialNumberTitle.setTypeface(typeface);
        timeTitle.setTypeface(typeface);
        distanceCoveredTitle.setTypeface(typeface);
        headerTextView.setTypeface(typeface);
        getDataTaskObj = new GetDataTask(getActivity());
     //   listView.setAdapter(adapter);
        if (android.os.Build.VERSION.SDK_INT >= 11) {
            // allows task to run parallely
            getDataTaskObj.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                    (Void[]) null);
        } else {
            getDataTaskObj.execute();
        }
        return rootView;
    }

    public class GetDataTask extends AsyncTask<Void, Void, Void> {
        Context context;
        Dialog dialog;

        // ProgressDialog progressDialog;

        public GetDataTask(Context context) {
            this.context = context;

            dialog = Utils.showValidationDialog(context, "Loading ...",
                    "Please wait ", false);

           // listDataArr = new ArrayList<ListData>();
        }

        @Override
        protected Void doInBackground(Void... params) {
            helper = new MyDbHelper(getActivity());

            Cursor cursor = helper.getAllLocationSavedCursor();
            //String myHexColor = "#CC2233";
            if (cursor.moveToFirst()) {
                do {

                    String number = cursor.getString(cursor.getColumnIndex("id"));
                    String duration = cursor.getString(cursor.getColumnIndex("UnixTimeStamp"));
                    String distance = cursor.getString(cursor.getColumnIndex("distance"));

                    adapter.add(new ListData(number, duration, distance));

                    //list.add(map);

                } while (cursor.moveToNext());
                cursor.close();
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (adapter != null && !adapter.isEmpty()) {
                listView.setAdapter(adapter);
                Toast.makeText(getActivity(), "Running trip data is here", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), "No History Found!!", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(aVoid);
        }
    }
}

Kindly let me know if anyone find something or if any more information is required.

A: Change the Linear layout of trip_history_Screen.xml . Use this
 <LinearLayout
>         android:id="@+id/titles_layout"
>         android:layout_width="match_parent"
>         android:layout_height="wrap_content"
>         android:layout_below="@+id/heading_layout"
>         android:orientation="horizontal"
>         android:weightSum="1.0">

Instead of this :
 <LinearLayout
        android:id="@+id/titles_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/heading_layout"
        android:orientation="horizontal"
        android:weightSum="1.0">


text:
Q: Why do I just get background music if I plug my headphones halfway in? This is weird. I plugged my headphones into the soundjack on the side of my Mac Air. I then go to Youtube and listen to a song, which sounds fine - I hear both the background music and the singing.
Then, I pull my headphones halfway out. The singing silences, but the background music is playing just fine. What is going on? Did I just find a cool way to hack background music for karoake?

A: I assume your plug has 3 contacts (stereo).
The first contact is the "Tip". This is (normally) for the "Right" channel signal.
The second contact is the "Ring" immediately next to the "Tip" contact. This is (normally) for the "Left" channel signal.
The third contact is the at the "base" of the plug, immediately next to the "Ring" contact. This is the "Common" (or "Ground") for both channels.
When you pull the plug partially out, the "Tip" contact on the plug becomes connected to the place the "Ring" contact is normally connected to, and the "Ring" contact is completely disconnected.  Sometimes in this situation, depending on the construction of the plug and jack, the "Ring" contact can remain connected to the "Left" channel signal while the "Tip" contact is also connected to the "Left" channel signal.
Since the "Common" ("Ground)" contact on the plug is typically fairly long, it will usually remain properly connected in this situation.
The effect of all this is that the sound on the "Right" channel is lost (disconnected), and the sound on the "Left" channel can be heard on the "Right" earpiece (or possibly both earpieces).
So, if the "Voice" was on the "Right" channel, and the background music was on the "Left" channel (or possibly both channels), then it would be normal (expected) to experience what you have described.

A: You experience this effect as a mix of the hardware and the audio mix.
Hardware
Your audio connector is most likely a stereo connection. There are two wires in your cable, and they are carrying an audio signal each, which is separated in the connected/plug. Have a look at the black stripe on the plug (or white, if it's an iPod headphone!).
By connecting halfway in, you're only getting one channel of that two channel audio stream. The wiki article on connectors explains the hardware nicely.
http://en.wikipedia.org/wiki/Phone_connector_(audio)
Audio Mix
Audio is typically mixed in stereo these days. It is still important for an audio engineer to consider the various audio environments, where many radios will be mono. This is curious in 2013 to see a lot of new models of radio units released with a single mono speaker. In this case, a stereo signal is summed as a mono signal. Both streams get squished together, in a fashion.
But largely, our stereo mixes exploit the stereo format to sound interesting. A large part of mixing audio is placement both in the left and right of the perceived audio environment, and forwards and backwards by use of things like reverb. The best mixes "place" audio in this three-dimension space effectively.
A quick example; for most radio-friendly music, the vocals are largely going to be in the center. Bass is as well, this is both another foundation element, and for reasons of phase and some fun legacies of the days of cutting records. But you will notice backing vocals, guitars, and drum kits are panned across the spectrum. Or even how old Beatles records would have really dramatic panning; entire instruments hard panned.
Imagine what happens with your signal when one of these channels drops?
What You're Hearing
When you only semi-patch the connection of a stereo signal, you're only getting part of that mix. Depending on the patching of your audio chain, this might be only that channel coming through, or else summing or inverting. Normalization affects the audio path as this other Wiki article introduces.
http://en.wikipedia.org/wiki/Patch_panel
But the effect you mention is likely a product of inversion. The following article shows how you might do this with an audio editor, and gives a general idea of what's happening. In your case, the center channel is being inverted.
http://www.howtogeek.com/56335/how-to-remove-vocals-from-music-tracks-using-audacity/

A: I had the same problem with quite a lot of my earphones, at first I thought they broke but then I found a way to solve the problem. If you are using a MAC, go to system preferences, sound settings, Output, and then fiddle around the balance. I put my balance point all the way to the left and everything started working again. Just watch something or listen to something while fiddling with the balance until you hear properly again. Hope this helps!

A: I had the same issue, got it resolved by following the below steps.
Connect your headset and make sure, you only hear music and not voice. Then proceed with these steps

*

*Click volume icon in the right side of Taskbar.

*Click the headset icon in the volume controller

*A dialog to set the properties of your headset will be shown.

*Click the tab named "Levels" in it.

*Click "Balance" button and adjust the second volume.

Now your can hear both music and voice


text:
Q: Comparing Functional Connectivity as measured by fMRI This question has been giving me a headache for a while so I'll define the problem before asking the question.
fMRI is a measure of Blood Oxygenation Level Dependent signal. Higher the blood oxygenation, higher the signal. Of course, there is noise and drift associated with the signal as well. The entire brain is imaged 185 times in our experiment, of which the first 5 volumes (measurements) are dropped. Each voxel (3D pixel) that makes up the 3D brain has a time-series associated with it, (consisting of 185 measurements).
Functional connectivity is defined as the temporal correlation between spatially remote neurophysiological events in the brain. Basically, correlation between two regions, say dlpfc-r and amy-l is the correlation coefficient between the time series of those two regions.
In our experiment, six subjects undergo two fMRI runs (resting state) pre and post treatment.
I extracted the time-series of the two regions of interest (ROIs) and computed the correlation coefficient between them for each subject to yield the functional connectivity pre and post treatment. I used Fisher's r-to-z transformation (http://vassarstats.net/rdiff.html) to get the p-value for the within subject (between visit) comparison. I did that for each ROI-pair for each subject (pre and post) and Bonferroni corrected it for multiple comparisons.
I need to generalize this result. How do I do a group comparison of correlation coefficients that will tell me if there is significant difference between pre and post for each ROI-pair, and in which direction? Thank you.

A: Since there are several major noise factors in the BOLD signal that should be modeled, I suggest using an fMRI analysis software rather than just extracting regions of interest. Conn is a very nice toolbox that has great options for motion correction etc. https://www.nitrc.org/projects/conn


text:
Q: Resize image view to fit image, not other way around I'm using XCode 6 to develop an application for OSX using Swift. In my window I have an image view which displays different images depending on which entry is selected in a table just above it. All of the images that can be displayed are the same width, but different height.
What I would like is for the image view (and the window!) to resize depending on which image is selected. I have no idea of how to do this in the Interface Builder (which is what I have used (bindings etc.) for most of my app), and can't find any tutorials/questions about it, since searching always gives results for how to resize images to fit an image view, not the other way around!
If you need any more specific information about my app, please just let me know what you need.
Edit:
There are currently no constraints at all on anything in my window, but the only way I can see to edit the content hugging and compression resistance priorities is to have at least one constraint on the image view. Hence the top space constraint to the search bar above.

A: Since you're using auto layout, you should make sure that the image view's Compression Resistance and Content Hugging priorities are both greater than 500 (which is NSLayoutPriorityWindowSizeStayPut). That way, changes to the image view's intrinsic content size will override the system's tendency to keep the window the same size.
It would probably be good to set the image view to do no scaling, too, but I'm not sure it's necessary.
Also, you need to make sure that your other constraints don't have the effect of fixing the size of the image view. Obviously, you should not have width or height constraints on the image view itself, but you also need everything else to be flexible enough to allow the image view to be any size. If you need help with that, you're going to have to show us the constraints within the window.


text:
Q: How to Invoke the IntPtr result of method_getImplementation The result of calling method_getImplementation(method) is an IntPtr.  How do I convert an IntPtr to a method?
[DllImport("/usr/lib/libobjc.dylib")]
extern static IntPtr method_getImplementation(IntPtr method);

public void SomeMethod
{
var method = class_getInstanceMethod(new UIViewController().ClassHandle, new Selector("viewWillAppear:").Handle);

IntPtr original_impl = method_getImplementation(method);
}

In obj-c:
IMP originalImp = method_setImplementation(method,swizzleImp);
originalImp(self,_cmd)

A: You need to use Marshal.GetDelegateForFunctionPointer and add [MonoNativeFunctionWrapper] to the delegate type:
[MonoNativeFunctionWrapper]
public delegate void ViewWillAppearDelegate (IntPtr self, IntPtr selector);

var del = (ViewWillAppearDelegate) Marshal.GetDelegateForFunctionPointer (original_impl, typeof (ViewWillAppearDelegate));
del (obj.Handle, Selector.GetHandle ("viewWillAppear"));


text:
Q: Flask app.run creates entity duplicates? I use a simple stack of Python (3.6.4), Flask (0.12.2), flask_admin (1.5.1) and flask_sqlalchemy (2.3.2). I chose SQLite as my DB.
The structure of my project is rather simple:
1) shared_db.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

2) models.py
from shared_db import db

class City(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

def fill_data(app):
    with app.app_context():
        db.create_all()
        db.session.add(City(name="Moscow"))
        db.session.add(City(name="New York"))
        db.session.add(City(name="London"))
        db.session.add(City(name="Paris"))
        db.session.commit()

3) model_views.py
from flask_admin.contrib.sqla import ModelView

from models import City

class CityView(ModelView):
    column_display_pk = True    # to force ids to appear in the Admin panel
    column_hide_backrefs = False
    column_list = ("id", "name")

def create_views(admin, db):
    admin.add_view(CityView(City, db.session))

4) app.py
import os

from flask_admin import Admin
from flask import Flask, jsonify, make_response, request

from shared_db import db
from models import fill_data
from model_views import create_views

app = Flask(__name__)
app.config["SECRET_KEY"] = "123456790"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////<path to the project>/myDB'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db.init_app(app)
fill_data(app)

admin = Admin(app, 'My app')
create_views(admin, db)

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)

Finally, I delete the myDB-file if it exists and I run the app with python3 app.py.
Surprisingly, eventually, I got 8 cities instead of 4! I perform some debug with DB Browser and find out that duplicated 4 cities creates right after the very last line of code - app.run(...) - executes.
How do I run the flask app correctly with a pre-filled database?

A: If you need to seed the database every time the app begins, you will want to make the act of populating the database idempotent. In other words, you need to check if the object already exists before you create it (because it is completely possibly for the app to restart when you have not deleted the database). This post might help you accomplish this behavior with SQLAlchemy.


text:
Q: How to load the google maps api
A: As of April 2021 Google has "made it easier to use the Maps JavaScript API in modern web apps" more details on their blog post: Loading Google Maps Platform JavaScript in Modern Web Applications.
This are the instructions for the Google Maps JavaScript API Loader library
import { Loader } from '@googlemaps/js-api-loader';

const loader = new Loader({
  apiKey: "",
  version: "weekly",
  libraries: ["places"]
});

const mapOptions = {
  center: {
    lat: 0,
    lng: 0
  },
  zoom: 4
};

// Promise
loader
  .load()
  .then((google) => {
    new google.maps.Map(document.getElementById("map"), mapOptions);
  })
  .catch(e => {
    // do something
  });

Or if you want, you can use the Google Maps JavaScript API React Wrapper library.

A: Yet another package react-dependent-script package to load Google Maps libraries, which provides the following features:

*

*ensure to load the JavaScript and/or CSS first, then render your
content

*ensures the external content is only loaded once, regardless of how
many times the render() function is called

Here is a simple example, where you wrap your map component in ReactDependentScript component:
<ReactDependentScript
      scripts={[
        "https://maps.googleapis.com/maps/api/js?key={YOUR-KEY-GOES-HERE}"
      ]}>
      <Map center={{ lat: -34.397, lng: 150.644 }} zoom={3} />
</ReactDependentScript>

Here is a demo  for your reference

A: Updates Oct 6, 2019: The example code is still working well, I have just updated them to use non-decorator syntax.

This is what I make it worked in my recent project. I used react-async-script-loader component.
import React from 'react';
import scriptLoader from 'react-async-script-loader';

class Maps extends React.Component {
  constructor(props) {
    super(props);
    this.map = null;
  }

  componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
    if (isScriptLoaded && !this.props.isScriptLoaded) {
      // load finished
      if (isScriptLoadSucceed) {
        this.map = new google.maps.Map(this.refs.map, {
          center: { lat: 10.794234, lng: 106.706541 },
          zoom: 20
        });

        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            position => {
              const pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
              };

              this.map.setCenter(pos);

              const marker = new google.maps.Marker({
                position: pos,
                map: this.map,
                title: 'Hello World!'
              });
            },
            () => {
              console.log('navigator disabled');
            }
          );
        } else {
          // Browser doesn't support Geolocation
          console.log('navigator disabled');
        }
      } else this.props.onError();
    }
  }

  render() {
    return (

        {!this.map &&
Loading...
}

    );
  }
}

export default scriptLoader(['https://maps.googleapis.com/maps/api/js?key=API_KEY'])(Maps);

A: Thanks Nguyen Thanh. As google now in global scope I used window.google.
import React, { Component } from 'react';
import scriptLoader from 'react-async-script-loader';
class Map extends Component{
    constructor(props) {
        super(props);
    }
    componentWillReceiveProps({isScriptLoadSucceed}){
        if (isScriptLoadSucceed) {
            var markers = [];

            var map = new window.google.maps.Map(document.getElementById('map'), {
                zoom: 12,
                center: {lat: 37.7749300, lng: -122.4194200}
            });
        }
        else{
            alert("script not loaded")
        }
    }

    render(){
        return(

        )
    }
}

export default scriptLoader(
    ["https://maps.googleapis.com/maps/api/js?key= APIKEY"]
)(Map)

With react hook we can also load external script

https://usehooks.com/useScript/

//useScript custom hooks from the site

let cachedScripts = [];

function useScript(src) {
  // Keeping track of script loaded and error state

  const [state, setState] = useState({
    loaded: false,
    error: false
  });

  useEffect(
    () => {
      // If cachedScripts array already includes src that means another instance ...
      // ... of this hook already loaded this script, so no need to load again.
      if (cachedScripts.includes(src)) {
        setState({
          loaded: true,

          error: false
        });
      } else {
        cachedScripts.push(src);
        // Create script
        let script = document.createElement("script");
        script.src = src;
        script.async = true;
        // Script event listener callbacks for load and error
        const onScriptLoad = () => {
          setState({
            loaded: true,
            error: false
          });
        };

        const onScriptError = () => {
          // Remove from cachedScripts we can try loading again
          const index = cachedScripts.indexOf(src);
          if (index >= 0) cachedScripts.splice(index, 1);
          script.remove();
          setState({
            loaded: true,
            error: true
          });
        };
        script.addEventListener("load", onScriptLoad);
        script.addEventListener("error", onScriptError);
        // Add script to document body
        document.body.appendChild(script);
        // Remove event listeners on cleanup
        return () => {
          script.removeEventListener("load", onScriptLoad);
          script.removeEventListener("error", onScriptError);
        };
      }
    },
    [src] // Only re-run effect if script src changes
  );
  return [state.loaded, state.error];
}

Usage
//App.js
import React from "react";
import ReactDOM from "react-dom";
import { useState, useEffect } from "react";
function App() {
  const [loaded, error] = useScript(
    "https://maps.googleapis.com/maps/api/js?key=API_KEY"
  );
  useEffect(() => {
    if (loaded) {
      new window.google.maps.Map(document.getElementById("map"), {
        zoom: 12,
        center: { lat: 37.77493, lng: -122.41942 }
      });
    }
  }, [loaded]);

  return (

        Script loaded: {loaded.toString()}

  );
}


text:
Q: What single board computer (SBC) solution would allow me to cut power instead of powering down? I'm building a circuit with a single on/off switch.
"On" turns on the circuit, which includes a SBC currently running on Windows that runs the GUI (Labview).
"Off" powers of the circuit, including the SBC.
I'd like to keep a single switch that turns everything "Off", without corrupting the computer memory / hard disk to ensure smooth startup each time. Is that possible and what solutions exist?

A: Buffer your board with an accu or an battery. As soon there are no changes anymore save your values. On bootup reload the saved values.


text:
Q: C#: Запуск Tasks в цикле Код:
    Task<RequestBodyModelDC>[] relatedObjectMapping = new Task<RequestBodyModelDC>[fields.Columns.Count];

    for (int i = 0; i < relatedObjectMapping.Count(); i++)
    {
        Task<RequestBodyModelDC> currTask = new Task<RequestBodyModelDC>(() =>
        {
            return FillMappingObkect(i, fields, entity);
        });

        relatedObjectMapping[i] = currTask;
        relatedObjectMapping[i].Start();
    }

Проблема в том, что в currTask каждый раз попадают последние данные из коллекции relatedObjectMapping, соответственно идет дублирование данных.
Подскажите, пожалуйста, как сделать так,чтобы в цикле при создании Таски в нее передавались актуальное значение параметра "i" в функцию FillMappingObkect!
Спасибо

A: Проблема в захвате переменной. Просто создайте переменную с ограниченной областью видимости и на каждой итерации цикла она будет своя:
for (int i = 0; i < relatedObjectMapping.Count(); i++)
{
    int localI = i;
    // Дальше везде используем localI вместо i


text:
Q: Can't authenticate via ssh key on new GitLab container I've recently set up a new GitLab docker container, and though everything else has been working great I can't authenticate to it via ssh.
I followed the instructions here to the letter, with no succes.
Whatever key type I generate, and regardless of the client (Linux, Windows git-bash), The server instantly rejects the publickey and does not prompt for a password.
Debug shows the following:
debug1: Offering public key: /c/Users/[user]/.ssh/id_ed25519 ED25519   SHA256:[SHA-256]
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51

Maybe it's something obvious, but I can't quite figure it out and no troubleshooting step managed to help.
As a side note, the ssh port is non standard, though I am accesing via the new port. I've also double checked ssh is enabled on both the server and the clients.
Any help would be greatly appreciated.
Thanks!

A: Check first if this is similar to gitlab-org/gitlab-foss issue 18371 "docker omnibus gitlab denying ssh public key"

In my case the problem was mismatch between ssh socket that docker container was exposing and my server's one.
It helped to expose it on different port like 10022 and reconfiguring gitlab like this:
gitlab_rails['gitlab_shell_ssh_port'] = 10022

Ideally, you would need to stop, restart the ssh daemon (server side, container side as seen in this thread) with
usr/sbin/sshd -d

That would allow you to check:

*

*if the SSH request is received at all

*if it is blocked for any reason


text:
Q: codeigniter - proper way to return data from API I'm trying to create an API.
I have a controller that does something, and returns let's say "ABC" as a string.
my url looks like this:
     http://myserver/myapp/myAPImethod/parm1

inside the method, I have code like this:
    header ('Content-Type: application/json; charset=UTF-8');
    $model= str_replace("%snv%"," ",$model);
    echo json_encode($model);

The application that consumes this API has a controller that does the following:
public function curl($url){
  //echo 'in the routine';
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data=curl_exec($ch);
    print_r($data);
    curl_close($ch);
    return $data;
  }
    $url = "http://myserver/myapp/index.php/myAPImethod/hname";
    $jsondata = $this->curl($url);
    //print_r(json_decode($jsondata));

My question is this:  When I run the application that consumes my API, because I have an echo statement, it shows "ABC" on the page.  But I don't want it to display the results.  I just want it to pass the data to the consuming application.  I've tried changing the echo statement in the API method to a "return" statement, but I don't get any data sent over to the caller.
Thanks.

A: Create a JSON view and pass data to the json view
// In view create a file json_view.php and paste this content

// RFC4627-compliant header
header('Content-type: application/json');

// Encode data
if(isset($response)) {
    echo json_encode($response);
}
else
    echo json_encode(array('error' => true));

And in your controller
// Build our view's data object
$data = array('response' => $response_data);
// Load the JSON view
$this->load->view('json_view', $data);


text:
Q: Add icon for specific tree items in Tree(CTreeCtrl) in MFC Can we add icons for specific tree items?
I am adding items with icon using following function:
HTREEITEM InsertItem(LPCTSTR lpszItem,int nImage,int nSelectedImage,HTREEITEM hParent = TVI_ROOT,HTREEITEM hInsertAfter = TVI_LAST);

To skip icon for an item, i am using -1 value for nImage and nSelectedImage. By doing this, icon is not appearing but space is coming.

A: Have you looked at CTreeCtrl::SetItem?
The easiest is to fill and pass a TVITEM structure.
typedef struct tagTVITEM {
  UINT      mask;
  HTREEITEM hItem;
  UINT      state;
  UINT      stateMask;
  LPTSTR    pszText;
  int       cchTextMax;
  int       iImage;
  int       iSelectedImage;
  int       cChildren;
  LPARAM    lParam;
} TVITEM, *LPTVITEM;

You set the mask to TVIF_IMAGE and specify the iImage value.
To begin, you need to create a CImageList object that stays valid for the duration of the CTreeCtrl. You usually add it to the class as a variable. Example:
m_imgList.Create(IDB_BMP_CHECK_IMAGELIST, 16, 10, 0x0000FF00);

Once it is initialised you can call CTreeCtrl::SetImageList. Example:
m_treeCtrl.SetImageList(&m_imgList, LVSIL_SMALL);

Thereafter you can use the image index values.


text:
Q: Selecting the current element when instantiating a JQuery widget I'm attempting to construct a dynamic URL for a JQuery auto complete widget, but I can't seem to find a way to reference the current element when I am instantiating the widget. $(this) and this reference the HTMLDocument object instead of the element which is currently having the widget instantiated, is there a way of changing this? Here is my code:
$(function()
{
    $(".autocomplete").autocomplete({
      source: baseUrl+"autocomplete/"+window.filter+"/"+$(this).attr("name"),
      minLength: 2
    });
}

This is the current URL that is created:

http://example.com/autocomplete/products/undefined?term=test

But it should be:

http://example.com/autocomplete/products/filter-name?term=test

Edit
Here is a JSFiddle

A: You're not inside a different scope, so this will refer to whatever it was already referring to.  You need to loop over each .autocomplete element:
$(".autocomplete").each(function(i, e) {
    //both "e" and "this" now refer to the element
    $(e).autocomplete({
      source: baseUrl+"autocomplete/"+window.filter+"/"+ $(e).attr("name"),
      minLength: 2
    });
});

A: In your code, this refers to the document object, which doesn't have a name property, hence the error you are seeing.
You need to initialize the autocomplete differently:
var filter = "products";
$(".autocomplete").each(function(i, el) {
  $(el).autocomplete({
    source: "http://example.com/autocomplete/" + filter + "/" + el.name,
    minLength: 2
  });
});

And that should work.


text:
Q: plotly.py layout images - hover events In plotly python, is it possible to trigger a hover event for images in your plot? I have a plot with a layout image. I would like to detect if the user hovers the mouse over the image.
example plot with image:
fig = go.Figure()

fig.add_trace(
    go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1])
)

fig.add_layout_image(
        dict(
            source="https://images.plot.ly/language-icons/api-home/python-logo.png",
            xref="x",
            yref="y",
            x=0,
            y=3,
            sizex=2,
            sizey=2,
            sizing="stretch",
            opacity=0.5,
            layer="below")
)

fig.show()

References:
• I've found hover events for plotly.js: https://plotly.com/javascript/hover-events/
• I see a hover example here: https://plotly.com/python/v3/cars-exploration/
but it does not work the way I intend, but perhaps it can be?
scatter = fig.data[0]

def hover_fn(trace, points, state):
    ind = points.point_inds[0]
    details.value = cars_df.iloc[ind].to_frame().to_html()

scatter.on_hover(hover_fn)

For instance, can I call something like:
def hover_fn():
   print("hello world")

my_image = fig.data[layout_image]
my_image.on_hover(hover_fn)

A: I'm going to start out with code and explanation; at the end of this answer, I've added all of the code again in one chunk.
As far as I know, as long as it's a layout object, there is no simple method of instituting hover content. If you would like hover content, then instead of a layout object, make it a trace.
There is one major difference between images in the layout and images in a trace. In a trace, you have to encode the image to base64. When it's in the layout, Plotly does it for you. (Why?? GREAT QUESTION!!! I can tell you it's the same in other programming languages.)
The first step: encode the image for the trace.
import plotly.graph_objects as go
import base64
from io import BytesIO
from urllib.request import urlopen

# read url
url = urlopen("https://images.plot.ly/language-icons/api-home/python-logo.png")
pref = "data:image/png;base64," # prefix for Javascript
# transcribe binary bytes into base64 UTF-8
aimg = pref + base64.b64encode((BytesIO(url.read())).getvalue()).decode('utf8')

When you add images as a trace, it automatically flips the y-axis. So, to prevent issues with the other trace, I have annotated a second y-axis.
fig = go.Figure().set_subplots(specs = [[{"secondary_y": True}]])

The traces. By the way, the order in which you code them is the order they are layered. So if you want the image on the bottom, add that trace first.
fig.add_trace(
    go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]),
    secondary_y = False
)
# size of image 100 x 100 with dx & dy at .03, reduce size to 3% of original
fig.add_trace(go.Image(source = aimg, x0 = 0, y0 = 0, dx = .03, dy = .03,
                       opacity = .5, hoverinfo = "all", zsmooth = 'fast',
                       name = "Python symbol"),
              secondary_y = True)

So that the image isn't skewed and the different axes are all aligned, I've added specifications for the axes to square it all up. I also hid the labels for the second y-axis.
fig.update_xaxes(range = [-.5, 3.5], constrain = "domain")
fig.update_yaxes(scaleanchor = "x", scaleratio = 1,
                 secondary_y = False, range = [-.5, 3.5])
fig.update_yaxes(title = "", secondary_y = True, scaleratio = 1, scaleanchor = "x",
                 showticklabels = False, range = [3.5, -.5])

All the code altogether:
import plotly.graph_objects as go
import base64
from io import BytesIO
from urllib.request import urlopen

# read url
url = urlopen("https://images.plot.ly/language-icons/api-home/python-logo.png")
pref = "data:image/png;base64," # prefix for Javascript
# transcribe binary bytes into base64 UTF-8
aimg = pref + base64.b64encode((BytesIO(url.read())).getvalue()).decode('utf8')

fig = go.Figure().set_subplots(specs = [[{"secondary_y": True}]])

fig.add_trace(
    go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]),
    secondary_y = False
)

fig.add_trace(go.Image(source = aimg, x0 = 0, y0 = 0, dx = .03, dy = .03,
                       opacity = .5, hoverinfo = "all", zsmooth = 'fast',
                       name = "Python symbol"),
              secondary_y = True)

fig.update_xaxes(range = [-.5, 3.5], constrain = "domain")
fig.update_yaxes(scaleanchor = "x", scaleratio = 1,
                 secondary_y = False, range = [-.5, 3.5])
fig.update_yaxes(title = "", secondary_y = True, scaleratio = 1, scaleanchor = "x",
                 showticklabels = False, range = [3.5, -.5])

fig.show()


text:
Q: How to calculate the probability that a set of data came from a CONTINUOUS probability distribution? I know that if you have a set of data, say $data=(x_1,x_2,x_3,...,x_n)$ that you think came from a discrete distribution, you can calculate the probability of that data occurring by just multiplying the PDF. e.g.:
if:$$data \sim binomial(n,p) = p(x)$$
then the probability of some $data=(x_1,x_2,x_3,...,x_n)$, would be:
$$prob(data|binomial(n,p)) = p(x_1)p(x_2)...p(x_n)=\prod_i p(x_i)$$
However, how do you do the same thing for a continuous distribution? If the probability at any given point is $0$, then the probability that data existed at exactly a single point is $0$ and thus $prob(data|distribution)=0$. The best you could do is say the probability is some value $p(x_i)dx$, but this is still infinitesimally small.
It is my understanding that in order for a continuous distribution to "behave" well as a measure on some sigma algebra, it cannot have a probability associated with a single point.
Could someone help me understand where my logic is flawed?

A: Don't see any flaw in your logic. The probability of getting the observed data is zero, but that's okay.


text:
Q: checking inline value is exists, set to object property in declaring object _ JavaScript suppose we want to create a new object.
let myObject = {};

and we have some property that exists in another object like :
let b = { foo: "bar"};

is it possible to check if b?.foo append foo to myObject inline in the declaration of the object?
something like this :
let myObject = { b?.foo }

A: I think the best you can do is :
let myObject = {
  some: "prop",
  ...(b?.foo && {foo:b.foo})
}

Or if you want to pass all the object
let myObject = {
  some: "prop",
  ...(b?.foo && b)
}


text:
Q: Exterior Power of a Vector Space Let $G$ be a finite group, $V$ an $n$-dimensional vector space over $\mathbb{C}$, and $\tau: G \rightarrow GL(V)$ a representation such that $\tau(g)$ has determinant 1 for all $g \in G$. Why is it that $\wedge^{n}(V) = \mathbb{C}$?

A: An element $g\in G$ acts on $\Lambda^bV$ by multiplication by $\det\tau(g)$, which is $1$.
Indeed, let $B=\{v_1,\dots,v_n\}$ is a basis of $V$ and suppose $g\cdot v_i=\sum_{j=1}^ng_{i,j}v_j$ for each $i\in\{1,\dots,n\}$, so that the matrix $(g_{i,j})_{1\leq i,j\leq n}$ is the matrix of $\tau(g)$ with respect to the basis $B$. The element $\omega=v_1\wedge\cdots\wedge v_n\in\Lambda^nV$ is a non-zero element in that $1$-dimensional space, so that $\{\omega\}$ is a basis of $\Lambda^nV$, and
\begin{align}
g\cdot\omega&=g\cdot v_1\wedge\cdots\wedge v_n\\
&=(g\cdot v_1)\wedge\cdots\wedge(g\cdot v_n)\\
&=\sum_{1\leq i_1,i_2,\dots,i_n\leq n}(g_{1,i_1}v_{i_1})\wedge\cdots\wedge (g_{n,i_n}v_{i_n})\\
&= \det(\tau(g)) \omega
\end{align}
Of course, one needs to justify the last equality. We start by rewriting the sum as $$\sum_{1\leq i_1,i_2,\dots,i_n\leq n}g_{1,i_1}\cdots g_{n,i_n}\;v_{i_1}\wedge\cdots\wedge v_{i_n}.$$ A term corresponding to a choice of $i_1$, $\dots$, $i_n$ in which we have repetitions is zero, so we can sum only over the choices of $i_1$, $\dots$, $i_n$ for which $(i_1,\dots,i_n)$ is a permutation of $(1,2,\dots,n)$, which we call $\pi$. If that is the case, then one should know that $$v_{i_1}\wedge\cdots\wedge v_{i_n}=\operatorname{sgn}(\pi)\;v_1\wedge\cdots\wedge v_n.$$ Doing this in all terms, we see that the sum is in fact equal to $\det(\tau(g))\;\omega$, in view of the definition of the determinant as a sum over permutations.

A: It is not strictly true that $\Lambda^n V=\mathbb C$, but only that $\Lambda^n V$ is a $1$-dimensional complex vector space.
However the automorphism $\tau_g:V\to V$ has an $n$-th exterior power   which is an endomorphism
$\Lambda^n (\tau_g):\Lambda^n V\to \Lambda^n V$ of a  one-dimensional vector space and thus is multiplication by a  complex number . That number is $det (\tau_g)\in \mathbb C$.
Note
At the level of elementary representation theory, it is permissible to be more down-to-earth and identify $V$ with $\mathbb C^n$, $GL(V)$ with $GL_n(\mathbb C)$, $\Lambda^n V$ with $\mathbb C$, etc.
However once you study more advanced material, that sort of confusion will lead to disaster: for example if $V$ is a rank-$n$ vector bundle, it is a terrible  mistake   to think that its determinant bundle is the trivial bundle with fibre $\mathbb C$.
So I encourage you to try and progressively learn the more canonical view as soon as possible.


text:
Q: Simple redirection after a submit from formBuilder I can not redirect the user after a connection
Here is my code:
    public function indexAction(Request $request) {

    $css = array('class' => 'form-control');
    $btn = array('class' => 'btn btn-info btn-raised', 'value' => 'Valider');

    $formulaire = $this->createFormBuilder()
            ->add('login', 'text', array('label' => 'Identifiant', 'attr' => $css))
            ->add('pwd', 'password', array('label' => 'Mot de passe', 'attr' => $css))
            ->add('submit', 'submit', array('attr' => $btn))
            ->getForm();

    $formulaire->handleRequest($request);

    if ($formulaire->isValid()) {
        $data = $formulaire->getData();
        $this->authentificationAction($data);
    }
    return $this->render('GestUtilisateursBundle:Auth:index.html.twig', array('leFormulaire' => $formulaire->createView()));
}

public function authentificationAction($data) {

    $login = $data['login'];
    $pwd = sha1($data['pwd']);

    $dataConnect = array('login' => $login, 'pwd' => $pwd);
    $orderBy = null;
    $em = $this->getDoctrine()->getManager();
    $visiteur = $em->getRepository('GestUtilisateursBundle:Visiteur')->findBy($dataConnect, $orderBy, 1, 0);
    var_dump($visiteur);
    //Si on ne trouve pas le visiteur
    if (!$visiteur) {
        throw $this->createNotFoundException('Identifiant ou mot de passe incorrect');
    }
    $session = $this->getRequest()->getSession();
    $session->set('visiteur', $visiteur);

    return $this->redirectToRoute('gsb_gest_utilisateurs_home');

}

My route gsb_gest_utilisateurs_home routing on that :
    public function indexAction() {

    $session = $this->getRequest()->getSession();
    $visiteur = $session->get('visiteur');
    return $this->render('GestUtilisateursBundle::layout.html.twig', array('visiteur' => $visiteur));
}

My routing.yml :
gsb_gest_utilisateurs_homepage:
path: /
defaults: { _controller: GSBGestUtilisateursBundle:Auth:index }

gsb_gest_utilisateurs_home:
path: /home
defaults: { _controller: GSBGestUtilisateursBundle:Home:index }

By executing this code, I have no issues, I put the information on the form to submit Doctrine send me the object, its working.
Only it updates the index page, so I would bring on the layout template while keeping the variables twig for later
And I do not understand why it does not work
Then in case of error login / pwd, I wish I could put a little warning on the index page and I tried to do {if error } in Twig with the addition of $error in the template but nothing appears
I hope someone can help, it's important and sorry for my english
Thanks

A: Since you're returning a RedirectResponse simply calling another method in your class wont do much, you have to use the return keyword yet again. Try it like that, if your form passes validation:
if ($formulaire->isValid()) {
    $data = $formulaire->getData();

    // notice the return here.
    return $this->authentificationAction($data);
}

Symfony's cookbook, has really good chapter about security and form logins. Give it a read here.


text:
Q: Does linux "clock()" function count in "sleep" time of a process? I called "sleep" functions, but seems not really counted, like this:
#include<iostream>
#include<unistd.h>
#include<time.h>
using namespace std;
int main(){
    clock_t t1=clock();
    sleep(2);
    clock_t t2=clock();
    cout<<t2-t1<<endl;
    return 0;
}

It prints a very small number of millisecond time interval between 2 "clock()" calls. I expected that it should report 2,000,000.
Is my guess correct? man page doesn't specify any answer to my question. Is there a better function to get the time elapsed between 2 lines of code?

A: clock(3) doesn't return seconds, it returns the number of seconds used, divided by CLOCKS_PER_SEC (value 1000000).
In C++, you probably want to use
auto t1 = std::chrono::system_clock::now();
sleep(2)
auto t2 = std::chrono::system_clock::now();
auto duration = t2 - t1;
std::cout << duration.count() << endl;

Don't forget to compile with -std=c++11


text:
Q: Pandas DataFrame row wise comparison I have a pandas DataFrame like following.
       id  label_x label_y
0        1    F    R
1        2    F    F
2        3    F    F
3        4    F    F
4        5    F    F

Now I want to count occurrences of label_x and label_y are equal and not equal. In this case there is only one occurrence of not equal and 4 occurrences of equal.
df = pd.DataFrame({'id' : ["1","2","3","4","5"],
                'label_x'  : ["F","F","F","F","F"], 'label_y' : ["R","F","F","F","F"]})

A: (df.label_x == df.label_y).value_counts()

Many ways to to that, including the above...
In [43]: (df.label_x == df.label_y).value_counts()
Out[43]:
True     4
False    1
dtype: int64

A: I came up with this solution. Is that the best one?
def compare(x):
    if x[1] == x[2]:
        return 'yes'
    else:
        return 'no'

df['result'] =  df.apply(compare, axis=1)

df2 = pd.DataFrame({'count' : df.groupby( ["result"] ).size()}).reset_index()


text:
Q: Why was trench so thin if they knew Wights can't pass it? In the latest Game of Thrones episode (S08E03), it was shown that a trench was set on fire to prevent Wights from climbing the wall.
If they knew, they could build a wide trench to stop the Wights and could have killed all the stationary ones using dragons.

A: Time and manpower were certainly factors. It takes a lot of time to dig a ditch, especially if the ground is frozen (and it is winter in the episode). You would also need more firewood to fill a wider trench - and remember that freshly felled trees don't make for very good firewood, unless there has been an extensive drought to dry out the wood. I imagine that basically all the stored firewood in Winterfell was used to fill the trenches.
As for using dragons to kill the stationary wights, that was done, but Dany and Jon chose to hunt the undead dragon rather than continue to do so - probably in an attempt to kill the Night King, who was riding that dragon at least some of the time. Also remember that dragons aren't invulnerable. The Night King killed and turned one, and another was nearly killed by a ballista in an earlier episode when Dany attacked a Lannister supply train. This suggests that using dragons in care should be done with care - more hit and run than steady attacks.

A: There's a lot of logistical problems to your question. Not sure there's a stated in-universe answer so we have to apply logic instead.

*

*how many shovels do they have to equip diggers? Do diggers without tools help enough to matter?  Even improvised tools will slow the pace considerably.

*what happens to diggers digging (and tired) if the wights show up while they're working?

*the ditch wasn't the barrier, the fire was. How much fuel can they supply to create continuous flame along the whole trench, that also burns large and long enough to matter?  Fuel doesn't burn forever.

*To be clear, you're talking about 100m wide and in a circle all the way around Winterfell. For easy numbers, let's say you want to place the trench 1/2 mile from the center of Winterfell (I'm not counting pixels to figure out how far away it actually was), that means you're digging a trench that's 3.14 miles long. I don't know how deep, let's call it 2m deep. That works out to about 5000 m x 100m x 2m, or about 1 million cubic meters of dirt and rocks. Moved by hand.  In an unspecified amount of time.
a. Digging in a bit more, I found modern shovels are non-standard, but a home improvement Q&A site (not a SE site, sadly) claims that a reasonable estimate is in the 135-162 shovel-fulls to fill a cubic yard, which for our purposes is close enough to a cubic meter.
b.  If we err a little on the high side and say that's 160 shovel-fulls per cubic meter of material (not accounting for partial fillage and such due to rocks, roots, etc), that tells us it'd take 160 million shovel-fulls to move enough dirt for a 100m-wide trench w/ a 1/2mile radius.
c.  According to the Canadian Center for Occupational Health and Safety the recommended rate for sustained shoveling is around 15 scoops per minute, but you shouldn't go more than 15 minutes w/o a break.  I think given the situation, we can forego the safety concerns with going longer than 15 minutes w/o a break, and to make the math slightly easier let's say it's 16 scoops per person-minute of work.  That works out to 10 M person-minutes of work, or 166,666.67 person-hours, not including breaks or the like.  Again, this assumes all your diggers have actual metal shovels that do not break.  We really are working off best-case numbers here.
d.  According a disturbingly well informed person on digging a grave a standard grave (6'deep x 5' wide, x 6.5' long) should take 6 hours on optimal soil conditions, which the frozen north probably was not.
As with most real-world battles the "why didn't they X?" question almost always comes down to intel or logistics. And those are most often gated by time and manpower.


text:
Q: Populate Jenkins changes with diff between current tag and last tag I have a Jenkins multibranch pipeline that is building releases that are tagged.  The issue is that nothing currently registers any changes for the build, since each tag is a single build/deploy.
How do I:

*

*Make changes to the Jenkins changes feature form within the Pipeline

*Figure out the branch name for the previous release and run a git diff to get the list of commits.

*Take those git diff commit messages and set them to the Changes in Jenkins.

Ideally for #2 I would want to skip pre-release tags, ex. If I am releasing 1.1.0-rc1 it should dhow a diff between it and 1.0.9 (the latest release before 1.1.0*)
Is the "changes" feature I mention above also called "changeset"?


text:
Q: Async Function Not refreshing This function works for a single data item but it should keep refreshing every few seconds.  How does this repeat?

   async function get_iss() {
       const response = await fetch('https://api.wheretheiss.at/v1/satellites/25544');
       const data = await response.json();
       document.getElementById("ISSdata").innerHTML = data.altitude;
       Textbox1.value = data.longitude;
       Textbox2.value = data.latitude;
   }
   get_iss();>

A:

async function getIss() {
  // make request
  const response = await fetch('https://api.wheretheiss.at/v1/satellites/25544');
  const data = await response.json();
  // update UI
  document.getElementById("altitude").textContent = data.altitude;
  document.getElementById("lat").textContent = data.latitude;
  document.getElementById("lng").textContent = data.longitude;
}

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("Starting requesting data...");
  // load data once
  getIss()
  // define interval
  const seconds = 2;
  // execute the function every x seconds (safe interval ID so we can stop the interval later)
  const interval = setInterval(getIss, seconds * 1000)

  // stop after 10 seconds here (just to not go overboard with requests here, you might not need this)
  setTimeout(() => {
    clearInterval(interval);
    console.log("Stopped requesting data.")
  }, 10 * 1000)
});

  Altitude:

  Lat:

  Lng: