text:
Q: Comma in front of square bracket - MDN docs MDN is my primary Javascript resource.
I often see a notation like ( currentValue[, index[, array]]) as in:
let new_array = arr.map(function callback( currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])

I'm surprised there's a square bracket in front of the comma. It looks like an invalid syntax to me.
I would highly appreciate it if somebody could give more information about this notation.

A:
The square brackets mean that the enclosed parameter is optional.

Refer MDN syntax section for more info.

A: That means the callback requires a currentValue as the first argument, and index and array are optional arguments.

A: It is an invalid JS syntax, and it would throw an error.
However, it is used to denote optional arguments as a pseudo-code.
The parts in the square brackets are considered optional (and in the real code the brackets should be omitted), so, you might call this function like:
let new_array = arr.map(function callback(currentValue) {
    // return element for new_array
})
//or
let new_array = arr.map(function callback(currentValue) {
    // return element for new_array
}, thisArg)
//or
let new_array = arr.map(function callback(currentValue, index) {
    // return element for new_array
})
//or
let new_array = arr.map(function callback(currentValue, index) {
    // return element for new_array
}, thisArg)
//or
let new_array = arr.map(function callback(currentValue, index, array) {
    // return element for new_array
})
//or
let new_array = arr.map(function callback(currentValue, index, array) {
    // return element for new_array
}, thisArg)

and each of them is valid.


text:
Q: Performance StringBuilder vs concatenation I tested a simple concatenation:
 string res = "";
 for (var i = 0; i < 1000; i++)
 {
     res += mystring;
 }
 return res;

and another with a StringBuilder object:
 StringBuilder builder = new StringBuilder();
 for (var i = 0; i < 1000; i++)
 {
     builder.Append(mystring);
 }
 return builder.ToString();

The bigger is the cycle, the better are the performances using the StringBuilder.
I would like to know the real reason of this result, I mean, that fact of creating, implementing an object, calling methods is faster than a simple string1 + string2?

A: Strings are immutable, so each += mystring creates a new object. In the StringBuilder case you're operating on one instance, hence the performance difference. You can improve the performance further by configuring the Capacity property. You can find more information on this issue in the documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nginx - ошибка при рестарте Установил на удаленный сервак nginx.
создал файл в nginx/sites-available с названием crm
server {
server_name yourdomainorip.com;

access_log off;

location /static/ {
    alias /opt/myenv/static/;
}

location / {
    proxy_pass http://127.0.0.1:8001;
    proxy_set_header X-Forwarded-Host $server_name;
    proxy_set_header X-Real-IP $remote_addr;
    add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}

И в файл nginx.conf происходит include моего файла из директории sites-enabled (была создана ссылка на файл из директории sites-available). B когда пытаюсь перезапустить nginx мне выходит такая ошибка
[emerg] unknown 'server' variable

В чем может быть ошибка?

A: Потому что нужно соблюдать иерархию nginx. Блок server всегда внутри http.
http {
    server {
         location / {
         }
    }
}

Подробнее написано в документации на официальном сайте.


text:
Q: Uses of category-theory I am a graduate student currently working my way through an introductory course in category theory.
A question I have for this theory is why it is usefull?
Now i know this is a rich theory that is being used in many fields in mathematics, for example we have encountered categorical notions in a (introductory) course of algebraic geometry. Here we defined a contravariant functor between the categories of k-varieties (with k an algebraically closed field) and the category of k-algebras with their respective morphisms.
However we did work with the notions of category-theory, we didn't use any specific theorems.
So to specify my question further: In what way does the work done in category theory help us in proving important theorems in other fields in mathematics? Or perhaps: Can you provide examples in which deep categorical theorems are applicable and usefull for proving hard problems in other fields of mathematics?
Any criticism on my way of posing this quesion is welcomed, this is my first post here!


text:
Q: How can I split one Excel Worksheet into multiple files based on date column? I need to split a worksheet with 10,000 rows into multiple Excel files based on the dates in column D. The file has 9 columns (A:I). Dates on column D are currently formatted as DD/MM/YYYY. I only want to split the file into MMM/YYYY so there are fewer files. Here is my code so far, it splits the worksheet into multiple files but when I open the files only the header has been copied over, not the data for relevant month & year.
How can I copy and paste all the data that's relevant to the MMM/YYYY in column D and how can I save all the split files into a specific folder like this one? C:\General\London\Clients
Sub SplitData()
'
' SplitData Macro

Dim objWorksheet As Excel.Worksheet
Dim nLastRow, nRow, nNextRow As Integer
Dim strColumnValue As String
Dim objDictionary As Object
Dim varColumnValues As Variant
Dim varColumnValue As Variant
Dim objExcelWorkbook As Excel.Workbook
Dim objSheet As Excel.Worksheet

Dim aCol As String
aCol = "D"

On Error GoTo err1

 With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.EnableEvents = False
 End With

Set objWorksheet = ActiveSheet
nLastRow = objWorksheet.Range("A" & objWorksheet.Rows.Count).End(xlUp).Row

Set objDictionary = CreateObject("Scripting.Dictionary")

 For nRow = 1 To nLastRow

    strColumnValue = Format(objWorksheet.Range(aCol & nRow).Value, "Report_mmm_yyyy")

    If objDictionary.Exists(strColumnValue) = False Then
       objDictionary.Add strColumnValue, 1
    End If
Next

varColumnValues = objDictionary.Keys

For i = LBound(varColumnValues) To UBound(varColumnValues)
    varColumnValue = varColumnValues(i)

    Set objExcelWorkbook = Excel.Application.Workbooks.Add

    Set objSheet = objExcelWorkbook.Sheets(1)
    objSheet.Name = objWorksheet.Name

    objWorksheet.Rows(1).EntireRow.Copy
    objSheet.Activate
    objSheet.Range("A1").Select
    objSheet.Paste

     For nRow = 1 To nLastRow
        If CStr(objWorksheet.Range(aCol & nRow).Value) = CStr(varColumnValue) Then

           objWorksheet.Rows(nRow).EntireRow.Copy

           nNextRow = objSheet.Range("A" & objWorksheet.Rows.Count).End(xlUp).Row + 1
           objSheet.Range("A" & nNextRow).Select
           objSheet.Paste
           objSheet.Columns("A:I").AutoFit
        End If
    Next
    objExcelWorkbook.SaveAs (CStr(varColumnValue))
Next

err1:
     With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
     End With

End Sub

A: The main thing was replacing
If CStr(objWorksheet.Range(aCol & nRow).Value) = CStr(varColumnValue) Then

with
If Format(objWorksheet.Range(aCol & nRow).Value, "Report_mmm_yyyy") = varColumnValue Then

But I made more changes in order to do the copy-pasting a bit quicker. As a side note, pasting is not a quick option, you could do something like TargetCell.Value = SourceCell.Value (in this case only values get transferred).
Sub SplitData()
  '
  ' SplitData Macro

  Dim objWorksheet As Excel.Worksheet
  Dim nLastRow As Integer, nRow As Integer, nNextRow As Integer
  Dim strColumnValue As String
  Dim objDictionary As Object
  Dim varColumnValues As Variant
  Dim varColumnValue As Variant
  Dim objExcelWorkbook As Excel.Workbook
  Dim objSheet As Excel.Worksheet
  Dim i As Long

  Dim aCol As String
  aCol = "D"

  On Error GoTo err1

  With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
    .EnableEvents = False
  End With

  Set objWorksheet = ActiveSheet
  nLastRow = objWorksheet.Range("A" & objWorksheet.Rows.Count).End(xlUp).Row

  Set objDictionary = CreateObject("Scripting.Dictionary")

  For nRow = 2 To nLastRow

    strColumnValue = Format(objWorksheet.Range(aCol & nRow).Value, "Report_mmm_yyyy")

    If objDictionary.Exists(strColumnValue) = False Then
      objDictionary.Add strColumnValue, 1
    End If
  Next

  varColumnValues = objDictionary.Keys

  For i = LBound(varColumnValues) To UBound(varColumnValues)
    varColumnValue = varColumnValues(i)

    Set objExcelWorkbook = Excel.Application.Workbooks.Add

    Set objSheet = objExcelWorkbook.Sheets(1)
    objSheet.Name = objWorksheet.Name

    objSheet.Rows(1).Value = objWorksheet.Rows(1).Value
    objWorksheet.Rows(1).Copy objSheet.Rows(1)

    nNextRow = 2
    For nRow = 1 To nLastRow
      If Format(objWorksheet.Range(aCol & nRow).Value, "Report_mmm_yyyy") = varColumnValue Then
        objWorksheet.Rows(nRow).Copy objSheet.Rows(nNextRow)
        nNextRow = nNextRow + 1
      End If
    Next
    objSheet.Columns("A:I").AutoFit
    ' Closing the workbook with changes saved
    objExcelWorkbook.Close True, CStr(varColumnValue)

  Next

err1:
  With Application
   .ScreenUpdating = True
   .Calculation = xlCalculationAutomatic
   .EnableEvents = True
  End With

End Sub

A: Sub SplitData()
  '
  ' SplitData Macro
Dim objWorksheet As Excel.Worksheet
  Dim nLastRow As Integer, nRow As Integer, nNextRow As Integer
  Dim strColumnValue As String
  Dim objDictionary As Object
  Dim varColumnValues As Variant
  Dim varColumnValue As Variant
  Dim objExcelWorkbook As Excel.Workbook
  Dim objSheet As Excel.Worksheet
  Dim i As Long
  Dim FPath As String
  FPath = Application.ActiveWorkbook.Path
Dim aCol As String
  aCol = "A"
On Error GoTo err1
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
    .EnableEvents = False
  End With
Set objWorksheet = ActiveSheet
  nLastRow = objWorksheet.Range("A" & objWorksheet.Rows.Count).End(xlUp).Row
Set objDictionary = CreateObject("Scripting.Dictionary")
For nRow = 2 To nLastRow
strColumnValue = Format(objWorksheet.Range(aCol & nRow).Value, "mmm_yyyy")

If objDictionary.Exists(strColumnValue) = False Then
  objDictionary.Add strColumnValue, 1
End If

Next
varColumnValues = objDictionary.Keys
For i = LBound(varColumnValues) To UBound(varColumnValues)
    varColumnValue = varColumnValues(i)
Set objExcelWorkbook = Excel.Application.Workbooks.Add

Set objSheet = objExcelWorkbook.Sheets(1)
objSheet.Name = objWorksheet.Name

objSheet.Rows(1).Value = objWorksheet.Rows(1).Value
objWorksheet.Rows(1).Copy objSheet.Rows(1)

nNextRow = 2
For nRow = 1 To nLastRow
  If Format(objWorksheet.Range(aCol & nRow).Value, "mmm_yyyy") = varColumnValue Then
    objWorksheet.Rows(nRow).Copy objSheet.Rows(nNextRow)
    nNextRow = nNextRow + 1
  End If
Next
objSheet.Columns("A:K").AutoFit
CheckDir (FPath & "\" & varColumnValue)
objExcelWorkbook.SaveAs FPath & "\" & varColumnValue & "\" & "Report.xlsx"
' Closing the workbook with changes saved
objExcelWorkbook.Close True, CStr(varColumnValue)

Next
err1:
  With Application
   .ScreenUpdating = True
   .Calculation = xlCalculationAutomatic
   .EnableEvents = True
  End With
End Sub
Function CheckDir(Path As String)
If Dir(Path, vbDirectory) = "" Then
    MkDir (Path)
End If

End Function


text:
Q: Android Bitmap: getPixel() color I have a photo which I load to a Bitmap. I checking color of some pixels. But in the picture sometimes something what should be for example red is a little bit more marron, magenta, orange etc, because of the light and other factors. I'm using method getPixel(x,y) which returns an int value of Color. Is any possibility to check if this int value is in interval which defines colors which are similar to red. Or is any website or something, where I can find any definitions or colors description?

A: Yes. From http://developer.android.com/reference/android/graphics/Color.html, the Color integer is of the format 0xffRRGGBB. (The ff is actually an alpha channel, i.e. opacity, but is usually opaque hence ff).
There are many sites which will enable you to enter such values to get a look at the color - for example http://www.colourchart.net/. You could pick the outer bounds of each color component.
You might also consider using Color.colorToHSV() which will enable you to specify the bounds in terms of hue, saturation and brightness instead of red, green and blue - this may be logically easier in your context.

A: Basicall RGB is not suitable for comparing colors, but there is a good color modell called HSV. So you should convert the RGB value to HSV then compare the Hue value of the colors with a threshold.
For example Hue value of the green color is 120, but you can accept the values between 90 and 150.
This link shows how to convert between the color modells: http://www.cs.rit.edu/~ncs/color/t_convert.html
More info about HSV modell: http://en.wikipedia.org/wiki/HSL_and_HSV


text:
Q: SOA Release management strategy Currently I have been asked to propose an automated release management solution for a large oracle SOA project. All code is stored on SVN repository and it would be nice if I could suggest something that would build, deploy, run test cases and produced reports for all projects on trunk. I know that I could do that by creating ant or maven scripts, but I would like to know if there is an open source alternative that handles all these complex stuff, without the need of so much coding.

A: I'm not sure what your requirements are. Are you looking to run tests on your production server?
Or, are you looking for a continuous integration server like Jenkins? Jenkins can run your unit tests every time you do a commit and send you a nice email if you fail any tests. You should only deploy after Jenkins says it is safe to do so. Note, there are other CI systems out there. I happen to use Jenkins at work.
This doesn't actually handle deploying and launching your updated service, but it's probably one step in the sequence.


text:
Q: How to add an item to start of an array in Java I am new to Java and I have an array
int [] A = {140,150,160,170,180,190}

I need to add infinity at the beginning of the array
like so:
int [] A = {inf,140,150,160,170,180,190}

I know from Python to do it like so:
A=[140,150,160,170,180,190]
A=[float('inf')]+A

I need a way to do that in Java as simple as Python without loops
It's important to say I need the array / list(A=[140,150,160,170,180,190]) to be given with the code.

A: You can use Java ArrayList that implements List interface and has a method add(int,E)
So, you can use something like list.add(0, myObj);.


text:
Q: ComboBox Event triggers a RadioButton to be checked and populate a listbox I'm a noob when it comes to XAML and MVVM and am constructing a maintenance screen for our project.  The combobox is populated from a list retrieved from a database.  When a value selected from the combobox is I want to read one of the properties from the selected item, and check 1 of 2 radiobuttons and then populate a listbox using that same selected item.  Here's my xaml:
<UserControl x:Class="StatementPrinting.Client.Views.Setup.TestView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         xmlns:telerikRibbonView="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.RibbonView"
         xmlns:examples="clr-namespace:Telerik.Windows.Controls.RichTextBoxUI"
         xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
<telerik:RadBusyIndicator IsBusy="{Binding BusyDetail.IsBusy}" BusyContent="{Binding}"
                          IsIndeterminate="True"
                          BusyContentTemplate="{StaticResource BusyIndicatorBusyContentTemplate}">
    <!--<Grid MinWidth="650" MinHeight="400">-->
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Column="0" Grid.Row="0" Margin="5,0,5,20">
            <TextBlock FontWeight="Bold" FontSize="18">Report Group Setup</TextBlock>
            <TextBlock>Here you edit whether the selected group is printed or not and what items are part it.</TextBlock>
        </StackPanel>
        <Grid Grid.Column="0" Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
            <DockPanel Grid.Column="0" Grid.Row="0">
                <TextBlock VerticalAlignment="Center" Margin="0,0,15,0">Select a Group:</TextBlock>
                <ComboBox x:Name="cmbReportGroup" IsEditable="False" ItemsSource="{Binding ReportGroups}" DisplayMemberPath="Description" SelectedValuePath="Name" SelectedItem="{Binding SelectedReportGroup}" />
            </DockPanel>
            <DockPanel Grid.Column="1" Grid.Row="0" Margin="40,0,0,0">
                <TextBlock VerticalAlignment="Center">Printing?</TextBlock>
                <RadioButton x:Name="printYesRadioButton" Margin="10" GroupName="printRadioButtonGroup" Content="Yes">
                    <RadioButton.Style>
                        <Style TargetType="{x:Type RadioButton}">
                            <Setter Property="IsEnabled" Value="True"/>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding ElementName=cmbReportGroup, Path=SelectedItem}" Value="{x:Null}">
                                    <Setter Property="IsEnabled" Value="False"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </RadioButton.Style>
                </RadioButton>
                <TextBlock Name="Or_TextBlock" VerticalAlignment="Center" Margin="5,10,5,10">or</TextBlock>
                <RadioButton x:Name="printNoRadioButton" Margin="10" GroupName="printRadioButtonGroup" Content="No">
                    <RadioButton.Style>
                        <Style TargetType="{x:Type RadioButton}">
                            <Setter Property="IsEnabled" Value="True" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding ElementName=cmbReportGroup, Path=SelectedItem}" Value="{x:Null}">
                                    <Setter Property="IsEnabled" Value="False"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </RadioButton.Style>
                </RadioButton>
            </DockPanel>
        </Grid>
        <Grid Grid.Column="0" Grid.Row="2" Margin="20">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
            <StackPanel Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="0" Margin="0,0,0,10">
                <TextBlock>
                    Change the items that belong to this group:
                </TextBlock>
            </StackPanel>
            <DockPanel Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2">
                <TextBlock DockPanel.Dock="Top" Margin="0,0,0,5">Current Notices:</TextBlock>
            </DockPanel>
            <DockPanel Grid.Column="2" Grid.Row="1">
                <TextBlock DockPanel.Dock="Top" Margin="0,0,0,5">Available Notices:</TextBlock>
            </DockPanel>
            <DockPanel Grid.Column="0" Grid.Row="2">
                <ListBox></ListBox>
            </DockPanel>
            <DockPanel Grid.Column="1" Grid.Row="2">
                <Button DockPanel.Dock="Top" VerticalAlignment="Center" Margin="10">
                    <Image Source="c:\_MicrosProjects\StatementPrinting\DEV\StatementPrinting\StatementPrinting.Client\Resources\arrow-left-10.png"/>
                </Button>
                <Button DockPanel.Dock="Top" VerticalAlignment="Center" Margin="10">
                    <Image Source="c:\_MicrosProjects\StatementPrinting\DEV\StatementPrinting\StatementPrinting.Client\Resources\arrow-right-10.png"/>
                </Button>
            </DockPanel>
            <DockPanel Grid.Column="2" Grid.Row="2">
                <ListBox></ListBox>
            </DockPanel>
        </Grid>
    </Grid>
