text:
Q: OnItemClickListener Navigation Drawer I am making an app from the example of Android Developers with the Navigation Drawer. I made the items but I don't know how I can open new Activity from each of items enlisted.
This is the MainActivity:
public class MainActivity extends Activity {

private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mGalaxyTitles;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();
    mGalaxyTitles = getResources().getStringArray(R.array.Galaxys_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item, mGalaxyTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(
            this,
            mDrawerLayout,
            R.drawable.ic_drawer,
            R.string.drawer_open,
            R.string.drawer_close
            ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch(item.getItemId()) {
    case R.id.action_websearch:
        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());

        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

  private  class DrawerItemClickListener implements ListView.OnItemClickListener {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub

    }

}
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    switch(position) {
    case 1:
            Intent a = new Intent(MainActivity.this, Page1.class);
            startActivity(a);
    break;
    case 2:
            Intent b = new Intent(MainActivity.this, Page2.class);
           startActivity(b);
           break;
    default:
    }
    }

private void selectItem(int position) {

    Fragment fragment = new GalaxyFragment();
    Bundle args = new Bundle();
    args.putInt(GalaxyFragment.ARG_Galaxy_NUMBER, position);
    fragment.setArguments(args);

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    mDrawerList.setItemChecked(position, true);
    setTitle(mGalaxyTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    mDrawerToggle.onConfigurationChanged(newConfig);
}

public static class GalaxyFragment extends Fragment {
    public static final String ARG_Galaxy_NUMBER = "Galaxy_number";

    public GalaxyFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_Galaxy, container, false);
        int i = getArguments().getInt(ARG_Galaxy_NUMBER);
        String Galaxy = getResources().getStringArray(R.array.Galaxys_array)[i];

        int imageId = getResources().getIdentifier(Galaxy.toLowerCase(Locale.getDefault()),
                        "drawable", getActivity().getPackageName());
        ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
        getActivity().setTitle(Galaxy);
        return rootView;
    }
}
}

And a Drawer List.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:textIsSelectable="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textColor="#fff"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

The click on the items don't call others activities, what is the mistake?

A: Instead of your code:
private void selectItem(int position) {

    Fragment fragment = new GalaxyFragment();
    Bundle args = new Bundle();
    args.putInt(GalaxyFragment.ARG_Galaxy_NUMBER, position);
    fragment.setArguments(args);

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    mDrawerList.setItemChecked(position, true);
    setTitle(mGalaxyTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

Use this code:
private void selectItem(int position) {
    switch(position) {
    case 1:
            Intent a = new Intent(MainActivity.this, Activity1.class);
            startActivity(a);
    break;
    case 2:
            Intent b = new Intent(MainActivity.this, Activity2.class);
           startActivity(b);
           break;
    default:
    }
}

And remove this part: (It is not necessary)
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

switch(position) {
case 1:
        Intent a = new Intent(MainActivity.this, Page1.class);
        startActivity(a);
break;
case 2:
        Intent b = new Intent(MainActivity.this, Page2.class);
       startActivity(b);
       break;
default:
}
}

A: Instead of using Activities just use a fragment and A fragment Manager to transition between them

A: Use Like that
 switch (position) {

            case 0:
                fragment = new Free();

                break;
            case 1:
               fragment  = new Manage();

                break;
            case 2:
              fragment = new Paid();

                break;
            case 3:
                fragment = new Categories();

                break;
            case 4:
             logout();

                break;
            default:
                break;
        }

A: switch(position) {
    case 1:
        Intent a = new Intent(Book.this, SecondActivity.class);
        startActivity(a);
        break;
    case 2:
        Intent b = new Intent(Book.this, ThirdActivity.class);
        startActivity(b);
        break;
    default:
}

A: In manifest  you write this code:
<activity
    android:name=".firstactivity"
    android:parentActivityName=".MainActivity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity"/>
</activity>

In Main activity:
Intent i=new Intent(MainActivity.this,firstactivity.class);
startActivity(i);

A:  private class DrawerItemClickListener implements ListView.OnItemClickListener
 {
 @Override
     public void onItemClick(AdapterView<?> parent, View view, int position, long id)
     {
         SelectItem(position);
     }
  }


text:
Q: How do I get a RTL8125 2.5GbE Controller working on 18.04 LTS Is there some thing I can search for and install via apt-get or something similar to get my RTL8125 2.5GbE Controller working on Ubuntu 18.04 LTS

A: RTL8125 is supported natively by kernel 5.4.
In a little over a month, you will be able to switch to Ubuntu 20.04 LTS with this kernel version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the direction of curve at the point $(0,0)$ Find the direction of $y= x/(1+x^2)$ at the point $(0,0)$.
I couldn't find the solution of the questions asked here. Really thankful for your kind helpfulness.

A: Not sure if i get you right but if you mean the tangent of the set of points fullfilling your equation the direction at $0,0$ is
$$
(1, \frac{d y}{d x}(1))
$$


text:
Q: Automatically export a change log from a shared Excel workbook upon un-sharing it I have a shared workbook on my organization's network share drive which is edited by a few dozen individuals. About once a week, I need to take it out of "Shared" mode (let's call this "un-sharing") to do run some advanced operations on the data input by these editors, and make changes that require me to unprotect the worksheet/workbook. Also, I occasionally have to perform maintenance on the VBA code in the workbook, which also requires me to un-share the workbook.
The problem is that every time I un-share, it erases the internal track-changes history. I would like to automate exporting this history to an external change-log file, otherwise saving the change history every time requires cumbersome and time-consuming manual effort.

A: After poking around the internet trying to find a way to access Excel's internal change history and coming up with nothing, I settled on this solution that utilizes Excel's Highlight Changes option to temporarily create a "History" sheet, then append the changes listed on that sheet to a csv file. I also tried to make it relatively reusable and modular:
'My function that disables workbook sharing
Function UnshareWkbk(wkbk as Workbook) as Boolean
    on Error goto errUnshare
    'If Sharing is already disabled, return TRUE and exit
    If Not (wkbk.MultiUserEditing) Then
        UnshareWkbk = True
        Exit Function
    Else
        'Sharing is enabled, unshare the workbook here
        Application.DisplayAlerts = False

        'If we are about to Unshare, we need to export the change log first
        Call ExportChangeLog(ThisWorkbook, "1/1/1900")

        'Go ahead and Unshare the workbook, it's safe to erase the change history
        wkbk.ExclusiveAccess
        Application.DisplayAlerts = True
    End If

    'Make sure it worked and return TRUE
    If Not (ThisWorkbook.MultiUserEditing) Then UnshareWkbk = True
    Exit Function

errUnshare:
    '[add your own error handling here as applicable]
    Application.DisplayAlerts = True
End Function

'Export changes from workbook from selected date to present
Sub ExportChangeLog(wkbk As Workbook, fromDate As Date)
    Dim rng As Range, rw As Range
    Dim logFile As Integer, logPath As String
    Dim isNewFile As Boolean, fileIsOpen As Boolean
    Dim errStr As String

    On Error GoTo changeLogErr

    With wkbk
        'If the workbook is open in read only mode then we don't need to save
        'the changelog since the change history won't be erased
        If wkbk.ReadOnly Then GoTo endExportLog

        'Create History sheet for changelog using Excel's Hightlight Changes procedure
        .HighlightChangesOptions When:=Format(fromDate, "m/d/yyyy")
        .ListChangesOnNewSheet = True
        .HighlightChangesOnScreen = False

        'If a History sheet is not created that means there have been no changes since
        'the chosen date, so go ahead and skip this procedure.
        On Error GoTo endExportLog

        With .Sheets("History")
            On Error GoTo changeLogErr
            .Activate

            'Set rng to just the actual changes in the change log, ignoring the extra data
            'output by Excel in the History worksheet and the headers
            'Note: you may care about this additional data, I do not
            On Error Resume Next
            Set rng = .UsedRange.Resize(.UsedRange.Rows.Count - 3).Offset(1)
            Set rng = rng.Resize(rng.Rows.Count, rng.Columns.Count - 3).Offset(0, 1)
            On Error GoTo changeLogErr

            'If no rng is set, the History sheet was created but there were no
            'changes... this shouldn't happen, but just in case I've added this
            'code which will skip this procedure
            If rng Is Nothing Then GoTo endExportLog
        End With

        'Move view away from the History sheet
        .Sheets(1).Activate
    End With

    'Initialize the log file
    logPath = wkbk.Path & "\changelog.csv"
    logFile = FreeFile  'Next available file number

    'If the file doesn't currently exist, set isNewFile to TRUE
    isNewFile = Dir(logPath) = ""

    Open logPath For Append As logFile

    'If we've made it here then the log file is ready to be written to
    fileIsOpen = True

    'Print table headers if the file doesn't yet exist
    If isNewFile Then
        'If you changed the rng selection above, you may need to update the
        'table headers here:
        Print #logFile, "DATE,TIME,WHO,CHANGE,SHEET,RANGE,NEW VALUE,OLD VALUE"
    End If

    'For each row in the change log, write to the CSV
    For Each rw In rng.Rows
        Print #logFile, RangeToCSV(rw)
    Next rw

    'UNTESTED, but you should be able to replace the above for loop with this*
    'Print #logFile, RangeToCSV(rng)

endExportLog:
    On Error Resume Next
    'Save and close changelog
    If fileIsOpen Then Close #logFile
    Set rng = Nothing: Set rw = Nothing
    Exit Sub

changeLogErr:
    errStr = "ERROR #" & Err.Number & " - " & Err.Description
    msgbox errStr
    On Error Resume Next
    'If an error happened after preparing the log file, we can also log the error there
    if fileIsOpen then Print #logFile, "ERROR," & Format(Now(), "YYYY.MM.DD_hhmm") & "," & errStr
    Resume endExportLog
End Sub

'Convert a given range (1D or 2D) to CSV and return as a string
Function RangeToCSV(ByRef rng As Range) As String
    Dim arr() As Variant, strArr() As String
    Dim outputStr As String, i As Long, j As Long

    'If only one cell in rng, return just that cell's value
    If rng.Cells.Count = 1 Then
        RangeToCSV = rng.Value2
        GoTo endRngToCSV
    End If

    'Store values of range to array
    arr() = rng.Value2
    ReDim strArr(0 To UBound(arr, 2) - 1)

    'More than 1 row of data, add vbnewline between csv rows
    If rng.Rows.Count > 1 Then
        For j = LBound(arr, 1) To UBound(arr, 1)
            For i = LBound(arr, 2) To UBound(arr, 2)
                strArr(i - 1) = Replace(arr(j, i), ",", ".")
            Next i
            outputStr = IIf(j = 1, Join(strArr, ","), outputStr & vbNewLine & Join(strArr, ","))
        Next j
    Else
        'Only one row of csv data
        For i = LBound(arr, 2) To UBound(arr, 2)
            strArr(i - 1) = Replace(arr(1, i), ",", ".")
        Next i
        outputStr = Join(strArr, ",")
    End If

    'Return CSV output
    RangeToCSV = outputStr

endRngToCSV:
    'Clean up
    On Error Resume Next
    Erase arr: Erase strArr: Set rng = Nothing: outputStr = ""
End Function

*I originally wrote the RangeToCSV function to only work with single rows of data, hence the for each rw loop in the ExportChangeLog procedure


text:
Q: DataGrid SelectionUnit=Cell disables all support for a selected row? .Net 4 WPF DataGrid C# MMVM
When the DataGrid SelectionUnit is full row, wpf databinding and the collectionview take care of letting me know in the viewmodel what is the actively selected item via the view's currentitem property. This works great for readonly grids with the selection mode set to the fullrow.
Now I have an editable grid. So I set the SelectionUnit=Cell to make it easier to spot which cell one is in. Now all of a sudden the grid no longer has any ability to track the selection item.  I can't even set SelectedItem when set to cell mode.  So now the viewmodel always thinks it's on the first row. I can handle SelectedCellsChanged in the grid to figure out what row I'm on, I just have no way of letting the viewmodel know since the grid's SelectedItem can no longer be set!
I don't understand why the grid can't still have a SelectedItem when in cell select mode.
Short of hardcoding into my grid to cast the ItemSource to my collectionview to call MoveCurrentTo from the SelectedCellsChanged event, is there any other MVVM true way to keep the view's CurrentItem in sync with the grid?
Either that, or I change the grid style to remove or reduce the row highlight effect when I have an editable grid.

A: I was searching for the same problems and found a simple solution
To access to the row with SelectionUnit set to Cell you have to do:
DataGridXX.SelectedCells[0].item

It works only if you can select only one cell at time (not in Extended mode).

A: I found a great solution for this on MSDN using attached properties:
<DataGrid ItemsSource="{Binding}" IsReadOnly="True" SelectionUnit="Cell">
  <DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
      <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
          <Setter Property="local:DataGridAttachedProperties.IsCellSelected" Value="True"/>
        </Trigger>
        <Trigger Property="IsSelected" Value="False">
          <Setter Property="local:DataGridAttachedProperties.IsCellSelected" Value="False"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </DataGrid.CellStyle>
  <DataGrid.ItemContainerStyle>
    <Style TargetType="{x:Type DataGridRow}">
      <Style.Triggers>
        <Trigger Property="local:DataGridAttachedProperties.IsCellSelected" Value="True">
          <Setter Property="BorderThickness" Value="2"/>
          <Setter Property="BorderBrush" Value="Red"/>
          <Setter Property="Background" Value="Yellow"/>
          <Setter Property="Opacity" Value="0.7"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </DataGrid.ItemContainerStyle>
</DataGrid>

And the C#:
public class DataGridAttachedProperties
{
    public static bool GetIsCellSelected(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsCellSelectedProperty);
    }
    public static void SetIsCellSelected(DependencyObject obj, bool value)
    {
        obj.SetValue(IsCellSelectedProperty, value);
    }
    public static readonly DependencyProperty IsCellSelectedProperty =
        DependencyProperty.RegisterAttached("IsCellSelected", typeof(bool), typeof(DataGridAttachedProperties), new UIPropertyMetadata(false,
        (o, e) =>
        {
            if (o is DataGridCell)
            {
                DataGridRow row = VisualTreeHelperEx.FindVisualParent<DataGridRow>(o as DataGridCell);
                row.SetValue(DataGridAttachedProperties.IsCellSelectedProperty, e.NewValue);
            }
        }));
}
public class VisualTreeHelperEx
{
    public static T FindVisualParent<T>(DependencyObject child)
    where T : DependencyObject
    {
        DependencyObject parentObject = VisualTreeHelper.GetParent(child);
        if (parentObject == null) return null;
        T parent = parentObject as T;
        if (parent != null)
        {
            return parent;
        }
        else
        {
            return FindVisualParent<T>(parentObject);
        }
    }
}

A: i too Have a similar problem, so here is the Style i used(Copied from Net).
So you copy the WhistlerBlue theme from http://datagridthemesfromsl.codeplex.com/ and make following modifications. Hope this helps.
<!--Cell-->
<Style x:Key='CellStyle' TargetType="{x:Type controls:DataGridCell}" >
    <Setter Property="Foreground" Value="{StaticResource ThemeForegroundBrush}" />
    <Setter Property="Height" Value="Auto" />
    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    <Setter Property="VerticalContentAlignment" Value="Stretch"/>
    <Setter Property="Cursor" Value="Arrow" />
    <Setter Property="BorderThickness" Value="1" />
    <!--Padding hack-->
    <Setter Property="Padding" Value="2 5 2 5" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:DataGridCell}">
                <Grid x:Name="Root" Background="Transparent">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Rectangle x:Name="FocusVisual" Margin="0,-2,0,0"
                               Stroke="White"  Fill="White"
                               Opacity="0" IsHitTestVisible="false"/>
                    <ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content="{TemplateBinding Content}"
                                      ContentTemplate="{TemplateBinding ContentTemplate}" Cursor="{TemplateBinding Cursor}"/>
                    <Rectangle x:Name="RightGridLine" VerticalAlignment="Stretch" Width="1" Grid.Column="1" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

</Style>

<!-- DataGridRow -->
<Style x:Key='RowStyle' TargetType="{x:Type controls:DataGridRow}">
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:DataGridRow}">
                <Border x:Name="DGR_Border"
              Background="{TemplateBinding Background}"
              BorderBrush="{TemplateBinding BorderBrush}"
              BorderThickness="{TemplateBinding BorderThickness}"
              SnapsToDevicePixels="True">
                    <primitives:SelectiveScrollingGrid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height='Auto' />
                        </Grid.RowDefinitions>
                        <Rectangle x:Name="Selected" Margin="0" Grid.RowSpan="2" Grid.ColumnSpan="2"
                               Fill="{StaticResource BtnOverFill}" Stroke="{StaticResource selectedStroke}"
                               Opacity="0"/>
                        <Rectangle x:Name="SelectedHighlight" Margin="1" Grid.RowSpan="2" Grid.ColumnSpan="2"
                               Stroke="#A0FFFFFF"
                               Opacity="0"/>
                        <primitives:DataGridRowHeader Grid.RowSpan="2"
                                                    primitives:SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
                                                    Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type controls:DataGrid}},
                            Path=HeadersVisibility,
                            Converter={x:Static controls:DataGrid.HeadersVisibilityConverter},
                            ConverterParameter={x:Static controls:DataGridHeadersVisibility.Row}}"/>
                        <Rectangle x:Name="Over" Margin="0" Grid.RowSpan="2" Grid.ColumnSpan="2"
                               Fill="{StaticResource hoverGradient}"
                               Stroke="{StaticResource hoverStroke}"
                               Opacity="0"/>
                        <primitives:DataGridCellsPresenter Grid.Column="1"
                                        ItemsPanel="{TemplateBinding ItemsPanel}"
                                        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        <primitives:DataGridDetailsPresenter Grid.Column="1" Grid.Row="1"
                                                           x:Name='DetailsPresenter'
                                                           primitives:SelectiveScrollingGrid.SelectiveScrollingOrientation="{Binding RelativeSource={RelativeSource AncestorType={x:Type controls:DataGrid}}, Path=AreRowDetailsFrozen, Converter={x:Static controls:DataGrid.RowDetailsScrollingConverter}, ConverterParameter={x:Static controls:SelectiveScrollingOrientation.Vertical}}"
                                                           Visibility="{TemplateBinding DetailsVisibility}"
                                                           />
                        <Rectangle Height="1" HorizontalAlignment="Stretch"
                                   x:Name="BottomGridLine"
                                   Fill="{StaticResource HorizontalVerticalGridLinesBrush}"
                                   Grid.Column="1" Grid.Row="2" />
                    </primitives:SelectiveScrollingGrid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property='IsSelected' Value='True'>
                        <Trigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="Selected" Storyboard.TargetProperty="Opacity" To="0.84"/>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="SelectedHighlight" Storyboard.TargetProperty="Opacity" To="1"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.EnterActions>
                        <Trigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="Selected" Storyboard.TargetProperty="Opacity" To="0"/>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="SelectedHighlight" Storyboard.TargetProperty="Opacity" To="0"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.ExitActions>
                        <!--<Setter Property="DetailsVisibility" Value="Visible" />-->
                    </Trigger>
                    <MultiTrigger >
                        <MultiTrigger.Conditions>
                            <Condition Property="IsMouseOver" Value="True" />
                            <Condition Property="IsSelected" Value="False" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="Over" Storyboard.TargetProperty="Opacity" To="0.73"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.EnterActions>
                        <MultiTrigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="Over" Storyboard.TargetProperty="Opacity" To="0"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.ExitActions>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelected" Value="True" />
                            <Condition Property="IsFocused" Value="False" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="Selected" Storyboard.TargetProperty="Opacity" To="0.84"/>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="SelectedHighlight" Storyboard.TargetProperty="Opacity" To="1"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.EnterActions>
                        <MultiTrigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="Selected" Storyboard.TargetProperty="Opacity" To="0"/>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="SelectedHighlight" Storyboard.TargetProperty="Opacity" To="0"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.ExitActions>
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: MDADM - Stop Resync and Force Clean - Possible and/or Safe? I have been having issues with my FileServer recently.
See "rcu_sched detected stalls on CPUs/tasks" - jiffies - ESXi Ubuntu 16 FileServer Guest
I just rebuilt it since I couldn't get any guidance on the issue. Unfortunatley, its resyncing my array again.
Seeing how this has been done multiple time in the last few days, I'm fairly confident that its "in sync".
I have a few questions to that regard.