</telerik:RadBusyIndicator>

The codebehind:
using Mbs.Common.Instrumentation;
using Mbs.Mvvm.Core;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using StatementPrinting.Client.ViewModels.Base;
using StatementPrinting.DataLayer;
using StatementPrinting.Domain;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StatementPrinting.Client.ViewModels.Setup
{
    public class TestViewModel : SecurityTabbedWorkspaceViewModelBase
    {
        public TestViewModel(IScreenViewModel screenVM, string connectionString, IEventAggregator eventAggregator)
        {
            this.SetNameAndTitle("Report Group Setup");
            this.ScreenVM = screenVM;
            this.ConnectionString = connectionString;
            this.AppEventAggregator = eventAggregator;

            this.SetSecurity();
            LoadReportGroups();
        }

        private readonly ObservableCollection<ReportGroup> _ReportGroups = new ObservableCollection<ReportGroup>();
        public ObservableCollection<ReportGroup> ReportGroups
        {
            get { return _ReportGroups; }
        }

        private string _SelectedIndex;
        public string SelectedIndex { get; set; }

        private ReportGroup _SelectedReportGroup;
        public ReportGroup SelectedReportGroup
        {
            get { return _SelectedReportGroup; }
            set
            {
                _SelectedReportGroup = value;

                MessageBox.Show("Print: " + SelectedReportGroup.Print.ToString());
                SetPrintOption(SelectedReportGroup.Print);

                this.RaisePropertyChanged("SelectedReportGroup");
            }
        }

        private void SetPrintOption(bool PrintOption)
        {
            MessageBox.Show("Print 2: " + SelectedReportGroup.Print.ToString());
            if (SelectedReportGroup.Print)
            {
                //printYesRadioButton.IsChecked = true;
            }
            else
            {
                //printNoRadioButton.IsChecked = true;
            }
        }

        private void LoadReportGroups()
        {
            try
            {
                CancellationToken cancelToken = this.GetCancellationToken();
                this.BusyDetail.CanBeCanceled = true;
                this.BusyDetail.TurnOnBusyIndicator("Loading...");

                Task<List<ReportGroup>> loadTask = Task.Factory.StartNew<List<ReportGroup>>(() =>
                {
                    using (StatementPrintingContext context = new StatementPrintingContext(ContextConnectionStringHelper.GetEntitiesConnectString(this.ConnectionString)))
                    {
                        return context.ReportGroups.ToList();
                    }
                },
                cancelToken);
                var completedTask = loadTask.ContinueWith((t) =>
                {
                    if (t.Exception != null)
                    {
                        this.RaiseErrorMessageNotification(t.Exception.ToString());
                    }
                    else
                    {
                        t.Result.ForEach(r => this.ReportGroups.Add(r));
                        //
                        //    or
                        //
                        //foreach (var r in t.Result.ToList())
                        //{
                        //    ReportGroups.Add(r);
                        //}
                    }
                },
                cancelToken, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (Exception ex)
            {
                this.RaiseErrorMessageNotification(ex.ToString());
            }
            finally
            {
                this.BusyDetail.TurnOffBusyIndicator();
            }
        }

        private DelegateCommand _SaveChangesCommand;
        public DelegateCommand SaveChangesCommand
        {
            get
            {
                if (_SaveChangesCommand == null)
                {
                    _SaveChangesCommand = new DelegateCommand(() =>
                    {
                        try
                        {
                            using (var db = new StatementPrintingContext(ContextConnectionStringHelper.GetEntitiesConnectString(this.ConnectionString)))
                            {
                                // ******Do any database changes here!********
                                // . . .
                                // . . .

                                this.SaveChangesCommand.RaiseCanExecuteChanged();
                                this.RaiseMessageNotification("Changes saved successfully.");
                            }
                        }
                        catch (Exception ex)
                        {
                            this.RaiseErrorMessageNotification(ex.Message);
                            ExceptionLogger.Instance.WriteExceptionTrace(ex, this.GetType().ToString());
                        }
                    },
                    () =>
                    {
                        // *******Put conditional code here!***********
                        // . . .
                        // . . .

                        return true;
                    });
                }
                return _SaveChangesCommand;
            }
        }

        private DelegateCommand _TestCommand;
        public DelegateCommand TestCommand
        {
            get
            {
                if (_TestCommand == null)
                {
                    _TestCommand = new DelegateCommand(() =>
                    {
                        try
                        {
                            this.TestCommand.RaiseCanExecuteChanged();
                        }
                        catch (Exception ex)
                        {
                            this.RaiseErrorMessageNotification(ex.Message);
                            ExceptionLogger.Instance.WriteExceptionTrace(ex, this.GetType().ToString());
                        }
                    },
                    () =>
                    {
                        return true;
                    });
                }
                return _TestCommand;
            }
        }
    }
}

Just to reiterate, a person selects an item from the combobox.  When they do that, it reads the print value of that item that is stored in the database and then checks either the "Yes" or "No" radiobutton.  This is the main issue I'm having right now.  Thanks for your help.

A: Add a Property in Your ViewModel named it SelectedName and Bind it to SelectedValue of the ComboBox:
<ComboBox x:Name="cmbReportGroup" IsEditable="False" ItemsSource="{Binding ReportGroups}" DisplayMemberPath="Description" SelectedValuePath="Name" SelectedItem="{Binding SelectedReportGroup}" SelectedValue="{Binding SelectedName}" />

and in the ViewModel in the Setter of the SelectedName Property add your code:
public string SelectedName
    {
        get { return _SelectedName; }
        set
        {
            _SelectedName= value;
            this.RaisePropertyChanged("SelectedName");

            // do your data retrieving form database ...
            CheckPrintYesOrNow();
        }
    }

for the RadioButton you can use the same way add a bool Property in your ViewModel and bind to.


text:
Q: Issue with a structure and pointers I Have this struct:
struct BaseLayerComponent {

    //Info
    int posX = -99999;
    int posY = -99999;

    //Texture
    std::string textureName = NULL_STR;
    std::string localTexture = NULL_STR;
    std::string remoteTexture = NULL_STR;
    std::string remoteTextureParent = NULL_STR;
};

It is store in a custom array class (Actually pointers of this struct are stored).
The class that mainly using it, is WD_MainWorld which inherit from WD_2DWorld
Those two class have a function call Init(), in this function a BaseLayerComponent is created, then we store the ref of this last into the grid (the custom array).
But later when I want to use it,  in another function I have a weird bug (Debug function is custom function created for debugging):
systems->ErrSys->Debug(layer0.Grid[X][Y]->textureName);
systems->ErrSys->Debug(layer0.Grid[X][Y]->remoteTexture);

Here the first is working perfectly BUT the second give me an access read violation (Note that I've also tested it with remoteTextureParent but same issue).
So for debugging purpose I've created a funciton called show:
virtual void show() {
    systems->ErrSys->Debug(layer0.Grid[0][0]->remoteTexture);
}

And after a long time of research I've discovered where it started to bug:
this is at the end of the Init function of the parent class (last thing called);
   show();
   return true;
}

here show() works perfectly BUT when we leave the function it stop working:
if (!world->Init())
{
    systems->LastErrMsg = "Main World can't be initialized";
    ErrSubmit(systems->ErrSys, EXO::ERR::LOG_TYPE::ERR, ERR_MAIN_WORLD_INIT, systems->LastErrMsg, "Main World Class - Can't be Initialized");
    return false;
}
else
    world->show();

Remember that textureName still working and I have tested pointer are still good (still the same address).
Thanks, in advance.
UPDATE:
I have changed the show function to test everything:
virtual void show() {

    std::cout << layer0.Grid[0][0] << std::endl;

    std::cout << layer0.Grid[0][0]->posX << std::endl;
    std::cout << layer0.Grid[0][0]->posY << std::endl;

    systems->ErrSys->Debug(layer0.Grid[0][0]->localTexture);
    systems->ErrSys->Debug(layer0.Grid[0][0]->textureName);
    systems->ErrSys->Debug(layer0.Grid[0][0]->remoteTextureParent);
    systems->ErrSys->Debug(layer0.Grid[0][0]->remoteTexture);
}

and here is the Output:
Before the end of Init():
0073EED8
0
0
src/World/DGI_New_Tile_Normal.png
DGI_New_Tile_Normal.png
http://rpg.exodiastudio.com/
TEMP/World/Main/Textures/DGI_New_Tile_Normal.png

After Init():
0073EED8
-858993460
0
  <- There is a space here
  <- and here the error (which is not same as previous, see below):

Unhandled exception at 0x756422A2 in RPGBoards.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0073E784.
UPDATE 2 (For Jabberwocky):
Init in WD_MainWorld:
    //First we create a EGE world in the main interface (Using connection)
    EXO::IO::INTERFACES_GAME_TYPE Type = EXO::IO::INTERFACES_GAME_TYPE::GM;
//Creating Builder (What world need);
EXO::TREATEMENT::WORLD::World_Builder Builder;
Builder.background = "black";
Builder.isMovable = true;

//Sending all textures
systems->FTP->CreateFolder(root, 0);
systems->FTP->CreateFolder(root + "Main", 0);
systems->FTP->CreateFolder(root + "Main/Textures", 0);

//Creating default tile
EXO::TREATEMENT::WORLD::BaseLayerComponent comp;
comp.posX = 0;
comp.posY = 0;
comp.localTexture = "src/World/DGI_New_Tile_Normal.png";
comp.textureName = "DGI_New_Tile_Normal.png";

//First we update the online texture path
comp.remoteTexture = root + "Main/Textures/" + comp.textureName;
comp.remoteTextureParent = "http://rpg.exodiastudio.com/";

//now we send texture
bool isDone = false;
systems->FTP->SendFile(comp.localTexture, comp.remoteTexture, 0, &isDone);

while (!isDone);

Builder.baseLayerComponents.push_back(comp);
AddTile(comp);

systems->connection->CallFunction("AddWorld", &Type, &Builder);

show();
return WD_2DWorld::Init();

Init in the parent class WD_2DWorld:
//First we check if systems are active because the class need it
if (systems == nullptr || GC == nullptr)
    return false;

//Creating all layers
for (int i = 1; i <= 9; i++) {
    EXO::TREATEMENT::WORLD::Layer newLayer;
    newLayer.layerLevel = i;
    layers.push_back(newLayer);
}

//set has initialized and return
classInitialized = true;

return true;


text:
Q: Finding in a predefined set of text options Say, I want to see if a DOM element is a block. I can write it in three ways, depending on my mood:
// first way
if (el.currentStyle.display == "block" || el.currentStyle.display == "inline-block" || el.currentStyle.display == "table-cell")

// second way
var blocks = {"block": 1, "inline-block": 1, "table-cell": 1};
if (el.currentStyle.display in blocks)//

// third way
if (el.currentStyle.display.match(/block|inline-block|table-cell/))

I have mixed feeling about all of them. First is too verbose once I have more than one option. Second contains those arbitrary values in the object (where I put 1s this time). Third looks like overkill. (What exactly is bad about overkilling?)
Do you know another, better way? If no, any cons I am missing about these three ways?
Javascript only, please.

A: I like the third way; I don't think it looks like overkill at all. If you need an even shorter way then this works too:
el.currentStyle.display.match(/(e-)?(block|cell)/)

But that's not very readable...
It might be worth abstracting it all away by extending the String prototype:
String.prototype.matches = function(what) {
    return (',' + what + ',').indexOf(',' + this + ',') > -1;
};

// Using it:
el.currentStyle.display.matches('block,inline-block,table-cell');

A: If we're primarily aiming for readability, and if this is happening more than once -- perhaps even if it is just once -- I'd move the test to a function.  Then define that function whichever way you like -- probably option 1, for max simplicity there.
Overkill?  Possibly.  But a gift to the programmer who wants to scan and understand the code 6 months from now.  Probably you :-)
function isBlock(el) {
  return (el.currentStyle.display == "block" ||
          el.currentStyle.display == "inline-block" ||
          el.currentStyle.display == "table-cell");
}

// ...

if (isBlock(el)) {
  // do something
}

A: Can't you use the 2nd way but check if it's undefined and then skip the ": 1" part. I haven't tested though.

A: It looks like you need an inArray function, here is one from the top search result:
Array.prototype.inArray = function (value) {
  var i;
  for (i=0; i < this.length; i++) {
    if (this[i] === value) {
      return true;
    }
  }
  return false;
};

Then the forth way would look like this:
if (['block','inline-block','table-cell'].inArray(el.currentStyle.display))

Or in a more readable manner:
var isBlock = ['block','inline-block','table-cell'].inArray(el.currentStyle.display);

A: My prefered solution for this is:
'block||inline-block||table-cell'.indexOf( el.currentStyle.display ) >= 0

I think that this will use native code of the string and be way more efficient than the array & iteration method.


text:
Q: how to compare a vector of pointers and string ? struct compare{

string k;
compare(string a) : k(a){}
bool operator()(const product* t)const{
return (t->productdetails.getName()<k);
}

};

void cashier::calculate(string s,vector<product*> &a){

//this is lambda (tried to use it ,but doesn't work)
auto comp=[](const product* t, const string b)
{
  return (b < t->productdetail.getName());
};

if (std::binary_search ( a.begin(), a.end(),s, compare(s)))
    cout << "found!\n";
else
    std::cout << "not found.\n";
 }

I'm stuck in this part for a long time.
the vector holds product(class) pointer. product pointer points to productdetail which has two variables (name and price)
I need to look up (string s) in the vector and if the string s is in vector (product->productdetail.getName()), I need to return the price..
how to compare proudct* and string s ?
my teacher gave me advice that i need to make anther string conversion function since the comparing type need to be the same..
(I tried to use lambda and it didn't work and changed to compare function)

A: I concur with @Fureeish, using bare pointers in modern C++ is not a good choice, unless you absolutely have to.
That said, writing predicates for the standard library requires a good knowledge of the library methods you are using. Have a look at std::binary_search documentation. A simple application is to search for the same type as you are searching through. In other words your needle is the same type as what is in your haystack. Here is an example:
#include <iostream>
#include <vector>
#include <algorithm>

class product {
public:
    class product_details {
    public:
        std::string name;
        double price;
    };

    product_details productDetails{};

    product(std::string const &name, double price) : productDetails{ name, price} {}
};

struct product_compare {
    bool operator()(product const &lhs, product const &rhs) {
        return lhs.productDetails.name < rhs.productDetails.name;
    }
};

int main(int argc, char *argv[])
{
    std::vector<product> producList{
            { "toaster", 74.99 },
            { "blender", 103.99 },
            { "slow cooker", 142.99 }
    };

    product_compare productCompare{};
    std::sort(producList.begin(), producList.end(), productCompare);

    product searchProduct{"slow cooker", 142.99};
    if (std::binary_search(producList.begin(), producList.end(), searchProduct, productCompare))
        std::cout << "Found!\n";
    else
        std::cout << "Not found!\n";
}

But that lacks elegance. Your needle can be a different type, the answer is actually in this SO question. Here is a rewrite that takes advantage of this. This idiom is a bit more complicated to write but is better related to the actual problem and therefore easier to understand. Ultimately you never know which side of the compare is going to be needle and which side is going to be hay. So you have to write your compare predicate to accept both comparisons.
#include <iostream>
#include <vector>
#include <algorithm>

class product {
public:
    class product_details {
    public:
        std::string name;
        double price;
    };

    product_details productDetails{};

    product(std::string const &name, double price) : productDetails{ name, price} {}
};

struct product_compare {
    bool operator()(std::string const &lhs, product const &rhs) {
        return lhs < rhs.productDetails.name;
    }

    bool operator()(product const &lhs, std::string const &rhs ) {
        return lhs.productDetails.name < rhs;
    }
};

// Used by std::sort
bool operator<(product const &lhs, product const &rhs) {
    return lhs.productDetails.name < rhs.productDetails.name;
}

int main(int argc, char *argv[])
{
    std::vector<product> producList{
            { "toaster", 74.99 },
            { "blender", 103.99 },
            { "slow cooker", 142.99 }
    };

    product_compare productCompare{};
    std::sort(producList.begin(), producList.end());

    if (std::binary_search(producList.begin(), producList.end(), std::string("slow cooker"), productCompare))
        std::cout << "Found!\n";
    else
        std::cout << "Not found!\n";
}


text:
Q: Error when editing wikimedia page in a protected namespace with api
*

*We have a mediawiki running.

*We created a custom namespace ("NS_FOO").

*We added a namespace (write) protection for "NS_FOO" (LocalSettings.php)

*for all users except our custom user-group "QM".

*We added pages to this custom namespace.

Everythings works just fine, i.e. no user can edit these pages except members of the group "QM".

*We try to edit this page with the api (botpassword of a user who is member of the QM group)

We get the error:
code:"protectednamespace"
info:"You do not have permission to edit pages in the FOO namespace."

This is a part of the LocalSettings.php:
define("NS_FOO", 3000);
define("NS_FOO_TALK", 3001);

$wgExtraNamespaces[NS_FOO] = "foo";
$wgExtraNamespaces[NS_FOO_TALK] = "foo_talk";

# add protection
$wgNamespaceProtection[NS_foo] = ['QM-edit-rights'];

# Allow QM to edit "FOO" namespace
$wgGroupPermissions['QM']['QM-edit-rights'] = true;

$wgGroupPermissions['QM']['edit'] = true;
$wgGroupPermissions['QM']['createpage'] = true;
$wgGroupPermissions['QM']['delete'] = true;
etc.

I am aware of the fact that there are millions of things which can go wrong using the api. But in this case it only seems to depend on the protected namespace. Because:

*

*The api edits work just fine, when changing pages in the default namespace. So there doesn't seem to be any problem changing pages with our api call in general.

*On the other side, the edits in the protected namespace work fine when done personally and not using the api.

But the combination of editing a page in a protected namespace WITH the api creates the error quoted above.
My understanding of the bot password (or api access) is that it should inherit the group rights of the user. And if the user is allowed to edit a page the bot should also be able to do it (if not further restricted - which this bot password is NOT).
Does the bot password need some extra rights for protected namespaces?
Or are bots in general not able to change pages in protected namespaces?
Is this a mediawiki bug?

A:
My understanding of the bot password (or api access) is that it should inherit the group rights of the user.

Bot password sessions inherit specific rights of the user. When managing the bot password, you have a list of rights bundles (grants), defined in $wgGrantPermissions, and you can select which ones to inherit. If the relevant grant is not checked, or no grant is defined for that right in the first place, the bot password session will not have that right. (IOW, the bot will only have those rights for which it has both a userright and a grant.)
So, you'd need something like
$wgGrantPermissions['editpage']['QM-edit-rights'] = true;

in addition to the above.


text:
Q: Presence of diamond in network profile is dependent on which site you accessed it from Tapping a user from a specific site view in the iOS app will take you to their network profile, with the originating site selected as the top account. If the user is a moderator on the originating site, their name will be displayed with a diamond:

However, if you access the same user's profile from a site where they are not a moderator, the diamond will disappear. While this in some ways technically makes sense, having the diamond displayed in the "network profile" view being dependent on whichever account happens to show up on top seems more confusing than anything else, especially given that moderator diamonds are not displayed next to the account itself.
Ignoring the fact that it may make more sense to go to the site-specific profile in the first place, moderator diamonds should be displayed consistently next to the user name in network profile, and should be displayed next to the site name in the accounts list.

A: This will be fixed in the next build.


text:
Q: Unable to create file with VideoWriter using OpenCV 3.1 on iOS 10 My goal is to create a basic proof of concept app where I open an existing MP4 video, process the frames, and write it back, primarily through OpenCV.
While I am able to open the video and process the frames, I have not been able to write it back successfully. What little literature I have found online has either not worked, or is unanswered.
The following is the first approach I tried for writing the file:
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyVideo" ofType:@"mp4"];
std::string filename = path.UTF8String;
self.videoCapture = cv::VideoCapture(filename);
if(!self.videoCapture.isOpened()) std::cout << "Unable to open source" << std::endl;

int width = static_cast<int>(self.videoCapture.get(CV_CAP_PROP_FRAME_WIDTH));
int height = static_cast<int>(self.videoCapture.get(CV_CAP_PROP_FRAME_HEIGHT));
double fps = self.videoCapture.get(CV_CAP_PROP_FPS);
cv::VideoWriter videoWriter("output.mp4", self.videoCapture.get(CV_CAP_PROP_FOURCC), fps, cv::Size(width, height));
if (!videoWriter.isOpened())
{
    std::cout << "Unable to open writer" << std::endl;
    return;
}

One immediate issue with this approach is that the values I obtain for width, height, fps and pretty much anything else related to CV_CAP is always 1. I read about it being an issue with certain file types, but it occurs with mp4, mov and mkv, so that did not help.
Next, I hard coded values using what I knew to be true for the video, but was getting the same result with it unable to open the writer.
NSString *path = [[NSBundle mainBundle] pathForResource:@"MyVideo" ofType:@"mp4"];
std::string filename = path.UTF8String;
self.videoCapture = cv::VideoCapture(filename);
if(!self.videoCapture.isOpened()) std::cout << "Unable to open source" << std::endl;
cv::VideoWriter videoWriter("output.mkv", CV_FOURCC('m','p', '4', 'v'), 30, cv::Size(1920, 1080));

if (!videoWriter.isOpened())
{
    std::cout << "!!! Output video could not be opened" << std::endl;
    return;
}

For what it is worth, I did read about there being issues with the output file existing, so I deleted the file & changed the name, without any luck.
I also changed the FOURCC value to several other formats & updated the output name accordingly, again, without any success.

A: I also struggled with cv::VideoWriter because it couldn't save processed video too.
Finally I gave up this, now I'm using AVAssetWriter : (
I hope somebody solve this problem.

A: int fourcc = cv::VideoWriter::fourcc('m', 'p', '4', 'v');//mp4
double rate = 30; // frame rate
int capture_width = 480;
int capture_height = 640;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *mp4_path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"video.mp4"];
writer.open([mp4_path UTF8String],
            cv::CAP_AVFOUNDATION,
            fourcc,
            rate,
            cv::Size(capture_width, capture_height),
            true);

work well for me.


text:
Q: Crazydomain setting for parseapp.com I am desperately trying to connect my domain to something.parseapp.com. I have tried a few settings but none of them works. My settings are in the following picture.

A: I search around and find a solution for you here: http://blog.kchandrahasa.com/blog/2013/07/09/crazydomains-crazy-issues/
Below is a summary with my own experience, just in case the link is dead in future.

In order to change CNAME records in Crazy Domains, you have to pay for it. For a cheaper solution, you can change the nameservers of your domain to other free DNS management services like:

*

*cloudns.net

*freedns.afraid.org

*CloudFlare
I suggest you to use CloudFlare since it's more powerful and support many features. Proceed as below:

*

*Create an account in Cloudflare

*Once you login, you will have to add your domain name.

*It will scan your DNS settings.

*After it finishes scanning, proceed with "I'm done entering my DNS records".

*Take note of the 2 nameservers Cloudflare provides you at this step.

Now come back to Crazy Domains, login to your account.

*

*Click on Domains and click Update Name Servers under DNS settings.

*Delete the existing crazy domains name servers and enter the two nameservers given by Cloudflare. It will take up to 24 hours, but in my experience it will be just some hours.

Now come back at CloudFlare and enter your CNAME as instructed by Parse.


text:
Q: Is String thread safe like StringBuffer or not? In Java, as stated in the javadoc:

*

*The StringBuffer class is thread-safe.

*The StringBuilder class is NOT thread-safe

But is the String class considered as thread-safe or not ?

A: According to documentation:

Strings are constant; their values cannot be changed after they are
  created. String buffers support mutable strings. Because String
  objects are immutable they can be shared.

Because Strings are immutable, they are thread safe.


text:
Q: Real life applications of Cauchy Sequences? What are some examples of real life applications of Cauchy sequences?(examples that could be modeled.) I read somewhere that the long term effects of weather on a construction could be modeled by a Cauchy sequence. Is it true? How is there convergence? Or could you give any other examples?

A: There is possibly no direct real-life application of Cauchy's Sequence. But if you go through Banach Contraction Theorem then you may find some examples which have application in real life.

A: Some intersting real life applications of Cauchy's Sequences are mentioned here: sensor data, stock market quotes, speech signals. In his book "A Wavelet Tour of Signal Processing: The Sparse Way", Stephane Mallat uses Cauchy's Sequences as well. Béla Lantos and Lőrinc Márton utilize them too, see their book "Nonlinear Control of Vehicles and Robots". I assume you will find a lot other examples in the area of Physics that are linked to industrial applications.


text:
Q: Особенности работы сессий laravel Всем привет. Планирую делать корзину для интернет-магазина. Не понимаю некоторые особенности сессий у laravel (драйвер - файловая система). Несколько вопросов:

*

*После окончания времени жизни сессии, она удаляется полностью и пользователь получает пустую корзину? Или же она регенерируется и пользователь этого не видит? Если удаляется, то есть ли смысл ставить время жизни сессии = неделя?

*Что правильнее: хранить данные о товарах в корзине в сессии или в куках пользователя?

*Как лучше сделать корзину: создать отдельную модель или сделать отдельный пакет для неё? Пакеты еще ни разу не создавал, поэтому точно не знаю, как правильнее поступить в данном случае.

Заранее спасибо!


text:
Q: mat-sidenav column not working, fxLayout="column" I've added a mat-sidenav navigation to my site and set it to be a column, but it's not working.
this is my HTML code:

  <mat-toolbar style="height: 7vh; color: honeydew; background-color:rgb(43, 44, 44); position: relative;" lang="en" dir="ltr" class="mat-elevation-z8" >

      <button [routerLink]="['']" routerLinkActive="active"  style="background-color: rgb(43, 44, 44);">
        <mat-icon>home</mat-icon>
      </button>

MaxProfit.TEB

      <button mat-icon-button (click)="sidenav.toggle()" dir="rtl">
        <mat-icon>menu</mat-icon>
      </button>

  </mat-toolbar>
  <mat-sidenav-container fxFlexFill class="example-container" style="color: honeydew; background-color:rgb(43, 44, 44); min-height: 93vh !important" lang="en" dir="rtl">
    <mat-sidenav color="honeydew" style="background-color: rgb(43, 44, 44); color: honeydew;" #sidenav mode="over"  opened="false" fxHide.gt-sm="true">

        <mat-icon>input</mat-icon>הרשמה
        <mat-icon>account_circle</mat-icon>התחברות
        <mat-icon>check_circle_outline</mat-icon>תנאי שימוש
        <mat-icon>border_color</mat-icon>אקדמיה
        <mat-icon>attach_money</mat-icon>MetaTrader4
        <mat-icon> directions_walk</mat-icon>Journry
        <mat-icon>feedback</mat-icon>ביקורות
        <mat-icon>message</mat-icon>משוב

    </mat-sidenav>
    <mat-sidenav-content fxFlexFill>
      <router-outlet class="routerstyle"></router-outlet>
    </mat-sidenav-content>
  </mat-sidenav-container>

what I get on the site:
mobile

desktop


text:
Q: ASP.NET Identity in MVC client using IdentityServer causes loop I have an Asp.NET Core application that uses IdentityServer for authentication.  This works fine.
Now I want to use ASP.NET Core Identity in my application for managing roles, claims, etc.
The documentation saysI should add service.AddIdentity ... for that.
However, when I add that in my client to the Startup.cs, the login with IdentityServer no longer works.
I will be redirected to IdentityServer, login and redirected back to the client (this works fine)
However, then my client throws an error about authorization and redirects to the IdentityServer again. This causes an endless loop
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44331/signin-oidc application/x-www-form-urlencoded 5297
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Cookies signed in.
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 184.9938ms 302
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44331/
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: Identity.Application was not authenticated. Failure message: Unprotect ticket failed
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Index", controller = "Home", page = "", area = ""}. Executing action TestApplication.Controllers.HomeController.Index (TestApplication)
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:Information: AuthenticationScheme: oidc was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action TestApplication.Controllers.HomeController.Index (TestApplication) in 15.4912ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 29.286ms 302
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44331/signin-oidc application/x-www-form-urlencoded 5297
-- and it starts all over again

Does anyone have a clue what I'm doing wrong?
Here's my Startup.cs
public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment environment)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(environment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddTransient<ApiService>();
        services.AddSingleton(Configuration);
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie()
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = 'Cookies';
            options.UseTokenLifetime = true;

            options.Authority = 'https://localhost:44350;
            options.RequireHttpsMetadata = true;

            options.ClientId = Configuration.GetValue<string>("IdentityServer:ClientId");
            options.ClientSecret = Configuration.GetValue<string>("IdentityServer:ClientSecret");
            options.ResponseType = "code id_token token"

            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = true;

            options.Scope.Add("api1");
            options.Scope.Add("offline_access");
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("email");

            options.TokenValidationParameters.NameClaimType = "name";
            options.TokenValidationParameters.RoleClaimType = "role";

        });

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
            .AddJsonOptions(x => x.SerializerSettings.NullValueHandling = NullValueHandling.Ignore);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
               name: "areas",
               template: "{area:exists}/{controller}/{action}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

    }
}