*

*When it resync's what is happening, is it just doing read operations on every piece of data? I feel i'm really abusing my HDD's at the moment

*Can I cancel resync? (I still want to be able to use the MDADM Though!)

*So Can I force it to "clean" state and remount?

*Is resync automatic when you mount a new MDADM (This is a new VM), or is there an error in the metadata that is forcing a resync and I NEED to let it finish. (It takes about 24 Hours and my server is extremely slow during that time)

Thanks!
Update: There are 4x 5tb HDDs in raid5 passed through via mapped raw lun to a VM guest which then exports nfs and smb.
This question is mostly about if the commands i want exist for mdadm and what sync does.

A: You can't stop a "parity check" as even though all the data is there, mdadm's metadata isn't correct. You have to let it finish.
Side Note: If you are having this issue repeatedly look into hardware failures as the culprit and solve asap!


text:
Q: Retain the values only in those rows of the column based on the condition on other columns in pandas I have a dataframe df_in, which contains column names that start with pi and pm.
df_in = pd.DataFrame([[1,2,3,4,"",6,7,8,9],["",1,32,43,59,65,"",83,97],["",51,62,47,58,64,74,86,99],[73,51,42,67,54,65,"",85,92]], columns=["piabc","pmed","pmrde","pmret","pirtc","pmere","piuyt","pmfgf","pmthg"])

If a row in column name which starts with pi is blank, make the same rows of columns which starts with pm also blank till we have a new column which starts with pi. And repeat the same process for other columns also.
Expected Output:
df_out = pd.DataFrame([[1,2,3,4,"","",7,8,9],["","","","",59,65,"","",""],["","","","",58,64,74,86,99],[73,51,42,67,54,65,"","",""]], columns=["piabc","pmed","pmrde","pmret","pirtc","pmere","piuyt","pmfgf","pmthg"])

How to do it?

A: You can create groups by compare columns names by str.startswith with cumulative sum and then compare values by empty spaces in groupby for mask used for set empty spaces in DataFrame.mask:
g = df_in.columns.str.startswith('pi').cumsum()
df = df_in.mask(df_in.eq('').groupby(g, axis=1).transform(lambda x: x.iat[0]), '')

#first for me failed in pandas 1.2.3
#df = df_in.mask(df_in.eq('').groupby(g, axis=1).transform('first'), '')

print (df)
  piabc pmed pmrde pmret pirtc pmere piuyt pmfgf pmthg
0     1    2     3     4                 7     8     9
1                           59    65
2                           58    64    74    86    99
3    73   51    42    67    54    65


text:
Q: Scenario to use YII DataProvider Can any one please explain me what are all the best scenario to use particular dataprovider.
For ex :

*

*When to use CActiveDataProvider ? (pros and cons)

*When to use CArrayDataProvider ? (pros and cons)

*When to use CSqlDataProvider ? (pros and cons)

A: *

*CActiveDataProvider - Use this if you have a list of models (uses findAll()).

*CArrayDataProvider - Use this when you have a raw array of objects which is not a list of models.

*CSqlDataProvider - Use this when you have a database query resulting in a list of objects and not a list of models.

You can use all three of them to construct html with for example the (default) widgets.
The docs are quite clear on when and how to use the three:

*

*CActiveDataProvider

*CArrayDataProvider

*CSqlDataProvider


text:
Q: c++ lambda can't convert to int I attempting to use a nested lambda as follows:
int main() {
    auto x=[](int a){
        return [a](int b){
            return a+b;
        };
    };

    int xx = x(1)(2);

    (void)xx;
    return 0;
}

However, the vs2013 compiler yields an error (C++11 language level):

[...] can't convert to int.

What is wrong?

A: Your code snippet is well-formed, and this is a compiler limitation or bug in the MSVC C++ compiler version used in VS2013. Note that VS2013 only claimed partial C++11 support, as per e.g. What's New for Visual C++ in Visual Studio 2013:

Improved ISO C/C++ Standards Support
Compiler
Supports these ISO C++11 language features:

*

*[...]


text:
Q: LOg4j - Getting fileName is Null {The parameter is null: fileName} When I run my application am getting File Name is null
Log4j - Getting file Name is Null {The parameter is null: file Name}
LOg4j2.yaml :->
Configuration:
  status: debug
  packages: com.xyz.x.log

  appenders:
    Console:
      name: LogToConsole
      PatternLayout:
        #Pattern: "%reqId%msg%n"
         Pattern: "%d{YYYY-MM-DD HH:mm:ss.SSS} [%-5level] %C{1} %L - %m%n"
    File:
      name: LogToFile
      PatternLayout:
        Pattern: "%d{YYYY-MM-DD HH:mm:ss.SSS} [%-5level]  %C{1} %L - %m%n"

  Loggers:
    logger:
      - name: com.xyz.x
        level: debug
        additivity: false
        AppenderRef:
          - ref: LogToConsole
          - ref: LogToFile
      - name: org.springframework.security
        level: debug
        additivity: false
        AppenderRef:
          - ref: LogToConsole
          - ref: LogToFile
    Root:
      level: error
      AppenderRef:
        ref: LogToConsole

Error I am getting:
 File org.apache.logging.log4j.core.config.ConfigurationException: Arguments given for element File are invalid: field 'fileName' has invalid value 'null'
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.injectFields(PluginBuilder.java:208)

A: Modify the File appender in order to add the filename property
For example:
File:
  name: LogToFile
  fileName: logs/yourLog.log
  PatternLayout:
    Pattern: "%d{YYYY-MM-DD HH:mm:ss.SSS} [%-5level]  %C{1} %L - %m%n"


text:
Q: Correct way to use parent environmental variables in maven in Intellij I have created a Maven Run Configuration in Intellij (Community Edition, Mac, Yosemite), and want to set up an Environmental Variable in the "Runner" tab of the configuration.  In the value of that variable, I was wanting to use a parent environmental variable (specifically, $HOME) for part of the value.
For example:
Run > Edit Configuration > Add New > Maven > Runner (tab) > Environmental Variables > Add New:

*

*name: SOME_CONFIG_FILE

*value: $HOME/.config/file.json
I have tried with HOME, $HOME, $HOME$, ${HOME} and %HOME% and none of them were able to resolve properly.  Clicking on the "Show" for the Parent Environmental Variables show HOME with the proper value.
What is the correct way to set the value?

A: It's not supported at the moment:

*

*IDEA-85313 Provide ability to reference parent environment variables in Run Configuration dialog


text:
Q: Responsive height for Background-Size Image CSS I have a responsive background image with the following properties
    background: url( '@{sitePath}/main_banner.png') center no-repeat;
    max-width: 100%;
    z-index: -10;
    height: 475px;
    background-size: contain;

The image needs to be able to scale down (as it does currently) but without a massive height (475px) for smaller devices. 100% min & standard height do not work and I want to avoid specifying individual heights for different media queries if I can help it.
Does anyone know how I can make this effectively responsive?
Thanks

A: You have put static height: 475px; If you want to have smaller height on smaller device try using media queries:
@media (max-width: size-that-you-want){
    .class-name{
        width: some-number;
    }
}

This should work.


text:
Q: android Stripe amount not changing I am using stripe to process my payments. I noticed that it keeps charging only $14.00 and I wanted to know how can I change that to something $1.00. I tried modifying the app.post("create-payment-intent") and still nothing is changing. Every time I check my stripe dashboard I still see $14.00 being charged. I have a copy of my code. Can someone please assist me with this. Thanks in advance
//Code

 private void startCheckout() {

        //amount will calculate from .00 make sure multiply by 100
        //double amount=Double.parseDouble(mAmount.getText().toString())*1;

        // Create a PaymentIntent by calling the sample server's /create-payment-intent endpoint.
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        /*
        String json = "{"
                + "\"currency\":\"usd\","
                + "\"items\":["
                + "{\"id\":\"photo_subscription\"}"
                + "]"
                + "}";

         */

        double amount=123.0;
        Map<String,Object> payMap=new HashMap<>();
        Map<String,Object> itemMap=new HashMap<>();
        List<Map<String,Object>> itemList =new ArrayList<>();
        payMap.put("currency","usd");
        payMap.put("amount","amount");
        itemMap.put("id","photo_subscription");
        itemMap.put("amount",amount);
        itemList.add(itemMap);
        payMap.put("items",itemList);
        String json = new Gson().toJson(payMap);
        //Log.i("TAG", "startCheckout: "+json);

        RequestBody body = RequestBody.create(mediaType,json);
        Request request = new Request.Builder()
                .url(BACKEND_URL + "create-payment-intent")
                .post(body)
                .build();
        httpClient.newCall(request)
                .enqueue(new PayCallback(this));

        // Hook up the pay button to the card widget and stripe instance
        //Button payButton = findViewById(R.id.payButton);
        payButton.setOnClickListener((View view) -> {
            //String get_card=cardInputWidget.getCard().getAddressZip();
            //Toast.makeText(PaymentPageActivity.this, get_card, Toast.LENGTH_SHORT).show();
            PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams();
            if (params != null) {
                Map<String, String> extraParams = new HashMap<>();
                extraParams.put("setup_future_usage", "off_session");

                ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams
                        .createWithPaymentMethodCreateParams(params, paymentIntentClientSecret);
                stripe.confirmPayment(this, confirmParams);
            }
        });
    }

//server.js

const express = require("express");
const app = express();
const { resolve } = require("path");
// This is your real test secret API key.
const stripe = require("stripe")("sk_test_****************");
app.use(express.static("."));
app.use(express.json());
const calculateOrderAmount = items => {
  // Replace this constant with a calculation of the order's amount
  // Calculate the order total on the server to prevent
  // people from directly manipulating the amount on the client
  return 100;
};
app.post("/create-payment-intent", async (req, res) => {
  const { items } = req.body;
  // Create a PaymentIntent with the order amount and currency
  const paymentIntent = await stripe.paymentIntents.create({
    amount: calculateOrderAmount(items),
    currency: "usd"
  });
  res.send({
    clientSecret: paymentIntent.client_secret
  });
});
app.get("/greet", async (req, res) => {
 res.send('hello it is working');
});
const PORT= process.env.PORT || 5001;
app.listen(PORT, () => console.log('Node server listening on port $(PORT)'));

A: The issue here is that your client code is pointing to a server that does not have your local changes. You have two options:

*

*Change your BACKEND_URL to point to your local server while your testing

*Leave your BACKEND_URL as is, commit and push your changes to master, and run git push heroku master to push your changes to heroku.


text:
Q: Variable is not declared or inaccessible due to its protection level. Im new in visual basic and right now I'm studying how to import csv file to database. I have this codes that imports csv file to access database but I keep getting this error:
'txtFile' is not declared. It may be inaccessible due to its protection level

Here is the code.
Imports System.Data.OleDb
Imports System.Threading
Imports System.Windows
Imports System.Collections

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim cnAccess As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" & Application.StartupPath & "C:\Users\vissia18\Desktop\ReportDB2.accdb;")

        Dim op1 As New OpenFileDialog
        op1.ShowDialog()
        txtFile.Text = op1.FileName

        Dim QryInsert As String = "", QryCreate As String = ""
        Dim i As Integer
        Dim cmd As New OleDbCommand
        Dim Fnm As String = txtFile.Text
        Dim s1 As String
        Dim s2(5) As String
        Dim freader As New IO.StreamReader(Fnm, False)
        cmd.Connection = cnAccess
        cnAccess.Open()
        While (freader.EndOfStream = False)
            s1 = freader.ReadLine
            s2 = s1.Split(",")
            QryInsert = "Insert Into Report Values (" & s2(0) & ",'" & s2(1) & "'," & s2(2) & ")"
            cmd.CommandText = QryInsert
            cmd.ExecuteNonQuery()
        End While
        MsgBox("Data Imported Successfully")
        cnAccess.Close()

    End Sub

End Class

Please correct me if I'm wrong somewhere else. Any help will be very much appreciated.

A: txtFile is not declared in your above code. You need to declare variables before using them.
Try to replace
txtFile.Text = op1.FileName
[....]
Dim Fnm As String = txtFile.Text

with
Dim txtFile as String = op1.FileName
[....]
Dim Fnm As String = txtFile


text:
Q: What is the fastest compression method for a large number of files? I need to compress a directory with around 350,000 fairly small files that amount to about 100GB total. I am using OSX and am currently using the standard "Compress" tool that converts this directory into a .zip file. Is there a faster way to do this?

A: This guy did some research on that. It appears that .zip will compress larger files faster. However, it yields one of the largest compression sizes. It also looks like he was using Windows utilities, but I'm betting OSX's utility is almost as optimized.
Here is an excellent website where numerous compression utilities have been benchmarked for speed over many files. There are many other tests on that site you could look at to determine the best utility for you.
Much of the speed has to do with the program you use. I've used 7zip's utility for Windows, and I find that to be very fast. However, compressing many files takes a long time no matter what so I would just let it go overnight. Or you could just tar the whole thing and not compress it...Personally I hate unzipping large archives so I would be careful if that's what you want to do.

A: For directories I'd  use a tar piped to bzip2 with max-compression.
a simple way to go is,

tar cfj archive.tar.bz2 dir-to-be-archived/

This works great if you don't intend to fetch small sets of files out of the archive
and are just planning to extract the whole thing whenever/wherever required.
Yet, if you do want to get a small set of files out, its not too bad.
I prefer to call such archives filename.tar.bz2 and extract with the 'xfj' option.
The max-compression pipe looks like this,

tar cf - dir-to-be-archived/ | bzip2 -9 - > archive.tar.bz2
#      ^pipe tarball from here to zip-in^ into the archive file.

Note: the 'bzip2' method and more compression tends to be slower than regular gzip from 'tar cfz'.
If you have a fast network and the archive is going to be placed on a different machine,
you can speed up with a pipe across the network (effectively using two machines together).

tar cf - dir/ | ssh user@server "bzip2 -9 - > /target-path/archive.tar.bz2"
#      ^ pipe tarball over network to zip ^ and archive on remote machine.

Some references,

*

*Linux Journal: Compression Tools Compared, Jul 28, 2005

*

*this also refers the MaximumCompression site mentioned by Dennis

*gzip vs. bzip2, Aug 26, 2003

*A Quick Benchmark: Gzip vs. Bzip2 vs. LZMA, May 31, 2005


text:
Q: Inequality on ratio of norms I would have a question that is a specific case of this post - Bounding the ratio of the $l^1$ norms of two vectors to the ratio of their $l^2$ norms - with $x_j=y_j^2$ and $c_1=1$, $c_2=1/2$.
Specifically, I would like to show that, given any real strictly positive vector $\mathbf{y}=(y_1,\dots,y_n)>\mathbf{0}$, the following holds:
$$ \left(\frac{\sum_{i=1}^n y_i^4}{\sum_{i=1}^n y_i^2} \right)^{1/2} \geq \frac{\sum_{i=1}^n y_i^2}{\sum_{i=1}^n y_i}. $$
The inequality seems to always hold numerically, but any help on a proof would be greatly appreciated.

A: By Holder $$\sum_{i=1}^ny_i^4\left(\sum_{i=1}^ny_i\right)^2\geq\left(\sum_{i=1}^ny_i^2\right)^3,$$ which gives your inequality.


text:
Q: SQL Where IN Order 2 SubQuery I have three tables in SQL :
video : ID, TITLE
join_video_clicked : ID_VIDEO, NB_VIEW
join_video_category : ID_VIDEO, ID_CATEGORY

My actual SQL Query :
SELECT ID,TITLE,THUMB
FROM video
WHERE ID
IN (
      SELECT * FROM
      (
         SELECT ID_VIDEO
         FROM join_video_clicked
         WHERE ID_VIDEO
         IN
         (
             SELECT ID_VIDEO
             FROM join_video_category
             WHERE ID_CATEGORY = 8
         )
    ORDER BY CLICKED DESC
  ) AS TEMP
 ) LIMIT 0,24

Explain 1 :
SELECT ID_VIDEO FROM join_video_clicked ORDER BY CLICKED DESC LIMIT 0,24

This query get 24 ids the most viewed
Explain 2 :
SELECT ID_VIDEO FROM join_video_category WHERE ID_CATEGORY = 8

This query get ids from custom category
Explain 3 :
SELECT ID,TITLE FROM video WHERE ID IN (!!!SUBQUERY!!!)

This query find id and title with subquery
I would like your help for adjust my query for get 24 most viewed video from custom category in correct order, because with this query i have the 24 video most viewed in my custom category but not in order DESC.

A: Try this,
SELECT ID,TITLE,THUMB FROM video v JOIN join_video_clicked jvc ON
ID=jvc.ID_VIDEO JOIN join_video_category jvcat ON ID=jvcat.ID_VIDEO WHERE
ID_CATEGORY = 8 ORDER BY CLICKED DESC LIMIT 0,24

A: You can do an inner join between the two tables to get all videos from that category, and in that query you can add your order by and limit:
SELECT jvclick.id_video
FROM join_video_clicked jvclick
JOIN join_video_category jvcat ON jvcat.id_video = jvclick.id_video
ORDER BY jvclick.clicked DESC
LIMIT 24;

A: Something like this should do it:
select
    vid.id_video,
    vid.title,
    count(click.id_video) cnt
from
    video_clicked click
    join video vid on click.id_video = vid.id_video
    join video_category cat on vid.id_video = cat.id_video
where
    cat.id_category = 1
group by
    vid.id_video,
    vid.title
order by
    cnt desc
;

Full example:
use example;

/*
video : ID, TITLE
join_video_clicked : ID_VIDEO, NB_VIEW
join_video_category : ID_VIDEO, ID_CATEGORY
*/

drop table if exists video_clicked;
drop table if exists video_category;
drop table if exists video;
drop table if exists category;

create table category (
    id_category int primary key,
    name varchar(256)
);

create table video (
    id_video int primary key,
    title varchar(256)
);

create table video_category (
    id_video int references video(id),
    id_category int references category(id)

);

create table video_clicked (
    id_video int references video(id),
    nb_view varchar(256)
);

select
    vid.id_video,
    vid.title,
    count(click.id_video) cnt
from
    video_clicked click
    join video vid on click.id_video = vid.id_video
    join video_category cat on vid.id_video = cat.id_video
where
    cat.id_category = 1
group by
    vid.id_video,
    vid.title
order by
    cnt desc
;

A: SELECT v.ID,v.TITLE,v.THUMB FROM video v
JOIN join_video_clicked jvc ON v.ID=jvc.ID_VIDEO
JOIN join_video_category jvcat ON v.ID=jvcat.ID_VIDEO
WHERE jvcat.ID_CATEGORY = 8 ORDER BY jvc.CLICKED DESC LIMIT 24


text:
Q: Jquery Autocomplete URL Based On Selected Value From Another Autocomplete I have a form allowing users to submit timesheets. This consists of multiple table rows for each day of the week. Each row is created by a call to AddRow, which adds the HTML, and also adds an autocomplete box on the JobNumber field, so the user can look up and select the required job.
I now need to add a second autocomplete to the Description field to allow the user to pick tasks that have been created for that job. I therefore need to pass a parameter in the source URL specifying the job that was selected in the previous box.
However, when I try to find the value of Job, it always returns "undefined".
What am I missing?
Here's the a simplified version of what I have:

Add

I added an alert in there to check the value, but its returning "undefined" every time. I've tried JobID and JobNumber fields, neither of which work.

A: Short answer: $(this) matches nothing, replace it with $(this.element)

This is happening because source is a widget option, not an event. As such, it's (pseudo-)handler is not bound on the node instance
ie. Inside the source function, this references the widget, not the element, which results in the selector not matching anything
To access the element, simply use this.element:
var jobID = $("input[id$='JobNumber']", $(this.element).parent().parent()).val();

Here's a fiddle with your code: https://jsfiddle.net/uxpeytxn/
NOTE: this is only relevant to source, in select, change and the other event handlers, this references the element, as one would expect