A: On Identity Server side , you can create Profile Service to make IDS4 include role claim when issuing tokens . Then on client side you can  map the role claim from your JWT Token to your claim principle . You can refer to  code sample from here .
To manage users or roles , you can provide API endpoint in your identity server4 application , or create a new application as another resource to manage your database , you client application will acquire access token for accessing you new application form Identity Server 4 , send request by appending token to HTTP Authorization header for management API calls .

A: If anyone else comes across this and still wants to authenticate via IdSrv but manage users outside of IdSrv, replace this:
services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

in your client app with this
services.AddIdentityCore<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    //.AddDefaultUI() // use standard identity UI forms for register, forgot pass etc.
    .AddDefaultTokenProviders();

Uncomment the line above to use the standard UI forms from MS identity but beware that you'll have to override the default sign in logic afterwards. This is done by adding the identity scaffolding to your project.


text:
Q: Sorting displayed results vs. entire results If I present a user with a table of results from a database which only displays the first 1000 rows, what does the user expect when they re-sort the table?  Do they expect only the displayed results to be sorted (on the client) or do they expect an entirely new result set from the db, sorted accordingly?
For example, if the first (default) table view displays rows A through D, should reversing the sort on that column simply display D through A, or Z through W?
Or should I provide the user with the option to do either?  If so, how could I succinctly phrase the options?