text:
Q: Scrollify + custom scroll events Essentially, I need scrollify to stop running once it gets to the first section, then start running again once the first section's animations are complete. I have tried stop(); but with no luck. Any help is greatly appreciated.
$(function() {
$('.section-image1').hide();
$('.section-image2').hide();
$('.section-image3').hide();
$.scrollify({
    section: ".header-home",
    section: ".section",
    before: function(section){
        console.log(section);
        if(section==1){
            //stop scrollify
            $(window).scroll(function(){

                $('.section-image1').show();
                $('.section-image2').show();
                $('.section-image3').show();
                $('.section-image1').addClass('fadeInUp');
                $('.section-image2').addClass('fadeInUp');
                $('.section-image3').addClass('fadeInUp');
        });
            //start scrollify
            if(section==2){
            //stop scrollify
            $(window).scroll(function(){

                $('.section-image4').show();
                $('.section-image5').show();
                $('.section-image6').show();
                $('.section-image4').addClass('fadeInUp');
                $('.section-image5').addClass('fadeInUp');
                $('.section-image6').addClass('fadeInUp');
        });
    }

}
});
});


text:
Q: how to get value from other view controller and compare ..? I have two view controllers

*

*SearchViewController.m

*ContentViewController.m

In SearchViewController.m  File
(void)searchBarSearchButtonClicked:(UISearchBar*)searchBar

 {
    [searchBar resignFirstResponder];

     NSString * searchStr = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

     [searchBar resignFirstResponder];
     [self.searchDisplayController setActive:NO animated:YES];
      **searchBar.text = searchStr**;

     #ifndef SQL_KEYWORD_PARSE
    // Process the search string for keywords
     NSMutableSet* tokens = [[Tokenizer sharedTokenizer] tokenize:searchStr];

    // Create and perform a request for existing keyword records for these tokens
    NSError* err;
    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Keyword"   inManagedObjectContext:self.managedObjectContext];
    request.predicate = [NSPredicate predicateWithFormat:@"keyword IN %@",tokens];
    NSArray* aKeywords = [self.managedObjectContext  executeFetchRequest:request error:&err];
   [request release];

   if (![aKeywords count])
{
    [[[[UIAlertView alloc] initWithTitle:nil
                                 message:@"No records match this search; it contains no indexed keywords"
                                delegate:self
                       cancelButtonTitle:@"Ok"
                       otherButtonTitles:nil] autorelease] show];
    return;
}
if (searchBar.selectedScopeButtonIndex && ([tokens count] != [aKeywords count]))
{
    [[[[UIAlertView alloc] initWithTitle:nil
                                 message:@"No records match this search; it contains one or more keywords with no matches"
                                delegate:self
                       cancelButtonTitle:@"Ok"
                       otherButtonTitles:nil] autorelease] show];
    return;
}

    // Create a filtered result set
   ((RuleSearchDataSource*) self.dataSource).exactPhrase = (searchBar.selectedScopeButtonIndex == 0);
   ((RuleSearchDataSource*) self.dataSource).useAll = (searchBar.selectedScopeButtonIndex == 1);
   ((RuleSearchDataSource*) self.dataSource).phrase = searchStr;
   ((RuleSearchDataSource*) self.dataSource).keywords = [NSSet setWithArray:aKeywords];
   #else
// Create a filtered result set
   ((RuleSearchDataSource*) self.dataSource).exactPhrase = (searchBar.selectedScopeButtonIndex == 0);
   ((RuleSearchDataSource*) self.dataSource).useAll =  (searchBar.selectedScopeButtonIndex == 1);
   ((RuleSearchDataSource*) self.dataSource).phrase = searchStr;
    #endif
    NSLog(@"String Search word :%@",searchStr);
}

ContentViewController.m File
(void) reloadHighlights: (ContentViewDataSource *) dataSource
{
   // Clear any existing highlights.
    for (NSArray * section in dataSource.items)
    {
   if (section.count > 0)
    {
        TTTableStyledTextItem * item = section[0];
        ContentStyledText * text = (ContentStyledText *) item.text;
        [text removeHighlights];
    //          text.font = nil;
    }
}
AppDelegate_Shared * appDelegate = (AppDelegate_Shared *) [[UIApplication sharedApplication] delegate];
HighlightsController * highlightController = appDelegate.highlightsController;

NSMutableArray * highlights = highlightController.highlights;
DefaultStyleSheet * styleSheet = [DefaultStyleSheet globalStyleSheet];

if (highlights)
{
        if (self.tempHighlightPassageArray != nil)
    {
 for (NSNumber * passageId in self.tempMHighlightPassageArray)
        {
            int rowIndex = [(ContentViewDataSource *) self.dataSource rowNumberForPassage:[passageId integerValue]];

            TTTableStyledTextItem * item = (TTTableStyledTextItem *) [dataSource getSectionItem:rowIndex itemIndex: 0];

 if (item.text)
 {
    ContentStyledText * text = (ContentStyledText *) item.text;
    UIColor * highlightColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0]; //

     NSString* wordsList = @"";
     NSArray * paraArray = [text.rootNode.outerText componentsSeparatedByString:@" "];

 // for loop for passag word count
 for (NSUInteger iCount=0; iCount < [paraArray count ]; iCount++)
 {
    if([paraArray[iCount] **compare:@"the"** options:NSCaseInsensitiveSearch]== NSOrderedSame)
    {
    if([wordsList isEqualToString:@""])
     {
       wordsList = [NSString stringWithFormat:@"%lu" , (unsigned long)iCount];
     }
     else{
         wordsList = [wordsList stringByAppendingString:@"|"];
         wordsList = [NSString stringWithFormat:@"%lu" , (unsigned long)iCount];
       }
  }
  if(![wordsList isEqualToString:@""]){
   NSArray* wordArray = [wordsList componentsSeparatedByString:@"|"];

   for (NSUInteger iCount=0; iCount < [wordArray count ]; iCount++)          {
    [text addHighlightFrom:[wordArray[iCount] integerValue] to:[ wordArray[iCount] integerValue] color:highlightColor stroke:highlightColor];
    //text.rootNode.outerHTML = text.rootNode.outerHTML;
    // return ;
             }
       }
 }
 }
        }
    }

    for (Highlight * highlight in highlights)
    {
        if (highlight.sectionId == [self.section.id integerValue])
        {
            [self loadHighlight:highlight dataSource: dataSource styleSheet: styleSheet];
        }
    }
}

  if (mSelectionHighlight && mSelectionHighlight.highlightColor == kEraseColor)
  {
     // Erase color highlights don't get added to the list, but we still want to show a selection.
    [self loadHighlight:mSelectionHighlight dataSource: dataSource styleSheet: styleSheet];
  }

}

I want to pass value from SearchViewController ==> of searchBar.text = searchStr value to the ContentViewController ==> to pass value in compare:@"the"
I am new in iOS development.

A: Create a public @property in ContentViewController to hold the NSString from the texbox. Then set it before pushing the view controller. Situations you might have:
A) You are using a storyboard to define the contentcontroller and searchcontroller. In this case you can Ctrl drag the ContentController with the mouse from the storyboard to the SearchController.h file and create an IBoutlet for it (so you now have access to the ContentController from the Search one, you can set the string value when user enters text)
B) You are pushing ContentController manually, then set the property before pushing it.
C) You are pushing it via storyboard. Then use the method - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender. This method is called before getting pushed so you have a chance to set the properties of the pushed controller there.


text: Q: Reading video from OpenMV H7 camera over ttyACM0 port using c++ code I have an OpenMV H7 camera who's output I need to read into OpenCV. Now, the serial output is ttyACM0 where I am able to stream image frames. How can I read these frames in c++ code? I cannot use cv::VideoCapture() as the camera is not recognized as a video device. Serial libraries for C++ that I've found so far are quite messy. I am able to do this on python using serial library. Any help in reading into c++ would be valuable.


text:
Q: Problema al guardar latitud y longitud en mysql con php y js tengo una problemática para guardar la latitud y la longitud en mi base de datos. La consulta para hacer la inserción funciona pero es como si mis variables para las coordenadas se mandaran vacías. La latitud y la longitud las obtengo con javascript y luego las mando a variables php que las uso para insertar en la bd junto con otros datos que si se guardan. He intentado hacerlo con ajax, obtengo las coordenadas y con input hidden envío la data usando ajax, pero se van vacías. También intenté con una variable de js enviarlas por método GET a una url destino pero de la misma forma me guarda valores vacíos. Ya no sé como más puedo hacerlo para que funcione, les dejo mis intentos:
Obtengo la latitud y longitud con javascript y las mando a la url destino por método GET,si hay valores porque los imprimo en un alert
navigator.geolocation.getCurrentPosition(fn_ok, fn_error);

function fn_error(){

alert('Error');
}

function fn_ok(respuesta){

var lat = respuesta.coords.latitude;
var lon = respuesta.coords.longitude;

global="lat="+lat+'&lon='+lon;
var urlDestino = "https://ejemplo.com/ejemplo/scan.php?"+global;
alert(global);
}

En mi archivo scan.php se supone que recibo los datos, para guardarlos posteriormente
$lat = $_GET["lat"];
$long = $_GET["lon"];
$registrar = mysqli_query($con, "INSERT INTO asistencia_bus (matricula,fecha,hora,dia,latitud,longitud,tipo,estatus,periodo,año) VALUES ('$datoqr','$date','$Hora','$dia','$lat','$long','$tipo_abordaje','Sin adeudo','$periodo','$year')");

Los otros valores no los pongo porque esos si se guardan en la BD
Pero como comento, se hace la inserción y esos 2 campos siempre se guardan vacíos.
Ahora con ajax. Aquí tengo los 2 input hidden que tienen los valores de latitud y longitud que obtengo con js
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/png" href="./assets/img/bus.png" />
<title>Carnet autobus escolar</title>
<link rel="stylesheet" type="text/css" href="./assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="./assets/estilo_camara.css"/>
<link href="./assets/css/style.css" rel="stylesheet">

<a href="<?php echo RUTA.'Cerrar'?>">

Salir

 REGISTRO DE ALUMNOS

          <input type="text" id="cd" value="<?php echo $cd; ?>" style="display: none;">
          <input type="text" id="st" value="<?php echo $st; ?>" style="display: none;">

 No se puede acceder a la transmisión de video (asegúrese de tener una cámara web habilitada)

            <canvas id="canvas" hidden></canvas>

Aún no se ha detectado carnet QR...

                Código:

  <audio controls id="sonido_qr" style="width: 0px !important;height: 0px !important;">
     <source src="./Halcon.mp3" type="audio/mpeg">
  </audio>

<input type="hidden" class="form-control" id="latitud" name="latitud" required>
<input type="hidden" class="form-control" id="longitud" name="longitud" required>

Aquí mi archivo js:
const funcionInit = () => {
    if (!"geolocation" in navigator) {
        return alert("Tu navegador no soporta el acceso a la ubicación. Intenta con otro");
    }

    let idWatcher = null;

    const $latitud = document.querySelector("#latitud"),
        $longitud = document.querySelector("#longitud");
        $log = document.querySelector("#log");

    const onUbicacionConcedida = ubicacion => {
        const coordenadas = ubicacion.coords;
        $latitud.innerText = coordenadas.latitude;
        $longitud.innerText = coordenadas.longitude;
        loguear(`${ubicacion.timestamp}: ${coordenadas.latitude},${coordenadas.longitude}`);
        enviarAServidor(ubicacion);
    }

    const enviarAServidor = ubicacion => {
        // Debemos crear otro objeto porque el que nos mandan no se puede codificar
        const otraUbicacion = {
            coordenadas: {
                latitud: ubicacion.coords.latitude,
                longitud: ubicacion.coords.longitude,
            },
            timestamp: ubicacion.timestamp,
        };

    const loguear = texto => {
        $log.innerText += "\n" + texto;
    };

    const onErrorDeUbicacion = err => {

        $latitud.innerText = "Error obteniendo ubicación: " + err.message;
        $longitud.innerText = "Error obteniendo ubicación: " + err.message;
        console.log("Error obteniendo ubicación: ", err);
    }

    const detenerWatcher = () => {
        if (idWatcher) {
            navigator.geolocation.clearWatch(idWatcher);
        }
    }

    const opcionesDeSolicitud = {
        enableHighAccuracy: true,
        maximumAge: 0,
        timeout: 5000
    };

    window.onload=function (){
        detenerWatcher();
        idWatcher = navigator.geolocation.watchPosition(onUbicacionConcedida, onErrorDeUbicacion, opcionesDeSolicitud);
    }

};
document.addEventListener("DOMContentLoaded", funcionInit);

Ya que las obtuve los valores están en mis input hidden y con ajax los mando a php
$(document).ready(function(){

                var latitud = document.getElementById("latitud").value;
                var longitud = document.getElementById("longitud").value;

                $.ajax({
                    url:"./scan.php",
                    method:"POST",
                    data: { latitud : latitud , longitud : longitud }
                  });

                });

Y finalmente las recibo en php para mandarlas guardar
$lat = $_POST['latitud'];
$long = $_POST['longitud'];

Pero en ningún caso funciona, siempre los demás datos se guardan con valore y esos 2 campos se van vacíos. Quedo atento a sus respuestas y gracias por el apoyo.


text:
Q: Как передать неограниченное кол-во аргументов в discord.py Хочу сделать так, что бы на картинку накладывался текст. Не могу понять как сделать, так, чтобы можно было передать несколько слов. Вот код)
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

TOKEN = 'tok'

def img(text, name):
    img = Image.open("123.jpg")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("18231.ttf", 100)
    draw.text((1024, 576),text,(255,255,255),font=font)
    img.save(str(name)+".jpg")

bot = commands.Bot(command_prefix='mix ') #инициализируем бота с префиксом 'mix '

@bot.command(pass_context=False) #разрешаем передавать агрументы
async def meme(ctx, *ggwp): #создаем асинхронную фунцию бота
    img(ggwp, "hiq")
    await ctx.send('', file=discord.File('hiq.jpg'))

bot.run(TOKEN)

A: Все можно, только ты наоборот отсекаешь контекст команды.
@bot.command(pass_context=True)
А у вас стоит False.


text:
Q: Restarting all tabs in SuperPuTTY at once? I have opened a couple of sessions on SuperPuTTY. The Internet got interrupted for a few minutes, which cause my SSH sessions to be disconnected in SuperPuTTY. Is there any way to restart all tabs in SuperPuTTY at once?

A: SuperPuTTY supports a feature called layouts, this allows you to open your sessions and layout your screen how you prefer. You can then click File -> Save Layout (CTRL+S), if you have your layouts window open (View -> Layouts) you can double click your saved layout and it will open all sessions you had previously opened in your layout.


text:
Q: Python - Name format_string is not defined error I'm trying to create a class tree from which I can create various files and insert a list of values.I have only included code for the Delimited file. Whilst running the below code,I get the message that appears in the title, please assist.Thanks
from datetime import datetime as Dt
from abc import abstractmethod,ABCMeta

class FileWriter(metaclass=ABCMeta):

    def __init__(self,FileName):
        self.FileName = FileName

    @staticmethod
    def return_time():
        return Dt.now().strftime('%Y-%m-%d %H:%M')

    @abstractmethod
    def write(self):
        return

    def format_string(self,Values,Seperator,CSV = False):
        self.Values = Seperator.join((Values))
        if CSV == True:self.Values = Seperator.join((Values))
        return self.Values

    def write_lines(self,Values,Seperator = ","):

        print(self.Values)
        File = open(self.FileName,'w')
        File.write(self.Values + '\n')
        File.close()

class DelimitedFile(FileWriter):

    def __init__(self, FileName):
        return super().__init__(FileName)

    def format_string(self, Values, Seperator):
        self.Values = Values
        self.Seperator = Seperator
        for i in range(len(self.Values)):
            if "," in self.Values[i]:self.Values[i] = ('"' + self.Values[i] + '"')
        self.Seperator = Seperator
        return super().format_string(Values, Seperator) + ','

    def write(self,Values,Seperator=',',CSV = False):
        self.Values = str(Values)
        self.Seperator = Seperator
        self.Values = format_string(self.Values,self.Seperator)
        super().write_lines(self.Values,Seperator=',')

NewInst = DelimitedFile('Test.txt')
print(NewInst.return_time())
Values = ['s','str','trtyh','yutyuty','u7u7u7u7','e5ryru,tut','u7u7tussth','y5syyjuyju']
NewInst.write(Values)
Value = (NewInst.format_string(Values,','))


text:
Q: Can the current value determine the logic value(0 or 1)? In case of parallel connection, is the statement "Depending on the current(electric current) value, logic (0 or 1) is determined." True or False? I do not understand why current cannot affect the voltage value in this case. Don't we need another assumption about the resistors having the same value in order for the statement to be false? I am confused.
This is a TF question from my logic design class. The answer provided is false because it is determined by voltage. I marked this as true because I thought current can affect the voltage therefore determine the logic value. But when I mailed my professor he said this is not true in case parallel connection. I am wondering why this is the case.

A: It's not a very clear question, but on logic ICs, it's the input voltage that determines if that input is high or low.  The IC doesn't know or care what current is flowing from the previous IC's output.

simulate this circuit – Schematic created using CircuitLab
So in the little diagram above, pressing SW2 changes the current flowing out of BUF1, but BUF2 doesn't care.


text:
Q: Multiple content subfolders in a MvcContrib PortableArea I'm looking to create a common ASP.MVC (c# and razor) base project containing common controllers, _Layout.cshtml, css and js for many of our webapps to extend from.
I thought that using MvcContrib and creating Portable Areas is my best bet
So the folder setup is roughly like this
BaseProj

*

*Content

*

*js

*

*plugins

*misc

*images

*

*foo

*css

*Controllers

*Views

MainProj

*

*Content

*Controllers

*Views

I am registering the BaseProj area by extending PortableAreaRegistration class (as per MvcContrib docs) so this url works...
htttp://localhost/MainProj/BaseProj/
Looking in the MvcContrib code for PortableAreaRegistration it also registers 3 static routes too (images, styles, scripts) under Content.
Therefore this url works fine too...
htttp://localhost/MainProj/BaseProj/images/bar.jpg
also subfolders work fine only if i use a dot instead of a slash...
htttp://localhost/MainProj/BaseProj/images/foo.bar.jpg
However its really useful to have subfolders under images, css, js etc for organisation purposes. These subfolders will now 404 though
ie this will not work....
htttp://localhost/MainProj/BaseProj/images/foo/bar.jpg
So the question is how do i map subfolders under images (without the dot notation)?
ie so this works....
htttp://localhost/MainProj/BaseProj/images/foo/bar.jpg
Thanks
EDIT:
Well a bit of thinking and I found a solution. I wonder if this kind of thing might be included in MvcContrib.Portable Areas by default.
First create a catch all route in your BaseProjRegistration.cs to catch all subfolders of Content
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
    ...

        //static controller with catch all for all subfolders of content
        context.MapRoute(
            "BaseProjContent",
            "BaseProj/Content/{*resourceName}",
           new { controller = "Content", action = "LoadContent", resourcePath =    "Content" }
       );
    ...
}

Then Create a ContentController class in your BaseProj which will extend MvcContrib.PortableAreas.EmbeddedResourceController.
This will convert slashes to dots to load the BaseProj content from the DLL
ie /BaseProj/Content/images/foo/bar.jpg => /BaseProj/Content/images.foo.bar.jpg
public class ContentController : MvcContrib.PortableAreas.EmbeddedResourceController
{

    public ActionResult LoadContent(string resourceName, string resourcePath)
    {
        string actualResourceName = resourceName.Replace("/", ".");
        return base.Index(actualResourceName, resourcePath);
    }
}

This worked for me, but any other recommnedations of how to setup a common base project for lots of webapps to extend are welcome


text:
Q: Constructing an F[x]-module from a vector space V. I'm working through Dummit and Foote (module theory), and I'm having a tough time understanding the following:
for any two linear transformations $A,B$ from $V$ to $V$ and elements $\alpha,\beta\in F$, let $\alpha A+\beta B$ be defined by
\begin{equation*}
(\alpha A+\beta B)(v)=\alpha(A(v))+\beta(B(v))
\end{equation*}
where $F$ is a field and $V$ is a vector space over $F$.
Shouldn't this be
\begin{equation*}
(\alpha A+\beta B)(v)=\alpha A(v)+\beta B(v)
\end{equation*}
Is this a typo or do I have a misunderstanding? Thanks in advance.