A: There's no added value to reversing data you can already see (consider the 'head' and 'tail' commands in unix). Even if you only get a snapshot of data, you still need to have access to all of it.


text:
Q: How do I take action instantly when up arrow key is pressed in C? I am writing a C program on Linux platform where I need to show something on console instantly when the up or down arrow key is pressed without ^[[A or ^[[B getting written on the console and then pressing enter to show something on the console.
I am simulating linux shell and I want to impelement linux shell like history feature where when we press up and down key, recent entered commands are displayed. I am using GNU history library to implement this. How do I do that?

A: we can write our own function for get char like disable  echo flag ,read character and again enable the echo flag .So that you can see the print on console.
#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int getch();

int main(int argc, char **argv) {
   int ch;
   for (;;) {
      ch = getch();
      if(ch == 27)
         printf("UP arrow\n");
      else if(ch ==28)
         printf("down arrow\n");
      else
         printf("wrong input \n");

      break;
   }
   return 0;
}

int getch() {
   struct termios oldtc;
   struct termios newtc;
   int ch;
   tcgetattr(STDIN_FILENO, &oldtc);
   newtc = oldtc;
   newtc.c_lflag &= ~(ICANON | ECHO);
   tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
   ch=getchar();
   tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
   return ch;
}


text:
Q: Showing that the map that takes $u_0$ to solution $u(t)$ is self-adjoint Let $u$ and $v$ be the solution of the heat equation
$$w'(t) - \Delta w(t) =0$$
with initial data $u_0$ and $v_0$ respectively, and with either homogeneous Dirichlet or Neumann BCs on a bounded domain $\Omega$.
Define $S(t):L^1(\Omega) \to L^2(\Omega)$ by $S(t)u_0 = u(t)$ be the mapping taking initial data to the solution evaluated at time $t$.
How can I show that $S(t)$ is self-adjoint without using Green's kernel? It amounts to showing that
$$(u(t), v_0)_{L^2} = (v(t), u_0)_{L^2}$$
but I cannot prove it.

A: For $0 \le s \le t$, the selfadjointness of $\Delta$ gives
\begin{align}
          \frac{\partial}{\partial s}(u(t-s),v(s))
           & =-(u'(t-s),v(s))+(u(t-s),v'(s)) \\
           & =-(\Delta u(t-s),v(s))+(u(t-s),\Delta v(s)) =0.
\end{align}
Therefore,
$$
             (u(t-s),v(s)|_{s=0} = (u(t-s),v(s))|_{s=t} \\
             (u(t),v_0)  =(u_0,v(t)).
$$


text:
Q: Failed to start SSH Agent: java.lang.RuntimeException: Cannot parse ssh-agent output: '' - TeamCity System configs:
TeamCity Master: Windows Server 2012 R2 Standard
TeamCity Agent: Windows Server 2022 Datacenter
Infrastructure is in AWS with the correct security groups and open ports needed (9090, 22, 443, etc)
I keep getting this error. I have checked that the ssh-agent is in the path. Keys  are added to Teamcity master (private) and GitHub (public key, clone is successful). Windows firewall is also open for port exceptions.

A: Seems like TeamCity is incompatible with Windows OpenSSH variant. I suggest you to uninstall it (via powershell or windows features) and install git for windows instead which in bundled with all ssh tools.


text:
Q: Uncaught TypeError: r.use is not a function Делаю с помощью webpack'a и при обновлении выдаёт ошибку:
build.js:1 Uncaught TypeError: r.use is not a function

var Vue = require('vue')
var VueRouter = require('vue-router')
var About = require('./src/about.vue')
var Brand = require('./src/brand.vue')

Vue.use(VueRouter)

var router = new VueRouter({
    routes: [
        { path: '/about', component: About},
        { path: '/brand', component: Brand}
    ]
})

new Vue ({
    el: '#app',
    router: router
})
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  padding-bottom: 80px;
}

a {
  color: inherit;
  text-decoration: none;
}

img {
  max-width: 100%;
}

/* HEADER */

header {
  height: 80px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}

.header-wrapper {
  max-width: 1000px;
  margin: 0 auto;
  padding: 18px 30px 20px;
}

.logo {
  display: block;
  height: 40px;
  object-fit: cover;
  float: left;
  margin-right: 50px;
}

nav {
  font-size: 16px;
  padding: 10px 0 14px;
  height: 40px;
  font-weight: 500;
}

nav a {
  margin: 0 26px 0 0;
  color: rgba(10, 10, 10, 1);
}

nav a.router-link-active {
  color: rgba(255, 255, 255, 1);
}

.grey {
  color: rgba(187, 187, 187, 1);
}

/* PAGES */

section {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

section h2 {
  font-size: 100px;
  color: black;
  display: block;
  width: 960px;
}

.projects {
  background-color: rgba(242, 199, 48, 1);
}

.brands {
  background-color: rgba(75, 192, 226, 1);
}

.contacts {
  background-color: rgba(126, 102, 241, 1);
}

/* BLOG */

.blog {
  display: flex;
  align-items: center;
  flex-direction: column;
  padding-top: 80px;
}

.blog__post {
  width: 100%;
  position: relative;
  float: left;
  height: 350px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.blog__post img {
  height: 100%;
  width: 100%;
  object-fit: cover;
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  filter: brightness(70%);
}

.blog__post h3 {
  font-size: 32px;
  line-height: 32px;
  color: #fff;
  font-weight: 300;
  text-align: center;
  z-index: 2;
}

.blog__post a {
  height: 48px;
  border: 1px solid #fff;
  border-radius: 4px;
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  line-height: 46px;
  display: block;
  z-index: 2;
  padding: 0 48px;
  text-align: center;
}

.blog__post a:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* POST */

.post {
  padding-top: 80px;
}

.post img {
  width: 100%;
  object-fit: cover;
  height: 500px;
  object-position: top center;
  margin-bottom: 40px;
}

.post h2 {
  font-size: 29px;
  line-height: 30px;
  color: #1f1f1f;
  margin: 0 auto 40px;
  max-width: 640px;
}

.post p {
  font-family: "PT Serif", serif;
  font-size: 18px;
  color: rgba(0, 0, 0, 0.6);
  line-height: 28px;
  margin: 0 auto 50px;
  max-width: 640px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Vue-router</title>
    <link rel="stylesheet" href="src/style.css">

       <router-view></router-view>

<template>

Хоп хей лалей

</template>

<template>

Бренды

</template>

A: Вместо require from, так как require - это синтаксис Node.js, а Import/from - ES6


text:
Q: Mpdf table not taking full width though putting inline width Printing a table with 795 rows and three column like category, sub category, questions. Grouping categories and subcategories using rowspan. And every categories contains more than 150 questions. In every other table with fewer data printing perfectly but this table with 795 data not printing with full width though using inline css. Please help how to resolve this issue. Thanks in advance

A: I'm not sure about your query, I suspect you are try to print the table with 100% with. Please try the below code
$html = '

                 ....
                 ....
                 ....

              .....
              .....

';
$mpdf->WriteHTML($html);


text:
Q: How to expand equations of bigger degree I am 8th grade, and I have to solve this equation (I got it from a problem when I simplified):
$$ x^4 + 6x^3 + 11x^2 + 6x - 24 = 0 $$
I looked at some solutions in online solvers, but I don't understand how I should guess that $6x^3 = -x^3 + 7x^3$ or $11x^2 = -7x^2 + 18x^2$. I would be very grateful if you can explain to me how to expand it and solve it.

A: One can easily see that $x=1$ is a solution to the given equation. Thus, the given expression will be given as a product of $(x-1)$ with a polynomial of 3rd degree. More specifically :
$$x^4 + 6x^3 + 11x^2 + 6x - 24 = (x-1)(ax^3 + bx^2 + cx + d)$$
Now, you can expand the right hand side and calculate $a,b,c$ and $ d$.
$$x^4 + 6x^3 + 11x^2 + 6x - 24 = ax^4 + bx^3 + cx^2 + dx - ax^3 - bx^2 - cx - d$$
$$\Leftrightarrow$$
$$x^4 + 6x^3 + 11x^2 + 6x - 24 = ax^4+ (b-a)x^3 + (c-b)x^2 + (d-c)x-d$$
For the equation to hold, each polynomial term must be equal, thus the coefficient of each of the $x^4,x^3,x^2,x$ terms must be equal and of course the constants. Thus, $a,b,c$ and $d$ are given as :
$$\begin{cases} x^4 = ax^4 \\ 6x^3=(b-a)x^3 \\ 11x^2 = (c-b)x^2 \\ 6x = (d-c)x \\ -24=-d\end{cases} \implies \begin{cases} a=1 \\ b=7 \\ c= 18\\ d = 24\end{cases}$$
Doind that, gives $a=1, b=7, c=18$ and $d=24$. Thus :
$$ax^3 + bx^2 + cx + d = x^3+7x^2+18x+24$$
You can apply any of the ways you've been taught to solve polynomials of 3rd degree and you shall get :
$$x^3+7x^2+18x+24 = 0 \Leftrightarrow (x+4)(x^2+3x+6) = 0$$
Thus the initial expression can be written as :
$$x^4 + 6x^3 + 11x^2 + 6x - 24 = 0 \Leftrightarrow (x-1)(x+4)(x^2+3x+6) =0$$
This means that the solutions to the equation are $x=1$ and $x=-4$, since the quadratic involved has a negative discriminant, thus no real solutions. Of course, if you're interested to solve over complex numbers, then you'd consider the complex numbers that satisfy the quadratic as well.

A: Hint
$$24=x(x+1)(x+2)(x+3)$$
Set $x(x+3)=y$ to form a quadratic equation in $y$

A: Tiny improvement to Rebellos' solution:
Once you see that $$x^4 + 6x^3 + 11x^2 + 6x - 24 = (x-1)(ax^3 + bx^2 + cx + d)$$
it's more efficient to do polynomial division rather than multiplying the RHS and forming linear equations.
        x^3 + 7x^2 + 18x + 24
       -------------------
x - 1 | x^4 + 6x^3 + 11x^2 + 6x - 24
        x^4 - x^3
        ----------
              7x^3
              7x^3 - 7x^2
              -----------
                     18x^2
                     18x^2 - 18x
                     ------------
                            24x
                            24x - 24
                            --------
                                   0


text:
Q: Preventing shift key from setting map into zoom mode we have the following problem in a legacy (GMaps V2) application: we show a info window upon clicking on a marker. A pop-up is displayed and the user enters an annotation. If the user presses the shift key (for capitalizing letters), the map goes into "zoom mode" (the hand cursor changes into the arrow cursor, and, should the user move the mouse cursor outside the info window, he sees the red rubber-band rectanlge for zooming). Upon closing the window, the map is stuck in the zoom mode, with the red zoom rectangle showing. This only goes away after the user clicks, drags and the map zooms.
Is there a way to prevent the shift key to set the map mode? (I had a look at the KeyDragZoom library, but this didn't solve the problem.) I also tried many workaround for canceling the events, stop bubbling etc, to no avail.
Thanks in advance

A: in this way you can disable keyboard inputs:
 var ui = map.getDefaultUI();
 ui.keyboard = false;
 map.setUI(ui);

A: Look at the reference documentation. You can specify the key which activates the drag zoom:

key   String  The hot key to hold down to activate a drag zoom, shift |
  ctrl | alt. Note that the altshift.

So, I would try to set it to null or "alt".


text:
Q: Why does BLOCKCHAIN.COM API only return recipient BASE58 addresses and omits BECH32s? Following this post, I am trying to access all transactions within the #630873 block in the bitcoin blockchain.
import requests

r = requests.get('https://blockchain.info/block-height/630873?format=json')
data = r.json()

When inspecting the (0-indexed) 4th transaction within this block (via data['blocks'][0]['tx'][4]['out']), I get this:
[{'n': 0,
  'script': '0014d0aba2c93bac0fcafafe43f2ad39d664ba51910d',
  'spent': False,
  'tx_index': 0,
  'type': 0,
  'value': 19571491},
 {'addr': '1A7tWftaGHohhGcJMVkkm4zAYnF53KjRnU',
  'n': 1,
  'script': '76a9146406a0a47d4ed716f6ddf2eeca20c725932763f188ac',
  'spending_outpoints': [{'n': 0, 'tx_index': 0}],
  'spent': True,
  'tx_index': 0,
  'type': 0,
  'value': 3928145371}]

Only the addr of the second recipient of this transaction is included. On the blockchain.com website this transaction looks like:

The bc1q6z469jfm4s8u47h7g0e26wwkvja9rygdqpeykd address is visible there. How to access it through the API?
The unaccessible address has BECH32 format, while the accessible one has BASE58 (which information I get by clicking on the address on the website). Those transactions which I was able to retrieve the reciepient address, had BASE58 format.
Link to the block I am talking about..

A: The Blochchain.com API does not fully support bech32 addresses yet.
So you could use another provider such as Blockstream or Blockchair.
Or you can also derive the addresses from the P2WPKH script. For example using BitcoinLib (Disclaimer: my library):
from bitcoinlib.transactions import script_deserialize
from bitcoinlib.keys import Address

locking_script = '0014d0aba2c93bac0fcafafe43f2ad39d664ba51910d'
scr = script_deserialize(locking_script)
a = Address(hashed_data=scr['hashes'][0], script_type=scr['script_type'])
print(a.address)


text:
Q: Converting Typesafe Config type to java.util.Properties The title talks by itself, I have a Config object (from https://github.com/typesafehub/config) and I want to pass it the a constructor which only supports java.util.Properties as argument.
Is there an easy way to convert a Config to a Properties object ?

A: You can try my scala wrapper https://github.com/andr83/scalaconfig. Using it convert config object to java Properties is simple:
val properties = config.as[Properties]

A: Here is a way to convert a typesafe Config object into a Properties java object. I have only tested it in a simple case for creating Kafka properties.
Given this configuration in application.conf
kafka-topics {
  my-topic {
    zookeeper.connect = "localhost:2181",
    group.id = "testgroup",
    zookeeper.session.timeout.ms = "500",
    zookeeper.sync.time.ms = "250",
    auto.commit.interval.ms = "1000"
  }
}

You can create the corresponding Properties object like that:
import com.typesafe.config.{Config, ConfigFactory}
import java.util.Properties
import kafka.consumer.ConsumerConfig

object Application extends App {

  def propsFromConfig(config: Config): Properties = {
    import scala.collection.JavaConversions._

    val props = new Properties()

    val map: Map[String, Object] = config.entrySet().map({ entry =>
      entry.getKey -> entry.getValue.unwrapped()
    })(collection.breakOut)

    props.putAll(map)
    props
  }

  val config = ConfigFactory.load()

  val consumerConfig = {
    val topicConfig = config.getConfig("kafka-topics.my-topic")
    val props = propsFromConfig(topicConfig)
    new ConsumerConfig(props)
  }

  // ...
}

The function propsFromConfig is what you are mainly interested in, and the key points are the use of entrySet to get a flatten list of properties, and the unwrapped of the entry value, that gives an Object which type depends on the configuration value.

A: As typesafe config/hocon supports a much richer structure than java.util.propeties it will be hard to get a safe conversion.
Or spoken otherwise as properties can only express a subset of hocon the conversion is not clear, as it will have a possible information loss.
So if you configuration is rather flat and does not contain utf-8 then you could transform hocon to json and then extract the values.
A better solution would be to implement a ConfigClass and populate the values with values from hocon and passing this to the class you want to configure.

A: It is not possible directly through typesafe config. Even rending the entire hocon file into json does provide a true valid json:
ex:
"play" : {
    "filters" : {
            "disabled" : ${?play.filters.disabled}[
            "play.filters.hosts.AllowedHostsFilter"
        ],
            "disabled" : ${?play.filters.disabled}[
            "play.filters.csrf.CSRFFilter"
        ]

    }
}

That format is directly from Config.render
as you can see, disabled is represented twice with hocon style syntax.
I have also had problems with rendering hocon -> json -> hocon
Example hocon:
  http {
   port = "9000"
   port = ${?HTTP_PORT}
 }

typesafe config would parse this to
{
  "http": {
    "port": "9000,${?HTTP_PORT}"
  }
}

However if you try to parse that in hocon - it throws a syntax error. the , cannot be there.
The hocon correct parsing would be 9000${?HTTP_PORT} - with no comma between the values. I believe this is true for all array concatenation and substitution


text:
Q: mongoose bulk insert in real time This is the detailed case :
A user click on button "Create Codes" which will be generating 50000 codes randomly and save them in a collection "codes" in the format similar to this
[{
    _id : "_id"
    code : "abc",
    orderId : "id",
    status : "status"
},
{
    _id : "_id"
    code : "def",
    orderId : "id",
    status : "status"
}]

I am using bulk.insert() -> bulk.execute() from bulk API and it is taking 1.30 - 2 minutes. Keeping user experience in mind how it can be done more quickly and also user will be seeing or downloading these codes right after completion of this process. I am open for suggestions if anything else can be done by changing the process flow to make it fast for the user.
Thanks in advance.

A: If your random logic is not complicated, you can generate all 50000 records inside mongodb.
This is an instruction on how to put js scripts inside mongo and run it there
https://www.mongodb.com/blog/post/boosting-javascript-from-mongo-shell-to-nodejs


text:
Q: SQLAlchemy error on left join I am new to SQLAlchemy and I am trying to achieve this SQL:
SELECT
    node.*,
    alarms.*
FROM
    node
        LEFT JOIN
            alarms ON alarms.nodeid = node.nodeid
WHERE
    node.foreignid IN ('foreignid_1','foreignid_2','foreignid_3')
ORDER BY node.nodeid;

I come up with this statement:
stmt = session.query(Node, Alarms).outerjoin(Alarms, Alarms.nodeid == Node.nodeid).filter(Node.foreignid.in_(['foreignid_1','foreignid_2','foreignid_3'])).order_by(asc(Node.nodeid))
results = stmt.all()

The generated SQL looks like:
SELECT
    node.nodeid AS node_nodeid,
    node.dpname AS node_dpname,
    node.nodecreatetime AS node_nodecreatetime,
    node.nodeparentid AS node_nodeparentid,
    node.nodetype AS node_nodetype,
    node.nodesysoid AS node_nodesysoid,
    node.nodesysname AS node_nodesysname,
    node.nodesysdescription AS node_nodesysdescription,
    node.nodesyslocation AS node_nodesyslocation,
    node.nodesyscontact AS node_nodesyscontact,
    node.nodelabel AS node_nodelabel,
    node.nodelabelsource AS node_nodelabelsource,
    node.nodenetbiosname AS node_nodenetbiosname,
    node.nodedomainname AS node_nodedomainname,
    node.operatingsystem AS node_operatingsystem,
    node.lastcapsdpoll AS node_lastcapsdpoll,
    node.foreignsource AS node_foreignsource,
    node.foreignid AS node_foreignid,
    alarms.alarmid AS alarms_alarmid,
    alarms.eventuei AS alarms_eventuei,
    alarms.dpname AS alarms_dpname,
    alarms.nodeid AS alarms_nodeid,
    alarms.ipaddr AS alarms_ipaddr,
    alarms.serviceid AS alarms_serviceid,
    alarms.reductionkey AS alarms_reductionkey,
    alarms.alarmtype AS alarms_alarmtype,
    alarms.counter AS alarms_counter,
    alarms.severity AS alarms_severity,
    alarms.lasteventid AS alarms_lasteventid,
    alarms.firsteventtime AS alarms_firsteventtime,
    alarms.lasteventtime AS alarms_lasteventtime,
    alarms.firstautomationtime AS alarms_firstautomationtime,
    alarms.lastautomationtime AS alarms_lastautomationtime,
    alarms.description AS alarms_description,
    alarms.logmsg AS alarms_logmsg,
    alarms.operinstruct AS alarms_operinstruct,
    alarms.tticketid AS alarms_tticketid,
    alarms.tticketstate AS alarms_tticketstate,
    alarms.mouseovertext AS alarms_mouseovertext,
    alarms.suppresseduntil AS alarms_suppresseduntil,
    alarms.suppresseduser AS alarms_suppresseduser,
    alarms.suppressedtime AS alarms_suppressedtime,
    alarms.alarmackuser AS alarms_alarmackuser,
    alarms.alarmacktime AS alarms_alarmacktime,
    alarms.managedobjectinstance AS alarms_managedobjectinstance,
    alarms.managedobjecttype AS alarms_managedobjecttype,
    alarms.applicationdn AS alarms_applicationdn,
    alarms.ossprimarykey AS alarms_ossprimarykey,
    alarms.x733alarmtype AS alarms_x733alarmtype,
    alarms.x733probablecause AS alarms_x733probablecause,
    alarms.qosalarmstate AS alarms_qosalarmstate,
    alarms.clearkey AS alarms_clearkey,
    alarms.ifindex AS alarms_ifindex,
    alarms.eventparms AS alarms_eventparms
FROM
    node
        LEFT OUTER JOIN
            alarms ON alarms.nodeid = node.nodeid
WHERE
    node.foreignid IN ('foreignid_2' , 'foreignid_1', 'foreignid_3')
ORDER BY node.nodeid ASC

But it also throws this error (from iPython):
In [86]: stmt = session.query(Node, Alarms).outerjoin(Alarms, Alarms.nodeid == Node.nodeid).filter(Node.foreignid.in_(['foreignid_1','foreignid_3','foreignid_2'])).order_by(asc(Node.nodeid))

In [87]: results = stmt.all()
---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
<ipython-input-87-1110c354b407> in <module>()
----> 1 results = stmt.all()

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/orm/query.pyc in all(self)
   2113
   2114         """
-> 2115         return list(self)
   2116
   2117     @_generative(_no_clauseelement_condition)

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/orm/query.pyc in __iter__(self)
   2225         if self._autoflush and not self._populate_existing:
   2226             self.session._autoflush()
-> 2227         return self._execute_and_instances(context)
   2228
   2229     def _connection_from_session(self, **kw):

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/orm/query.pyc in _execute_and_instances(self, querycontext)
   2240                         close_with_result=True)
   2241
-> 2242         result = conn.execute(querycontext.statement, self._params)
   2243         return self.instances(result, querycontext)
   2244

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.pyc in execute(self, object, *multiparams, **params)
   1447                                                 object,
   1448                                                 multiparams,
-> 1449                                                 params)
   1450         else:
   1451             raise exc.InvalidRequestError(

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_clauseelement(self, elem, multiparams, params)
   1582             compiled_sql,
   1583             distilled_params,
-> 1584             compiled_sql, distilled_params
   1585         )
   1586         if self._has_events:

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1696                                 parameters,
   1697                                 cursor,
-> 1698                                 context)
   1699             raise
   1700

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
   1689                                     statement,
   1690                                     parameters,
-> 1691                                     context)
   1692         except Exception, e:
   1693             self._handle_dbapi_exception(

/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.8-py2.6-linux-x86_64.egg/sqlalchemy/engine/default.pyc in do_execute(self, cursor, statement, parameters, context)
    329
    330     def do_execute(self, cursor, statement, parameters, context=None):
--> 331         cursor.execute(statement, parameters)
    332
    333     def do_execute_no_params(self, cursor, statement, context=None):

InternalError: (InternalError) current transaction is aborted, commands ignored until end of transaction block
 'SELECT node.nodeid AS node_nodeid, node.dpname AS node_dpname, node.nodecreatetime AS node_nodecreatetime, node.nodeparentid AS node_nodeparentid, node.nodetype AS node_nodetype, node.nodesysoid AS node_nodesysoid, node.nodesysname AS node_nodesysname, node.nodesysdescription AS node_nodesysdescription, node.nodesyslocation AS node_nodesyslocation, node.nodesyscontact AS node_nodesyscontact, node.nodelabel AS node_nodelabel, node.nodelabelsource AS node_nodelabelsource, node.nodenetbiosname AS node_nodenetbiosname, node.nodedomainname AS node_nodedomainname, node.operatingsystem AS node_operatingsystem, node.lastcapsdpoll AS node_lastcapsdpoll, node.foreignsource AS node_foreignsource, node.foreignid AS node_foreignid, alarms.alarmid AS alarms_alarmid, alarms.eventuei AS alarms_eventuei, alarms.dpname AS alarms_dpname, alarms.nodeid AS alarms_nodeid, alarms.ipaddr AS alarms_ipaddr, alarms.serviceid AS alarms_serviceid, alarms.reductionkey AS alarms_reductionkey, alarms.alarmtype AS alarms_alarmtype, alarms.counter AS alarms_counter, alarms.severity AS alarms_severity, alarms.lasteventid AS alarms_lasteventid, alarms.firsteventtime AS alarms_firsteventtime, alarms.lasteventtime AS alarms_lasteventtime, alarms.firstautomationtime AS alarms_firstautomationtime, alarms.lastautomationtime AS alarms_lastautomationtime, alarms.description AS alarms_description, alarms.logmsg AS alarms_logmsg, alarms.operinstruct AS alarms_operinstruct, alarms.tticketid AS alarms_tticketid, alarms.tticketstate AS alarms_tticketstate, alarms.mouseovertext AS alarms_mouseovertext, alarms.suppresseduntil AS alarms_suppresseduntil, alarms.suppresseduser AS alarms_suppresseduser, alarms.suppressedtime AS alarms_suppressedtime, alarms.alarmackuser AS alarms_alarmackuser, alarms.alarmacktime AS alarms_alarmacktime, alarms.managedobjectinstance AS alarms_managedobjectinstance, alarms.managedobjecttype AS alarms_managedobjecttype, alarms.applicationdn AS alarms_applicationdn, alarms.ossprimarykey AS alarms_ossprimarykey, alarms.x733alarmtype AS alarms_x733alarmtype, alarms.x733probablecause AS alarms_x733probablecause, alarms.qosalarmstate AS alarms_qosalarmstate, alarms.clearkey AS alarms_clearkey, alarms.ifindex AS alarms_ifindex, alarms.eventparms AS alarms_eventparms \nFROM node LEFT OUTER JOIN alarms ON alarms.nodeid = node.nodeid \nWHERE node.foreignid IN (%(foreignid_1)s, %(foreignid_2)s, %(foreignid_3)s) ORDER BY node.nodeid ASC' {'foreignid_1': 'foreignid_1', 'foreignid_3': 'foreignid_3', 'foreignid_2': 'foreignid_2'}

I just don't understand what is the error while the generated SQL is good.
Thank you.

A: Your exception has nothing to do with your generated SQL, which is exactly what you wanted.
Your database connection is in the wrong state; a transaction was aborted (probably due to an integrity error somewhere) and no new transaction was started, and your database didn't like that.
While experimenting with SQLAlchemy from an iPython prompt, it's probably better to turn auto-commit on, so you don't have to deal with the intricacies of transaction management.


text:
Q: Why does my method throw a NoSuchMethodError? I have implemented successfully the reflectionEquals method, with a list of excluded fields.
return  EqualsBuilder.reflectionEquals(this, obj, new String[] {"files", "notes", "status"});

However, I recently compiled my program on Java 1.5 and now I get the following error when the program hits the above line:

java.lang.NoSuchMethodError:
  org.apache.commons.lang.builder.EqualsBuilder.=
  reflectionEquals(Ljava/lang/Object;Ljava/lang/Object;[Ljava/lang/String;)Z

If anyone has an insight on why the method does not exist at runtime, I would appreciate it

A: Every NoSuchMethodError that I've ever encountered has (eventually) been found to be a mismatch between the version of an external library on the classpath at compile time vs. the version of the library on the classpath at runtime (i.e. - in this case, you would have a different version of apache commons on your classpath when the application is compiled than when it is running.)
The method was definitely there when your code was compiled - or a compiler error would've been thrown.
Check the versions of commons-lang.jar on your classpaths - I'm betting you'll find a mismatch.
It's worth noting that this is NOT a MISSING jar file - that would throw a ClassNotFoundException (maybe eventually followed by a NoClassDefFoundError.)

A: This is likely a var args problem. Be sure to recompile everything in java 1.5 and be sure you are running it on java 1.5, and be sure you reference the same jar at compilation as at runtime.

A: You may have an older version on your runtime classpath.
Get the latest version of Apache Commons Lang


text:
Q: Explain the values returned by readNetFromCaffe's forward method net = cv2.dnn.readNetFromCaffe(prototxt, model)
detections = net.forward()

The detections will have 4D array with shape (1, 1, 200, 7). What are the different values there?
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]

The above loop gets confidence value at the 3rd dimension provide is for row number and 4th dimension is the column number, so it is pretty much clear that the object is detected with that much confidence or probability. But I could't understand the other parameters.
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])

to create a box, the above code is used with 3 to 6 columns and its values. So what are these values in columns 2 to 6?
Below code to reproduce the values...
from imutils.video import VideoStream
import imutils
import numpy as np
import cv2
import argparse
import time

# construct the argument parser
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True, help="path to caffe deploy prototxt file")
ap.add_argument("-m", "--model", required=True, help="path to pre-trained caffe model")
ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum confidence required")
args = vars(ap.parse_args())

# MODEL - load the model which will be used to predict
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

# INPUT - start video to capture frames
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
# vs = VideoStream(usePiCamera=True).start()  # this is to stream video for Raspberry Pi camera
# vs = FileVideoStream(path='/path to file')  # this is to get video content from file
time.sleep(2)  # allow the cam to warm up

# for live streaming, while loop will be required to capture frames
while True:
    frame = vs.read()
    frame = imutils.resize(frame, width=400)

    # get the dimensions of the frame
    print('shape of frame:', frame.shape)
    (h, w) = frame.shape[:2]

    # blob the frame
    blob = cv2.dnn.blobFromImage(frame, scalefactor=1.0,
                                 size=(300, 300), mean=(104.0, 177.0, 123.0))

    # use the blob for detection
    net.setInput(blob)
    detections = net.forward()
    print(detections)
    # loop over the detections
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        if confidence < args['confidence']:
            continue

        # create box
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        (startX, startY, endX, endY) = box.astype("int")

        # draw the box on the face
        text = "{:.2f}%".format(confidence * 100)
        y = startY - 10 if startY - 10 > 10 else startY + 10
        cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), thickness=2)
        cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)

    # show on screen
    cv2.imshow("frame", frame)
    if cv2.waitKey(1) & 0xFF == 27:
        break

cv2.destroyAllWindows()
vs.stop()

A: the first column represents the class id to which it belongs
the second column represents the confidence value, is there any object in the frame or not by comparing it with confidence threshold
[3:7] i.e. 3,4,5,6 columns represents the coordinates/points to create a box around the object, they are stored as numpy array hence to be converted in int type to make a box.


text:
Q: Acumatica Processing Screen Updating ARTran Custom Field Needs To Also Update Custom Table field We have a custom processing screen that is updating a custom field called UsrDateNotified in the ARTran table where the UsrDateNotified is prior to the RevisionDateReceived in a custom table ItemBaseDocument.  We also need to update the UsrDateNotified field in table ItemBaseDocument which is linked to the InventoryID in ARTran.  Our current code below validates for updating the ARTran table, but we are struggling with how to also update the related ItemBaseDocument for the selected ARTran records.  What is the right approach for this scenario?
using System;
using System.Collections;
using System.Linq;
using PX.Data;
using PX.SM;
using PX.Objects.AR;
using PX.Objects.CR;
using PX.Objects.IN;

namespace DocCenter
{
  public class UpdateLastNotified : PXGraph<UpdateLastNotified>
  {
    public PXFilter<UpdateLastNotifiedFilter> MasterView;
    public PXCancel<UpdateLastNotifiedFilter> Cancel;

    [PXFilterable]

    public PXSelect<ARTran> DetailsView;

 public UpdateLastNotified()
    {
   Cancel.SetCaption("Clear Filter");
   this.DetailsView.Cache.AllowInsert = false;
   this.DetailsView.Cache.AllowDelete = false;
   this.DetailsView.Cache.AllowUpdate = true;
    }

protected virtual IEnumerable detailsView()
{
UpdateLastNotifiedFilter filter = MasterView.Current as UpdateLastNotifiedFilter;
PXSelectBase<ARTran> cmd = new PXSelectJoinOrderBy<ARTran,
  InnerJoin<InventoryItem, On<ARTran.inventoryID, Equal <InventoryItem.inventoryID>>,
  InnerJoin<ItemBaseDocument, On<InventoryItemExt.usrDocumentNumber, Equal<ItemBaseDocument.baseDocumentCode>>,
  InnerJoin<Contact, On<ARTranExt.usrContactID, Equal<Contact.contactID>>>>>,
  OrderBy<Asc<ARTran.tranDate>>>(this);

cmd.WhereAnd<Where<ContactExt.usrNotificationPriority,
Equal<Current<UpdateLastNotifiedFilter.notificationPriority>>>>();

cmd.WhereAnd<Where<ARTranExt.usrDateNotified,
Less<ItemBaseDocument.revisionDateReceived>>>();

 if (filter.BaseDocumentCode != null)
{
 cmd.WhereAnd<Where<InventoryItemExt.usrDocumentNumber,
Equal<Current<UpdateLastNotifiedFilter.baseDocumentCode>>>>();
}

   return cmd.Select();
}

public PXAction<UpdateLastNotifiedFilter> Process;
[PXProcessButton]
[PXButton(CommitChanges=true)]
[PXUIField(DisplayName = "Process")]
protected virtual IEnumerable process(PXAdapter adapter)
{

  PXLongOperation.StartOperation(this, delegate()
  {
  foreach(ARTran tran in DetailsView.Select())
    {
    if (tran.Selected==true)
      {
      ARTranExt tranExt = tran.GetExtension<ARTranExt>();
      ARInvoiceEntry tranEntry = new ARInvoiceEntry();
      tranExt.UsrDateNotified = MasterView.Current.DateNotified;
      tranEntry.Transactions.Update(tran);
      tranEntry.Save.PressButton();

      }

    }

  }

        );
 return adapter.Get();
}

    [Serializable]
    public class UpdateLastNotifiedFilter : IBqlTable
    {

public static class NotificationPriority
{
    public const string None = "N";
    public const string Alert = "A";
    public const string Express = "E";
    public const string Shipment = "P";
    public const string Subscription = "S";
}

      #region NotificationPriority
      public abstract class notificationPriority : PX.Data.IBqlField
      {
      }

      [PXDBString(1, IsFixed = true)]
      [PXDefault(NotificationPriority.None)]
      [PXUIField(DisplayName = "Notification Type")]
      [PXStringList(
          new string[]
      {
      NotificationPriority.None,
      NotificationPriority.Alert,
      NotificationPriority.Express,
      NotificationPriority.Shipment,
      NotificationPriority.Subscription
      },
      new string[]
      {
      "None",
      "Alert",
      "Express",
      "Shipment",
      "Subscription"
      })]

      #endregion

      #region BaseDocumentID
      public abstract class baseDocumentCode : PX.Data.IBqlField
      {
      }

 [PXString(50)]
[PXUIField(DisplayName="Document Number")]
[PXSelector(typeof(DocCenter.ItemBaseDocument.baseDocumentCode))]

      public virtual String BaseDocumentCode
      {
        get;

        set;

      }
      #endregion

      #region DateNotified
      public abstract class dateNotified : PX.Data.IBqlField
      {
      }
      [PXDBDate()]
      [PXDefault(typeof(AccessInfo.businessDate))]
      [PXUIField(DisplayName = "Date Notified")]
      public DateTime? DateNotified { get; set; }
      #endregion

    }

  }
}

A: Your best bet would be to create a view that selects ItemBaseDocument.
PXSelect<ItemBaseDocument> ViewName;

In your for loop of your action button, you will want to create a new ItemBaseDocument object and set it equal to the corresponding ItemBaseDocument row entry. You can then update the date of this object, and when you execute your Save.PressButton() action, that should save the updates to that entry as well.
foreach(ARTran tran in DetailsView.Select())
{
if (tran.Selected==true)
  {
  ARTranExt tranExt = tran.GetExtension<ARTranExt>();
  ARInvoiceEntry tranEntry = new ARInvoiceEntry();
  tranExt.UsrDateNotified = MasterView.Current.DateNotified;
  tranEntry.Transactions.Update(tran);
  tranEntry.Save.PressButton();

  //Target Added Code
  ItemBaseDocument doc = PXSelect<ItemBaseDocument, Where<ItemBaseDocument.inventoryID,
     Equal<Required<ARTran.inventoryID>>>>.Select(tran.InventoryID);
  doc.UsrDateNotified = MasterView.Current.DateNotified;

  }

}

Disclaimer: There may be a syntax error in the added code above. If there is, please let me know and I will fix it.