text:
Q: Bootstrap Javafx 2.0 with Weld I am trying to bootstrap a small javafx application using Weld-SE. I was able to run the application if I remove the @Inject annotation on the Menubar and instantiate it manually.
But the moment I add @Inject, the application throws exception. Listed below are the injection point and the Producer method. This is all the configuration I did, am I missing something ?
Injection Point
@Inject MenuBar menuBar

Class with producer method
public class ComponentProducer {

    @Produces
    public MenuBar createMenuBar(){
        return new MenuBar();
    }

}

Exception
    491 [JavaFX Application Thread] INFO org.jboss.weld.Bootstrap - WELD-000101 Transactional services not available. Injection of @Inject UserTransaction not available.    Transactional observers will be invoked synchronously.
    8868 [JavaFX Application Thread] WARN org.jboss.interceptor.model.InterceptionTypeRegistry - Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled
    8868 [JavaFX Application Thread] WARN org.jboss.interceptor.model.InterceptionTypeRegistry - Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled
    Exception in Application start method
    Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:399)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:722)

    Caused by: java.lang.NullPointerException
at net.sourceforge.squirrel_sql.client.MainScene.<init>(MainScene.java:26)
at net.sourceforge.squirrel_sql.client.FXApplication.startup(FXApplication.java:176)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:304)
at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54)
at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:163)
at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:298)
at org.jboss.weld.introspector.jlr.WeldMethodImpl.invokeOnInstance(WeldMethodImpl.java:200)
at org.jboss.weld.introspector.ForwardingWeldMethod.invokeOnInstance(ForwardingWeldMethod.java:59)
at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:194)
at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:241)
at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:216)
at org.jboss.weld.manager.BeanManagerImpl.notifyObservers(BeanManagerImpl.java:654)
at org.jboss.weld.manager.BeanManagerImpl.fireEvent(BeanManagerImpl.java:647)
at org.jboss.weld.manager.BeanManagerImpl.fireEvent(BeanManagerImpl.java:641)
at org.jboss.weld.event.EventImpl.fire(EventImpl.java:93)
at net.sourceforge.squirrel_sql.client.Main.start(Main.java:180)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:315)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:174)
at com.sun.javafx.application.PlatformImpl$3.run(PlatformImpl.java:141)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication$2$1.run(GtkApplication.java:79)
... 1 more

A: Is it because you are trying to use menuBar in the constructor or initialiser block?
If so, try using Initializable and using them in initialize.

A: ShaggyInjun, you refer to the Initializable interface which indicates you were trying to integrate with the FXMLLoader.  All of the information below assumes you are using FXML for your interface definition and only discusses issues around injecting values into FXML controllers.
The FXMLLoader has the concept of a controller factory, which you should use to integrate the controller instantiation with your dependency injection system.  There is a brief discussion of controller factories in Oracle's Mastering FXML Tutorial.  Andy demonstrates definition of such a factory for Guice in his blog and there is a comprehensive integration of Guice in FXML on github.

For Weld you will need to implement a similar controller factory callback mechanism to realize the dependency injection functionality which Weld provides.  The article by Matthieu Brouillard that you linked in a comment FXML & JavaFX—Fueled by CDI & JBoss Weld would seem to provide all of the information you need to both initialize Weld and interface Weld into the FXMLLoader controller factory mechanism. Specifically, the following code is the Weld equivalent of Andy Till's FXML based injection mechanism:
public class FXMLLoaderProducer {
  @Inject Instance<Object> instance;
  @Produces public FXMLLoader createLoader() {
    FXMLLoader loader = new FXMLLoader();
    loader.setControllerFactory(new Callback<Class<?>, Object>() {
      @Override public Object call(Class<?> param) {
        return instance.select(param).get();
      }
    });
    return loader;
  }
}

Even when an FXMLoader controller factory is used, I believe it is the FXMLLoader that is instantiating the controller.  So in those cases, you should not make of annotations like @PostConstruct because they only apply when the dependency injection system is maintaining the lifecycle of the object - and that is not the case if the FXMLLoader creates the controller.
There is one other alternative, and that it is to explicitly set the controller to be used by the FXMLLoader using setController.  This would allow you to have your dependency injection system instantiate (and inject into) controllers using whatever means it wishes and then you could subsequently pass the instantiated controller to your FXMLLoader.  In such cases anotations like @PostConstruct should work as the dependency injection system is now maintaining the objects lifecycle (and @PostConstruct would be invoked by the dependency injection system after the Controller has been created and before you pass the  Controller through to the FXMLLoader).

I'll post Andy's Guice based solution here as it is a small and simple example of how similar injection is accomplished in Guice (in case his blog goes offline):
class GuiceControllerFactory implements Callback<Class<?>, Object> {
  private final Injector injector;
  public GuiceControllerFactory(Injector anInjector) {
    injector = anInjector;
  }
  @Override public Object call(Class<?> aClass) {
    return injector.getInstance(aClass);
  }
}

A: EJB documentation states that the method annotated with @PostConstruct will be called after the injections are done, and that this is the method to expect variable injections.
@PostConstruct
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.
Expecting the variable to be initialized inside the initialize does seem to work however.
According to the Initializable documentation, initialize is Called to initialize a controller after its root element has been completely processed.
Initializable
Order of call for initialize and @PostConstruct
I think it is safe to understand that the calling of initialize does not have anything to do with object construction. Instead, initialize is called when the root of the current node graph has been completely processed, so one can process things like event handlers etc. Something on the lines of document.onload or jQuery(document).ready(). If you were to try to attach event handlers before  object graph is ready, there is a pretty good chance to see a null pointer because the node is not the object graph yet making it impossible to attach an event handler.
So, you'd instantiate an object (either directly or via injecting) before you load it to the scene-graph. Therefore @PostConstruct gets called before the initialize. But, if you instantiate the object directly then the responsibility to call the method annotated @PostConstruct falls on you, otherwise that post processing will not happen.
Conclusion:
It is safe to assume that initialize is always called after the method annotated with @PostConstruct.
EDIT
@Jewelsea has pointed out a few assumptions that I have not listed above. So here it goes, the circumstances where the above worked for me.

*

*Using FXML files for views.

*Controller name specified inside the fxml file.


text:
Q: What is the state of MPMusicPlayerController when the now playing item is skipping to outside the current playlist? I'm using MPMusicPlayerController and I have implemented skip track and previous track controls to control the music playback. When I reach the end of an album/playlist that is  in the now playing list. The App no longer skips track nor goes previous track.
Example: First track of album, tap on previous track the app would stop responding and skip track/play/previous track will no longer respond.
Example: Last track of album, tap on previous track the app would stop responding and skip track/play/previous track will no longer respond.
I noticed on the iPod app itself, after it finishes a playlist it'll return to the playlist selection view or it'll return to the album selection view. What state is the MPMusicPlayerController in at this point of time? How can I use it to launch the iPod app when I encounter such a state within my App?
http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPMusicPlayerController_ClassReference/Reference/Reference.html

A: I've found that if repeatMode is set to MPMusicRepeatModeAll, next track will go back to the first item in the playlist. I think previous will still do nothing.
So, use notifications as described above, or set repeatMode to prevent this from happening.

A: Based on my experience, the state becomes MPMusicPlaybackStateStopped In this state, playlist is actually gone, and needs to be update by playing iPod Music player again. You may use MPMusicPlayerControllerPlaybackStateDidChangeNotification to evaluate the condition of the player and do the action of your choice. Notification Programming Topics: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html#//apple_ref/doc/uid/10000043i


text:
Q: Cordova Mobile: Web File API doesn't work correclty We recently migrated an Cordova App to Capacitor.
I am currently working on a feature, which uses Canvas blob data to create File (WebAPI), which we sent to an API.
But I noticed that the File API in the Capacitor WebView is outdated and broken:
In the Screenshot I am debugging the App on an iPhone 8 with iOS 14.3 and you will notice the size of the File is always zero and the name property somehow holds the actual data. (e is an Blob).
The first example shows creating a File from a blob, but afterwards the file has size 0 and the name is the BlobArray.
const e = blob;
new File([e], 'asdf', {type: e.type})

The second example shows the basic MDN File example, which works fine in Chrome and Desktop Safari, but on mobile it also uses the string array as name
new File(["foo"], "foo.txt", {
  type: "text/plain",
});

I also tried this in just the iOS Safari Browser and it worked fine.
Therefore I have to assume that our Capacitor App uses an outdated Safari version.
Unfortunately I wasn't able to find any information on how to set the WebView/Safari version for Ionic/Capacitor.
Here is my setup:

*

*Device: iPhone 8

*iOS version: 14.3

*User-Agent of the ionic App:

Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148

*

*User-Agent of iOS Safari:

Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Mobile/15E148 Safari/604.1
Packages and versions:
    "@capacitor/cli": "2.4.6",
    "@capacitor/core": "2.4.6",
    "@capacitor/ios": "^2.4.6",
    "ionic": "^5.4.14",
    "@ionic/angular": "^5.4.1",
    "@ionic/angular-toolkit": "~2.0.0",
    "ionic-native": "^2.9.0",
    "@ionic-native/file-transfer": "^5.29.0",
    "cordova-plugin-file": "^6.0.2",

Is there a way to set the Safari Version for the WebView or might this be some case of misconfiguration on our part (because of the migration to capacitor)?

A: The only thing i can think of that would help, is try changing or updating to a different version of @capacitor/ios. This package is part of what controls the webview that capacitor uses. I don't think there is a way to directly set it.
I made a dummy project that uses "@capacitor/ios": "^2.4.5" and ran the second example you posted. Worked fine for me.

A: By looking at the File prototype in the debugger I noticed that the File constructor was completely different.
I googled the the code snippet and found out that the code is from the cordova-plugin-file package.
The plugin overwrites the global File variable.
Therefore the File Web API was not usable anymore.
By removing the plugin (and the plugin that depended on it) we were able to fix the issue.
Relevant Github Issue: https://github.com/apache/cordova-plugin-file/issues/453


text:
Q: Display Dictionaries in Tkinter Python I am written a simple Tkinter program and i am trying to display both my stock name and stock Quantity, but i find that only my stock name displays. My code is as follows:
import sys
from tkinter import *
from tkinter import ttk
import time
from datetime import datetime
now= datetime.now()
x = []
d = dict()
def quit():
    print("Have a great day! Goodbye :)")
    sys.exit(0)
def display():
    x_var.set(list(d))
def add(*args):
    global stock
    global d
    global Quantity
    stock = stock_Entry.get()
    Quantity = int(Quantity_Entry.get())
    if stock not in d:
        d[stock] = Quantity
    else:
        d[stock] += Quantity

root = Tk()
root.title("Homework 5 216020088")

x_var = StringVar()
x_var.set(x)

mainframe = ttk.Frame(root, padding="6 6 20 20")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))

ttk.Label(mainframe, text="you are accesing this on day %s of month %s of %s" % (now.day,now.month,now.year)+" at exactly %s:%s:%s" % (now.hour,now.minute,now.second), foreground="yellow", background="Black").grid(column=0, row = 0)

stock_Entry= ttk.Entry(mainframe, width = 60, textvariable="stock")
stock_Entry.grid(column=0, row = 1, sticky=W)
ttk.Label(mainframe, text="Please enter the stock name").grid(column=1, row = 1, sticky=(N, W, E, S))

Quantity_Entry= ttk.Entry(mainframe, width = 60, textvariable="Quantity")
Quantity_Entry.grid(column=0, row = 2, sticky=W)
ttk.Label(mainframe, text="Please enter the quantity").grid(column=1, row = 2, sticky=(N, W, E, S))

ttk.Button(mainframe, text="Add", command=add).grid(column=0, row=3, sticky=W)
ttk.Button(mainframe, text="Display", command=display).grid(column=0, row=3, sticky=S)
ttk.Button(mainframe, text="Exit", command=quit).grid(column=0, row=3, sticky=E)

ttk.Label(mainframe, textvariable= x_var).grid(column=0, row= 4, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
root.mainloop()

Now, this is only displaying my stock and not the Quantity, can you please help me or recommend what I should do?

A: Currently, in your display() function you are only changing x_var which refers to the stock.
Have you tried adding another tk.Label and bind a quantity variable to it?

A: You can try this:
import sys
from tkinter import *
from tkinter import ttk
import time
from datetime import datetime

now = datetime.now()
x = []
d = {}

def quit():
    print("Have a great day! Goodbye :)")
    sys.exit(0)

def display():
    x = []
    for key, value in d.items():
        x.append([key, value])
    print(x)
    x_var.set(x)

def add(*args):
    global stock
    global d
    global Quantity
    stock = stock_Entry.get()
    Quantity = int(Quantity_Entry.get())
    if stock not in d:
        d[stock] = Quantity
    else:
        d[stock] += Quantity

root = Tk()
root.title("Homework 5 216020088")

x_var = StringVar()
x_var.set(x)

mainframe = ttk.Frame(root, padding="6 6 20 20")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))

ttk.Label(mainframe, text="you are accesing this on day %s of month %s of %s" % (
now.day, now.month, now.year) + " at exactly %s:%s:%s" % (now.hour, now.minute, now.second), foreground="yellow",
          background="Black").grid(column=0, row=0)

stock_Entry = ttk.Entry(mainframe, width=60, textvariable="stock")
stock_Entry.grid(column=0, row=1, sticky=W)
ttk.Label(mainframe, text="Please enter the stock name").grid(column=1, row=1, sticky=(N, W, E, S))

Quantity_Entry = ttk.Entry(mainframe, width=60, textvariable="Quantity")
Quantity_Entry.grid(column=0, row=2, sticky=W)
ttk.Label(mainframe, text="Please enter the quantity").grid(column=1, row=2, sticky=(N, W, E, S))

ttk.Button(mainframe, text="Add", command=add).grid(column=0, row=3, sticky=W)
ttk.Button(mainframe, text="Display", command=display).grid(column=0, row=3, sticky=S)
ttk.Button(mainframe, text="Exit", command=quit).grid(column=0, row=3, sticky=E)

ttk.Label(mainframe, textvariable=x_var).grid(column=0, row=4, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
root.mainloop()


text:
Q: Can I extend IDEs suggestions by creating class collisions If a library I use, have a class that extends 2 other classes by the use of __call(), only the main extended class gets it's methods listed in the objects suggestions.
I noticed that if I make another php file in the project, where I put a class with the same name and namespace, and let it extend the other class, the IDE don't know witch one of them I'm referring to and gives me the suggestions for both of them, that way it suggests the methods from both of the extended classes.
This works sometimes, but in some case the IDE is to smart, and somehow know that my class isn't the real one, and only shows methods from the main extendsion.
Is there a better way to tell the IDE that a class in the library have more functions that it seams? Or a way that at least works every time?
Example:
<?php // index.php
    include(__DIR__ . "/lib.php");
    $c = new c();
    echo $c->s_a();
    echo $c->s_b(); // Accepted by the IDE
    $d = new d();
    echo $d->s_a();
    echo $d->s_b(); // Not acceted by the IDE

<?php // lib.php
    class a {
        function s_a() { return "a";}
    }
    class b {
        function s_b() { return "b";}
    }
    class c extends a {
        public $b;
        function __construct() {
            $this->b = new b();
        }
        function __call($name, $arguments) {
            return call_user_func_array(array($this->b, $name), $arguments);
        }
    }
    class d extends c {}

<?php // fake.php
    class c extends b {};

For $c the IDE don't know if it should use class c from lib.php or from fake.php, so it gives be a list with the methods of both.
For $d the that is of class d that extends c, it somehow know that its class c in file lib.php, so $d->s_b() are not sugested.


text:
Q: windows 10 add remove programs missing version info I'm a developer who is responsible for, among other things, the installer (and InstallScript project) for our product. We have 10 or so dependencies that sometimes cause issues for us. Our usual first stop when troubleshooting is Add/Remove Programs to see what is installed. On Win 7, the Version of a component is listed alongside the name of the installed packages. However, on Win 10, the version is missing. This is highly problematic when there are three Visual C++ 20xx Redistributables listed, but we can't easily see what the versions they are.
Has anyone else noticed this? Found a way to turn that info on with a tweak somehow? I can get the info from 'wmic', but that's a hard sell when I'm dealing with a customer on the phone.


text:
Q: What happens to your stuff related to a game if access is revoked? I mean hours, screenshots, achievements and all that stuff.
I'm asking because I'm currently testing a game and the devs plan to revoke all the testing keys given out for free. So I would lose access temporarily. Is it just hidden until you regain access, or is it completely gone?

A: If you're worried about screenshots, those are stored locally and can be moved elsewhere. You can access your screenshots folder by opening Steam, under View > Screenshots > Choose your game from the drop down > Show on Disk.
But, if the devs decide to remove the game from Steam, or if Steam themselves choose to remove a game (ex. if servers are offline for a multiplayer only game, Steam and Square Enix did this for a standalone multiplayer expansion to one of their games), then one would assume your achievements and playtime would not stay either. Those stats are likely buried in Steam somewhere, but accessing them from the Steam interface is likely impossible.
The other notable scenario is when Steam bans a game from their platform, like in the case with the horror game Devotion. If you purchased it while it was available on the store, it's still in your Library, but you cannot buy it anymore.


text:
Q: Issue in scons having both static and dynamic lib as target Hi have a Sconscript file that is used to build two different targets - a shared lib and a dynamic lib.
Issue the first time when I issue a build the static lib that is build is empty. There are no object in the shared lib.
However, if I again issue a build command and all shared object are already build this time shared lib is build correctly.
Includes for both shared and dynamic lib target have some common files
Structure for my Sconscript file looks as :
Import('module_env')
env = module_env.clone()

static_includes = ['inc1/', 'inc2']
static_sources = ['src1', 'src2']
#build static lib
env.Append(CPPPATH = static_includes)
lib = env.StaticLibrary(libname, static_sources)

#build dynamic lib
# same mechanism, parse through list of sources and build dynamic lib

A: How about this?
I've not tried it, but it should work..
Import('module_env')
env = module_env.clone()

static_includes = ['inc1', 'inc2']
static_source_dirs = ['src1', 'src2']
#build static lib
env.Append(CPPPATH = static_includes)

static_sources = []
for s in static_source_dirs:
    static_sources.extend(Glob(os.path.join(s,'*.c')))

static_objects = []
for s in static_sources:
    # note I'm constructing the target for the static object compile to have a different name than default.  You only need this if you are going to build the same sources also as shared objects.
    base_name = static_objects.extend("${SOURCE.basename}_static.$OBJSUFFIX",env.StaticObject(s))

lib = env.StaticLibrary(libname, static_objects)

#build dynamic lib
# same mechanism, parse through list of sources and build dynamic lib


text:
Q: Export function in Typescript I have a .ts file with a module and a function outside module like this:
$(function () {
   populate()
});

function populate() {
...
}

module portfolio.charts {
   export function foo(){
   ...
   }
}

Using Typescript compiler command tsc --declaration the declaration file is created. This .d.ts file contains the following code:
 function populate(): void;
 module portfolio.charts {
       function foo(): void;
 }

Why populate() function and portfolio.charts module are exported? I thought it was necessary the keyword export to export a function or a module. If I add the d.ts file as a dependency on another file I can use all functions and the module. Can I declare them private? Thanks and sorry for my english.

A: The TypeScript specification is a bit dry on this, so here are some examples.
Example 1
module MyModule {
    class MyClass {
        myFunction() {
            alert('Test');
        }
    }

    function myOtherFunction() {
        alert('Test Again');
    }
}

In this example, MyModule is a global module (it isn't inside of any other module) so this will appear in the definition file. MyClass,myFunction and myOtherFunction are invisible in the definition:
module MyModule {
}

So to make something visible in your declaration, it either...

*

*Needs to be in the global scope, like MyModule or like populate in your example, or

*Needs to be prefixed with the export keyword
In your example, point 1 applies.