Q: Spring Boot Security: Why Strict-Transport-Security header is not including preload; when preload set to true I have a spring boot application where i have added WebSecurityConfigurerAdapter.
I want to have the response header strict-transport-security: max-age=16000000; includeSubDomains; preload;
I have added the below code to the SecurityConfig as:
@Override
  protected void configure(HttpSecurity http) throws Exception {

    http.headers(headers ->
        headers.httpStrictTransportSecurity(hstsConfig -> {
          hstsConfig.preload(true);
          hstsConfig.includeSubDomains(true);
          hstsConfig.maxAgeInSeconds(31536000);
        })
            .contentSecurityPolicy(contentSecurityPolicy ->
                contentSecurityPolicy
                    .policyDirectives("script-src 'self'")
            )
            .addHeaderWriter(new StaticHeadersWriter("X-My-Custom-Header","myvalue"))
    );

    http.csrf().disable();
  }

The response header is not adding the "preload;" instead it looks like:
Strict-Transport-Security: max-age=31536000; includeSubDomains
Can someone please help me to understand what am I missing here?
Spring Security Config: v5.4.6
Thanks


Q: Limit without L'Hospital rule
The value of $$\lim_{y\rightarrow \infty}y \ln\bigg(\frac{\sin(x+1/y)}{\sin x}\bigg), x\in \bigg(0,\frac{\pi}{2}\bigg)$$

Try: Put $\displaystyle y=\frac{1}{z}$
So $$\lim_{z\rightarrow 0}\ln\bigg(\frac{\sin(x+z)}{\sin x}\bigg)\cdot \frac{1}{z}$$
$$ = \lim_{z\rightarrow 0}\frac{\ln(\sin (x+z))-\ln(\sin x)}{z}$$
Using L'Hospital rule
$$\lim_{z\rightarrow 0}\frac{\cos(x+z)}{\sin (x+z)}=\cot x$$
Could some help me? How can I solve without L'Hospital rule? Thanks

A: $\displaystyle\lim_{y\rightarrow \infty}y \ln\bigg(\frac{\sin(x+1/y)}{\sin x}\bigg)=\displaystyle\lim_{y\rightarrow \infty}y \ln\bigg(\frac{\sin(x)\cos(1/y)+\cos(x)\sin(1/y)}{\sin x}\bigg)\\=\displaystyle\lim_{y\rightarrow \infty}y \ln\bigg(\cos(1/y)+\cot(x)\sin(1/y)\bigg)\\=\displaystyle\lim_{y\rightarrow \infty}y \ln\bigg(1+\big[\cos(1/y)+\cot(x)\sin(1/y)-1\big]\bigg)$
Since $\cos(1/y)+\cot(x)\sin(1/y)-1\to0$ as $y\to\infty$, using the standard limit $\displaystyle\lim_{m\to0}\frac{\ln(1+m)}{m}=1$, we get
$=\displaystyle\lim_{y\rightarrow \infty}y\big(\cos(1/y)+\cot(x)\sin(1/y)-1\big)\\=\displaystyle\lim_{z\to0^+}\frac{\cos z-1}z+\cot(x)\cdot\lim_{z\to0^+}\frac{\sin z}z$

A: $\displaystyle\lim_{z\rightarrow 0}\frac{\ln(\sin (x+z))-\ln(\sin x)}{z}$ is precisely the derivative of $\ln(\sin x)$ for $x\in\left(0,\dfrac{\pi}{2}\right)$using limits.

A: Beside the simple solution given by Yadati Kiran, you could use Taylor series
$$\frac{\sin(x+z)}{\sin (x)}=\cot (x) \sin (z)+\cos (z)$$ Now, using the classical expansion of $\sin(z)$ and $\cos(z)$ you then have
$$\cot (x) \sin (z)+\cos (z)=1+z \cot (x)-\frac{z^2}{2}+O\left(z^3\right)$$ Continue with the logarithm to get
$$\log (\cot (x) \sin (z)+\cos (z))=z \cot (x)-\frac{1}{2} z^2 \left(\cot ^2(x)+1\right)+O\left(z^3\right)$$
$$\frac 1 z \log (\cot (x) \sin (z)+\cos (z))= \cot (x)-\frac{1}{2} z \left(\cot ^2(x)+1\right)+O\left(z^2\right)$$ which shows the limit and also how it is approached.

A: This is not a solution, more of a question.
I get to
1)$\log \left ( \cos (1/y) +\frac{\sin (1/y)}{1/y}\frac{\cot x}{y}\right )^y.$
$y \rightarrow \infty : $
Known:
2) $\lim_{y \rightarrow \infty} \log (1+(\cot x)/y)^y= \cot x$.
(Recall $\lim_{y \rightarrow \infty}(1+a/y)^y= e^a$, $a$ real.)
Is there a fairly straightforward way to get from 1)to 2) using limit manipulations ?
Could not come up with a solution.
Thanks


Q: In android, what can I use for a root element (View, ViewGroup, etc.) of my custom control which only allows a single child? Trying to write better-encapsulated custom views and composite controls.
The old way I would do this was to subclass a ViewGroup such as LinearLayout, like so...
public class RadioButton extends LinearLayout
{
    private RadioButtonView radioButtonView;
    private TextView        textView;

    public RadioButton(Context context)
    {
        super(context);
        commonInit(context, null, 0);
    }

    public RadioButton(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        commonInit(context, attrs, 0);
    }

    public RadioButton(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        commonInit(context, attrs, defStyle);
    }

    private void commonInit(Context context, AttributeSet attrs, int defStyle)
    {
        View.inflate(context, R.layout.part_radio_button, this);

        radioButtonView = (RadioButtonView) findViewById(R.id.radioButtonView);
        textView        = (TextView)        findViewById(R.id.textView);

        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RadioButton, defStyle, 0);

        String text = a.getString(R.styleable.RadioButton_text);
        setText(text != null ? text : "Unset");

        boolean isSelected = a.getBoolean(R.styleable.RadioButton_isSelected, false);
        setIsSelected(isSelected);

        a.recycle();
    }

    public String getText()
    {
        return textView.getText().toString();
    }
    public void setText(String newValue) { textView.setText(newValue); }

    public boolean getIsSelected()
    {
        return radioButtonView.getIsSelected();
    }
    public void setIsSelected(boolean newValue){ radioButtonView.setIsSelected(newValue);}
}

The layout R.layout.part_radio_button would look like this (note the Merge tag)...
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <com.citi.mobile.reusable.ui.RadioButtonView
        android:id="@+id/radioButtonView"
        style="@style/DefaultRadioButtonView" />

    <TextView
        android:id="@+id/textView"
        style="@style/DefaultRadioButtonText" />

</merge>

This worked really well ...at first!  It looked like it properly handled automatic loading the layout so the user could simply 'new-up' the control, or just reference it in a layout file themselves.
But soon it became evident that there were issues with this approach.

*

*DataBinding which requires a root <layout /> tag.

*The <merge /> tag cannot be a child of the  tag nor vice-versa.

*I couldn't define the default properties for the root control in the XML and had to do it programmatically in the constructor.

*Since I was setting them in the constructor, I also couldn't style them since the constructor was overriding their values.  I couldn't simply set the constructor-set values first, because until they were loaded from the layout, there was nothing to set.

*I also realized by subclassing LinearLayout (or any other such control) I was also exposing that LinearLayout to whomever was using this, meaning they could change the orientation, etc.
Because of the above, especially #5, I realized I should do the following instead:

*

*Don't subclass LinearLayout directly as you're exposing it to the outside world when you do.  Instead find a different root control to subclass.

*Because of the change in #1, you can now move LinearLayout back as the root of the layout portion of the layout.xml file (either directly, or under a <layout /> tag when data-binding

*Make the control you've chosen in #1 expose only the bare essentials (i.e. width, height, and whatever attributes you specifically want to expose.)
At this point, I'm starting to think what I need to do is subclass ViewGroup, or perhaps even View (as ViewGroup itself does) and enforce the one-child policy, but I'm not 100% sure, hence this question.

Note: In C#/WPF, they have a Panel class, which is similar to a ViewGroup, but they also have a ContentPresenter class which does exactly what I want... presents a single piece of content.
It's actually pretty slick in that not only can it present a UI component directly, but if you attempt to present something that isn't a UI component, like a (view)model object, it will actually apply a data-bound data template to that object based on its data type, which converts it to something for the UI.  Even if there's no defined template for that specific data type, it will call toString() on it and spit out the equivalent of a TextView.
As cool as that automatic data-presentation capability is though, I'm really only after the first part... the ability to display a single child view(group) which is somewhat protected from the outside world.


Q: Run Multiple timer simultaneously in datagrid wpf I am new to the Window Presentation Foundation (WPF). I have a Data grid showing data very well but I now want to show time in Time column dynamic like call time which is changed every second for every row of data.
here is my class
 public class UserTab
{
    public int Id { get; set; }
    public string AgentName { get; set; }
    public string Extension { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
    public string RowDetail { get; set; }
    public int ActiveParticipants { get; set; }
    public int HeldParticipants { get; set; }
    public int Duration { get; set; }
    public string CallStatus { get; set; }
    public string QueueName { get; set; }
    public string Time { get; set; }
    public string CallStatusColor { get; set; }
    public bool isRowDetail { get; set; }
    public List<UserTab> GetUsers()
    {
        List<UserTab> users = new List<UserTab>();
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:40:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42033", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#d70d0d", Time = "00:05:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Not Ready - Lunch", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "John Doe", Extension = "42034", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:30", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42035", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:06:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "AJohn Doe", Extension = "42036", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:05:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "BJohn Doe", Extension = "42037", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:55", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "CJohn Doe", Extension = "42038", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:00:40", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "DJohn Doe", Extension = "42039", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#E6A30C", Time = "00:55:00", QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "EJohn Doe", Extension = "42003", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:06:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "EJohn Doe", Extension = "42053", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:10:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "FJohn Doe", Extension = "42073", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:20", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "GJohn", Extension = "42078", Name = "Sammy", Birthday = new DateTime(1991, 9, 2) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:41", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "HJohn Doe", Extension = "42083", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:25:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "IJohn Doe", Extension = "42093", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
        users.Add(new UserTab() { CallStatusColor = "#1BDA6D", Time = "00:00:00", QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "JJohn Doe", Extension = "42013", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });

        return users;
    }
}

  public partial class Tabs : Window
  {
        InitializeComponent();
        List<UserTab> us = new List<UserTab>();
        UserTab user = new UserTab();
        us = user.GetUsers();
        dgSimple.ItemsSource = us
}

here is DataGrid
 <DataGrid Name="dgSimple" VerticalAlignment="Center" VerticalContentAlignment="Center" CellStyle="{StaticResource Body_Content_DataGrid_Centering}" Height="350" EnableRowVirtualization="False">
                                        <DataGrid.Columns>
                                            <DataGridTextColumn Header="Agent Name" Binding="{Binding AgentName}" IsReadOnly="True" />
                                            <DataGridTemplateColumn SortMemberPath="CallStatus" CanUserSort="True" Header="Status" CellTemplate="{StaticResource StatusTemplate}"/>
                                            <DataGridTextColumn Header="Time" Binding="{Binding Time}" IsReadOnly="True"/>
                                            <DataGridTextColumn Header="Extension" Binding="{Binding Extension}" IsReadOnly="True" />
                                        </DataGrid.Columns>
  </DataGrid>

A: A simple sample based on your code, it refresh the DataGrid every 1 second.

*

*In class Tabs, start a new thread by StartMockValue to mock Time value.

*In StartRefreshDataGrid, start a new thread to determine whether to update the DataGrid

*If the Time is different from DisplayTime, then set UserTab -> DisplayTime to notify property changed.

*Finally, the DataGrid updated by new data.
Tabs.xaml
<Window x:Class="TestWpfApp.Tabs"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
    <StackPanel>
         <DataGrid Name="dgSimple" VerticalAlignment="Center" VerticalContentAlignment="Center" Height="350"
                   EnableRowVirtualization="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Agent Name" Binding="{Binding AgentName}" IsReadOnly="True" />
                <DataGridTemplateColumn SortMemberPath="CallStatus" CanUserSort="True" Header="Status"/>
                <!--NOTE: bind 'DisplayTime' instead of 'Time'-->
                <DataGridTextColumn Header="Time" Binding="{Binding DisplayTimeString}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Extension" Binding="{Binding Extension}" IsReadOnly="True" />
            </DataGrid.Columns>
         </DataGrid>
    </StackPanel>
</Window>

Tabs.xaml.cs
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace TestWpfApp
{
    public partial class Tabs : Window
    {
        public Tabs()
        {
            InitializeComponent();

            this.Users = new List<UserTab>();
            UserTab user = new UserTab();
            this.Users = user.GetUsers();
            dgSimple.ItemsSource = this.Users;

            this.StartMockValue();

            this.StartRefreshDataGrid();
        }

        private List<UserTab> Users;

        private void StartMockValue()
        {
            // NOTE: this is a thread to mock the business logic, it change 'Time' value.
            Task.Run(() =>
            {
                var rando = new Random();
                while (true)
                {
                    foreach (var user in this.Users)
                    {
                        if (rando.Next(0, 3) == 1)
                        {
                            user.Time = user.Time + 1;
                        }
                    }

                    Thread.Sleep(1000);
                }
            });
        }

        public void StartRefreshDataGrid()
        {
            // NOTE: this is a thread to update data grid.
            Task.Run(() =>
            {
                while (true)
                {
                    foreach (var user in this.Users)
                    {
                        // NOTE: update if the time changed.
                        if (user.DisplayTime != user.Time)
                        {
                            user.DisplayTime = user.Time;
                        }
                    }

                    // NOTE: refresh the grid every seconds.
                    Thread.Sleep(1000);
                }
            });
        }
    }
}

UserTab.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace TestWpfApp
{
    public class UserTab : INotifyPropertyChanged
    {
        public int Id { get; set; }
        public string AgentName { get; set; }
        public string Extension { get; set; }
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
        public string RowDetail { get; set; }
        public int ActiveParticipants { get; set; }
        public int HeldParticipants { get; set; }
        public int Duration { get; set; }
        public string CallStatus { get; set; }
        public string QueueName { get; set; }

        // NOTE: this is the 'real time', some business thread will update the value.
        public int Time { get; set; }

        private int displayTime;

        // NOTE: this is the 'displayed time' in the DataGrid.
        public int DisplayTime
        {
            get => displayTime;
            set
            {
                displayTime = value;
                this.OnPropertyChange(nameof(this.DisplayTimeString));
            }
        }

        public string DisplayTimeString => $"{displayTime / 60 / 60}:{displayTime / 60 % 60}:{displayTime % 60}";

        public string CallStatusColor { get; set; }
        public bool isRowDetail { get; set; }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public List<UserTab> GetUsers()
        {
            var maxSeconds = 24 * 60 * 60;
            var random = new Random();

            List<UserTab> users = new List<UserTab>();
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42033", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#d70d0d", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Not Ready - Lunch", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "John Doe", Extension = "42034", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "John Doe", Extension = "42035", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "AJohn Doe", Extension = "42036", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "BJohn Doe", Extension = "42037", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "CJohn Doe", Extension = "42038", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "DJohn Doe", Extension = "42039", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#E6A30C", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = true, CallStatus = "Talking", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "EJohn Doe", Extension = "42003", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "EJohn Doe", Extension = "42053", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "FJohn Doe", Extension = "42073", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "GJohn", Extension = "42078", Name = "Sammy", Birthday = new DateTime(1991, 9, 2) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 1, AgentName = "HJohn Doe", Extension = "42083", Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 2, AgentName = "IJohn Doe", Extension = "42093", Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
            users.Add(new UserTab() { CallStatusColor = "#1BDA6D", DisplayTime = random.Next(0, maxSeconds), QueueName = "AMQ", isRowDetail = false, CallStatus = "Ready", Duration = 1000, HeldParticipants = 500, ActiveParticipants = 30, Id = 3, AgentName = "JJohn Doe", Extension = "42013", Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
            return users;
        }
    }
}


Q: HTTPD ReverseProxy ProxyPass directive ending in wrong Location header HTTPD is configure as following:
#redirectder edit Location "(^http[s]?://)([^/]+)" "" port 80 to secure
<VirtualHost *:80>

    ServerName mitestui02.sn.test.net
    #ServerAlias server server2.domain.com server2
    ServerAdmin support.p240@test.com
    ErrorLog /var/log/test/iiq/appserver/apache-error.log
    CustomLog /var/log/test/iiq/appserver/apache-access.log common

    Redirect /identityiq/ https://mitestui02.sn.test.net/identityiq/
    Redirect / https://mitestui02.sn.test.net/identityiq/

</VirtualHost>

#redirect to port 8080 on localhost
<VirtualHost *:443>
    ServerName mitestui02.sn.test.net
    # ServerAlias mitestui02 mitestui02.sn.test.net
    ServerAdmin support.p240@test.com
    SSLProxyEngine On
    SSLEngine On
    #allow only tls
    SSLProtocol -all +TLSv1.2
    SSLHonorCipherOrder on
    SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...

    SSLCertificateFile /etc/opt/test/iiq/appserver/secure/ssl/web-iiq.crt
    SSLCertificateKeyFile /etc/opt/test/iiq/appserver/secure/ssl/apache-iiq.key

    Redirect /identityiq/ https://mitestui02.sn.test.net/
    Redirect / https://mitestui02.sn.test.net/identityiq/

    ProxyRequests     Off
    ProxyPreserveHost On

    ProxyPass /identityiq/ http://localhost:8080/identityiq/

    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} ^OPTIONS
    RewriteRule .* - [F]

    <If "%{THE_REQUEST} =~ m#.jsf/?[?\s]#">
        Header add X-UI-Source "mitestui02"
        Header add X-UA-Compatible "IE=edge"
        Header add Referrer-Policy "strict-origin-when-cross-origin"
        Header add Feature-Policy "microphone 'none'; geolocation 'none'; usb 'none'; payment 'none'; document-domain 'none'; camera 'none'; display-capture 'none'; ambient-light-sensor 'none'"
        Header add Permissions-Policy "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()"
        Header add Strict-Transport-Security "max-age=63072000; includeSubDomains"
        Header add Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval'"
        Header add X-Content-Type-Options "nosniff"

        Header always edit Set-Cookie (.*) "$1; Secure; SameSite=Strict"
        Header onsuccess edit Set-Cookie (.*) "$1; Secure; SameSite=Strict"
    </If>
</VirtualHost>

When I connect to the front-end URL, https://mitest.sn.test.net/ I get redirected with a response code 302 and Location header pointing to https://mitestui02.sn.test.net/identityiq/ instead of  https://mitest.sn.test.net/identityiq/ .
This doesn't happen when connecting to https://mitest.sn.test.net/identity/ directly.
I have tried with different ProxyPass and ProxyPassReverse directives and also rewriting the Location header, nothing seems to help.
Thanks

A: So the issue seemed to be related to the Redirect directives.
We removed them and added the following for 443:
    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301,NE]
    # Redirect / to /identiyiq
    RedirectMatch ^/$ /identityiq

We removed them and added the following for 80:
   Redirect permanent / https://mitestui02.sn.test.net/

Now it is working as expected.


Q: using std::size in a function i have written the following code. The std::size() function ist executing properly in the main() function but not in the getMin() function. Why?
#include <iostream>

int getMin(int numbers[]) {
    int temp = numbers[0];
    int sizeA = std::size(numbers);
    for (int i = 1; i < sizeA; i++) {
        if (temp > numbers[i])
            temp = numbers[i];
    }
    return temp;
}

int main()
{
    int numbers[5] = { 5, 5, -2, 29, 6 };

    std::cout << getMin(numbers) << " with Size of "<< std::size(numbers) << std::endl;

    std::cin.get();
}


Q: Google Maps API Solid State Borders When creating a map, the state borders keep coming up as dashed lines.  Is there any way to make them solid?  I am working with the province settings in the json but I cannot seem to find a directive for solid line, perhaps in .stroke?

A: If you can't do it with Styled Maps (and I don't see how you can right now), you could use Styled Maps to hide the state boundaries:
 {
    featureType: 'administrative.province',
    elementType: 'geometry.stroke',
    stylers: [{visibility: '#off'}]
  },

Then add your own (note that you need a source of the boundaries somewhat consistent with the map tiles).
Example of using borders from a FusionTable
proof of concept fiddle
proof of concept fiddle with styled borders

code snippet:

function initMap() {
  // Styles a map in night mode.
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 40.674,
      lng: -73.945
    },
    zoom: 7,
    styles: [{
      featureType: 'administrative.province',
      elementType: 'geometry.stroke',
      stylers: [{
        visibility: '#off'
      }]
    }, ]
  });
  var layer = new google.maps.FusionTablesLayer({
    query: {
      select: 'kml_4326',
      from: '19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA'
    },
    map: map
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}


Q: jquery form plugin does not work I am a newbie programmer. I have been stuck for two days with a simple coding problem.I try to use jquery form plugin for submitting a form to another page and get feedback from that page.The problem is the plugin is not working, the form is submitted normally without feedback. Here is the code:

<form  action='ajaxcall.php' id='upload_pic' enctype='multipart/form-data'  method='post'>
<input type='file' id='pic' name='picture'>
<input type='submit' id='sub'>
</form>

var options=
{
  target:'#preview',
  url:'ajaxcall.php'
};

$(document).ready(function(){
    $("#sub").click(function(){
        $('#preview').html("");
        $('#upload_pic').ajaxForm(options).submit();
    });
});

Here is my ajaxcall.php page code
if(!empty($_FILES['picture']['size']))
{
 echo "";
}

Expectation was the echoed image would feedback but the page is simply redirected to ajaxcall.php page.I understand that ajaxForm() function is not working. The same question I am asking two times in SO, but still no satisfactory solution. But why? Please help.Thanks in advance.

A: Use adeneo's answer, because I also do not see why you would use this plugin, but here could be a few reasons why what you have isn't working:
In the examples from the plugin's website, you should

*

*bind to the form, not the button

*use the beforeSubmit option

*Remove the submit() from the end of your call, not sure why it is
there

*Watch console for any errors

var options=
{
  target:'#preview',
  url:'ajaxcall.php',
  beforeSubmit:  showLoading,
  error: function(e){
      alert("Error: " + e);
  }
};

function showLoading(){
    $('#preview').html("");
}

$(document).ready(function(){
    $("#upload_pic").ajaxForm(options);
});


Q: Meson scattering amplitude in the linear sigma model I am trying to calculate scattering amplitudes with linear sigma model Lagrangian, given as
$$\mathcal L= \frac{1}{2}(\partial_{\mu}\sigma)^2+\frac{1}{2}(\partial_{\mu}\vec{\pi})^2-\mathcal U(\sigma,\vec{\pi})\tag{112}$$
Where,
$$\mathcal U(\sigma,\vec{\pi})=\frac{\mathcal{\lambda}}{4}(\sigma^2+\vec \pi^2 -\mathcal f^2)^2-{H\sigma}.\tag{113}$$
the scattering amplitudes, for $\pi\pi\rightarrow\pi\pi$ and $\sigma\sigma\rightarrow\sigma\sigma$ are
$$\mathcal M_{{\pi}^a{\pi}^b;{\pi}^c{\pi}^d}=-2\lambda\Bigl(\frac{s-m_\pi^2}{s-m_\sigma^2}\delta_{ab}\delta_{cd}+\frac{t-m_\pi^2}{t-m_\sigma^2}\delta_{ac}\delta_{bd}+\frac{u-m_\pi^2}{u-m_\sigma^2}\delta_{ad}\delta_{bc}\Bigr)\tag{118}$$
$$\mathcal M_{{\sigma}{\sigma};{\sigma}{\sigma}}=-6\lambda-36\lambda^2\mathcal f_\pi^2\Bigl(\frac{1}{s-m_\sigma^2}+\frac{1}{t-m_\sigma^2}+\frac{1}{u-m_\sigma^2}\Bigr)\tag{121}$$
Where $s$,$t$ and $u$ are Mandelstam variables and $$\mathcal f_\pi^2=\frac{m_\sigma^2-m_\pi^2}{m_\sigma^2-3m_\pi^2}\mathcal f^2.\tag{117}$$ I do not know how to start, to get last two expressions (118) & (121), namely, $\mathcal M_{{\pi}^a{\pi}^b;{\pi}^c{\pi}^d}$ and $\mathcal M_{{\sigma}{\sigma};{\sigma}{\sigma}}$.
References:

*

*http://arxiv.org/abs/arXiv:1006.0257


Q: FileDialog does not work in some excel versions VBA I have a code that works in the excel version 2010 normally, but in the 2013 version does not. Take a look.
Sub select_strategy()
'Subroutine that lets the user select a strategy table
'
    'Declare local variables
    Dim strategyFileDialog As Office.FileDialog
    'Declare local variables
    Dim intStrategySelection As Integer

    'Initialize global variables
    Call initialize_global_variables

    ' Allows the user to select the strategy table to use
    Set strategyFileDialog = Application.FileDialog(msoFileDialogFilePicker)

    With strategyFileDialog
        .Title = "Select Strategy Table"
        .InitialFileName = ActiveWorkbook.Path
        .AllowMultiSelect = False
    End With

    intStrategySelection = strategyFileDialog.Show  'updates cell only if a file is selected
     If intStrategySelection <> 0 Then
        wsMain.Cells(2, 3) = strategyFileDialog.SelectedItems(1)
     Else
        wsMain.Cells(2, 3) = ""
     End If

End Sub

The error for the 2013 version is Compile error: Cant find project or library.
Any ideas how to solve it?

A: To use late binding use the FileDialog() function from the Excel.Application Object. Excel.Application.FileDialog() Is a function that returns a FileDialog Object for an open Workbook. If you declare a variable as a specific object such as Office.FileDialog it will create the object of the version that is used in the VBA reference the code was written with and at runtime on a different pc will ignore other version references and look for the specific version that the variable was declared with.
You can use the reference to the active workbook but is not explicitly needed in Excel
Dim strategyFileDialog As Object
Set strategyFileDialog = ActiveWorkbook.Application.FileDialog(3)

'Filedialog Enumerations:
'msoFileDialogFilePicker = 3 File picker dialog box.
'msoFileDialogFolderPicker = 4 Folder picker dialog box.
'msoFileDialogOpen = 1 Open dialog box.
'msoFileDialogSaveAs = 2 Save As dialog box


Q: GoCD - Task Plugins not adding tasks I have setup a GoCD server and agent (on a Windows machine if that matters). I am using it to build a .NET application. I have installed a few Task plugins (Powershell, Xunit-converter) and when I restart the server I see those as loaded and installed without issue in the plugin admin screen.
However, when I go to create or edit a job, I do not see these new tasks in the "Add Task" dropdown.  I can get around the powershell one by using a Custom command, but I need to be able to convert my MsTest ouptut to Xunit so that it can display the results in the Test Results Tab.


Q: Gutenberg getMedia() in post query doesn't return all featured images In my edit() function for a custom block I'm using the following to list my post titles and featured images:
import { useSelect } from '@wordpress/data';

edit( { attributes, setAttributes } ) {

// Request data
const data = useSelect((select) => {
  return select('core').getEntityRecords('postType', 'post');
});

return (

    {data &&
      data.map( ( post, i ) => {
        const featuredImage = post.featured_media ? wp.data.select('core').getMedia( post.featured_media ) : null;

        return (

            { post.title.rendered }
            { featuredImage &&

            }

        )
      })
     }

);

},

....

In the editor, this shows all my post titles but shows only a few featured images. When I click the block in the editor, all the other images appear as well. Why is this happening? I'm not sure what I'm doing wrong. I don't get errors.


Q: Unable to get the value in the shell variable     #!/bin/ksh
    for i in 1 2 3 4 5
    do
        echo "hello world"> $i
    done
    v = echo $?
    if [ $v -eq 0 ]; then
     echo " Completed"
    else
     echo "Not completed"
    fi

Unable to get the value in v = echo s?, due to this if condition always fails

A: Wrong logic use just this (direct assignation):
v=$?

A: Instead of v = echo $?
Either write
v=`echo $?`

OR
v=$?


Q: Xcode 9.2 - Can't see "iOS Simulator" within run destination I'm trying to run my application with a Xcode simulator but I can't select any simulator since my only options are the one showed in this screenshot
As per apple guide, I should see the section "iOS Simulator" below "Build Only Device", but within my Xcode that section is missing.
What I've already tried to solve the issue:

*

*Set iOS Deployment Target under Project > Info > Deployment Target and restart Xcode.

*Check if there are simulators installed within Xcode>Preferences>Components. There are Simulator 11.0 and 11.1

*Check if there are simulator within Window > Device and Simulator > Simulators. There are around 30 simulators.

*Restart Xcode

*Reinstall Xcode

I am using Xcode 9.2 and macOS version 10.12.6.
Does anyone knows what could be the problem?


Q: Start and Stop indicatorView and put it in centre tableView in swift I am using a spinner in bottom of tableView to show the spinner when data is reloading.
var sneakers: [sneakerModel] = []

I stored all my data in sneakers and returning the count on numberOfRowsInSection method.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.sneakers.count
}

And now I am using willDisplay method to show the spinner in bottom.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1

if indexPath.row == self.sneakers.count - 1 && !didPageEnd {
    pageNo += 1
    getSneakerSearch()
 }

    if (indexPath.row == self.sneakers.count) {
       self.tableView.tableFooterView?.isHidden = true
    } else {

    if indexPath.section ==  lastSectionIndex && indexPath.row == lastRowIndex {
     let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
     spinner.activityIndicatorViewStyle = .whiteLarge
     spinner.color = .red
     spinner.startAnimating()
     spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(5), width: tableView.bounds.width, height: CGFloat(44))

     self.tableView.tableFooterView = spinner
     self.tableView.tableFooterView?.isHidden = false
        }

    }

}

But it is not working. How can I stop spinner when no more data is loading. Please help?
Getting the data from api.
func getSneakerSearch() {

   let param: [String:Any] = [ "search_term" :  searchText ?? "","page": pageNo, "token": commonClass.sharedInstance.userToken ?? ""]

    if self.pageNo == 0{
        commonClass.sharedInstance.startLoading()
    }
    Alamofire.request(Constants.API.url("search"), method: .post, parameters: param, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
        (response:DataResponse<Any>) in

        commonClass.sharedInstance.stopLoading()

        guard let json = response.result.value as? [String:Any] else {return}
        printD(json)

        guard let status = json["status"] as? Int else {return}
        printD(status)

        if status == 1 {

            guard let data = json["data"] as? [[String:Any]] else { return}
            printD(data)
            if self.pageNo == 0 {
                self.sneakers.removeAll()
            }
            for item in data {
                guard let description =  item["description"] as? String else { return}
                printD(description)
                self.sneakers.append(sneakerModel(response: item))
            }
            self.didPageEnd = data.count < limitPerPage

        }
        DispatchQueue.main.async {
            self.reloadData()
        }
    }
}

A: Create loadingview in viewdidload
override func viewDidLoad() {
    super.viewDidLoad()
    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    spinner.activityIndicatorViewStyle = .whiteLarge
    spinner.color = .red
    spinner.startAnimating()
    spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(5), width: tableView.bounds.width, height: CGFloat(44))

    self.tableView.tableFooterView = spinner
    self.tableView.tableFooterView?.isHidden = true
}

and update willDisplay cell
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    let lastSectionIndex = tableView.numberOfSections - 1
    let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1

    if indexPath.row == self.sneakers.count - 1 && !didPageEnd {
        pageNo += 1
        getSneakerSearch()
    }
}

Update getSnackerSearch func:
...
    if self.pageNo == 0{
        commonClass.sharedInstance.startLoading()
    }else{
        self.tableView.tableFooterView?.isHidden = false
    }
    Alamofire.request(Constants.API.url("search"), method: .post, parameters: param, encoding: URLEncoding.httpBody, headers: nil).responseJSON {
        (response:DataResponse<Any>) in

        if self.pageNo == 0{
            commonClass.sharedInstance.stopLoading()
        }else{
            self.tableView.tableFooterView?.isHidden = true
        }

    }
   ...

A: For center of you spinner to tableview you can follow these steps to do it. You don't need to provide height and width for spinner.
    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    spinner.activityIndicatorViewStyle = .whiteLarge
    spinner.color = .red
    spinner.startAnimating()

    let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
        (self.navigationController?.navigationBar.frame.height ?? 0.0)

    spinner.center=CGPointMake(self.tableView.center.x, self.tableView.center.y- topBarHeight);


Q: Incoming IP addresses for webhooks? What IP Address range do your webhooks come from? We need to white list them to receive your Copyleaks results to our web server.
Thank You,

A: As of now, Copyleaks API not arriving from fixed list of IP addresses. But, you have other alternatives to securing your endpoints. The options described here:
https://api.copyleaks.com/documentation/v3/webhooks/security
Another option you have to secure your endpoints is to add "Authentication" header to the webhook request with a private secret in its value. With Copyleaks API you have the ability to specify the headers that will arrive to your endpoints.


Q: PHP - Refactoring / improving Ifs I have the following data structure;
Array ( [0] => Array ([suit] => c [rank] => A )
        [1] => Array ( [suit] => d [rank] => A ) )

I want to test if these cards are certain values and display an appropriate message;
if (
    (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "A"))
 || (($hand[0]['rank'] == "K") && ($hand[1]['rank'] == "K"))
 || (($hand[0]['rank'] == "Q") && ($hand[1]['rank'] == "Q"))
 || (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "K"))
 || (($hand[0]['rank'] == "K") && ($hand[1]['rank'] == "A"))
   ) {
    echo "Action: Raise pre-flop. Re-raise if already raised.
\n";
}

 if (
       (($hand[0]['rank'] == "7") && ($hand[1]['rank'] == "7"))
    || (($hand[0]['rank'] == "A") && ($hand[1]['rank'] == "J") && ($hand[0]['suit'] == $hand[1]['suit']))
    || (($hand[0]['rank'] == "J") && ($hand[1]['rank'] == "Q") && ($hand[0]['suit'] == $hand[1]['suit']))
    || (($hand[0]['rank'] == "10") && ($hand[1]['rank'] == "J") && ($hand[0]['suit'] == $hand[1]['suit']))
       ) {
        echo "Action: Worth a call pre-flop (provided no-one has raised).
\n";
    }

I have simplified the IFs by removing some of the conditions.
Can anyone suggest a better way of doing this?

A: Maybe try to use in_array() method
php.net in_array()

A: Try to use references like this:
$rank0 =& $hand[0]['rank'];
$rank1 =& $hand[1]['rank'];

if (
($rank0 == "A" && $rank1 == "A")
|| (...)

Just, as the first step to code minimization


Q: UserDefine Runtime Attributes doesn't work in Xcode8.0 It seems like xcode8.0 does not set the value of user runtime attributes when set from storyboard.What am trying to do is simple,set the label inside a cell as corneRadius of 10 which has width/height of 20. When i try to debug the views i got the following output which has weird width height(1000/1000..?)

_UILabelLayer:0x600000283750; position = CGPoint (500 500); bounds = CGRect (0 0; 1000 1000); delegate = >; opaque = YES; allowsGroupOpacity = YES; cornerRadius = 10; contentsMultiplyColor = (null); rasterizationScale = 2; contentsScale = 2>

A: i think it's helpful for you.

and also check the clipToBounds

Checking "Clip Subviews" is equal to the code addMessageLabel.clipsToBounds = YES;

A: You can use this code and method on your controller
 override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            yourLabel.clipsToBounds = true
            yourLabel.layoutIfNeeded()
            print("Frame ------> ",yourLabel.frame)
     }


Q: rails "where" statement: How do i ignore blank params I am pretty new to Rails and I have a feeling I'm approaching this from the wrong angle but here it goes... I have a list page that displays vehicles and i am trying to add filter functionality where the user can filter the results by vehicle_size, manufacturer and/or payment_options.
Using three select form fields the user can set the values of :vehicle_size, :manufacturer and/or :payment_options parameters and submit these values to the controller where i'm using a
@vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, :vehicle_size => params[:vehicle_size] )

kind of query. this works fine for individual params (the above returns results for the correct vehicle size) but I want to be able to pass in all 3 params without getting no results if one of the parameters is left blank..
Is there a way of doing this without going through the process of writing if statements that define different where statements depending on what params are set? This could become very tedious if I add more filter options.. perhaps some sort of inline if has_key solution to the effect of:
@vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, if(params.has_key?(:vehicle_size):vehicle_size => params[:vehicle_size], end if(params.has_key?(:manufacturer):manufacturer => params[:manufacturer] end )

A: You can do:
@vehicles = Vehicle.order('vehicles.id ASC')
if params[:vehicle_size].present?
  @vehicles = @vehicles.where(vehicle_size: params[:vehicle_size])
end

Or, you can create scope in your model:
scope :vehicle_size, ->(vehicle_size) { where(vehicle_size: vehicle_size) if vehicle_size.present? }

Or, according to this answer, you can create class method:
def self.vehicle_size(vehicle_size)
  if vehicle_size.present?
    where(vehicle_size: vehicle_size)
  else
    scoped # `all` if you use Rails 4
  end
end

You call both scope and class method in your controller with, for example:
@vehicles = Vehicle.order('vehicles.id ASC').vehicle_size(params[:vehicle_size])

You can do same thing with remaining parameters respectively.

A: The has_scope gem applies scope methods to your search queries, and by default it ignores when parameters are empty, it might be worth checking


Q: XText - get content (compiled value) of XExpression I have a certain part of my XText grammer that defines a block for classes that shall print all its expressions. The XText grammar part for this looks as follows:
Print:
    {Print}
    'print' '{'
        print += PrintLine*
    '}';
PrintLine:
    obj += XExpression;

Now I use the following inferrer code to create a print() method:
Print: {
    members += feature.toMethod('print', typeRef(void)) [
    body = '''
        «FOR printline : feature.print»
            System.out.println(«printline.obj»);
        «ENDFOR»
        '''
    ]
}

Ok, I go ahead and test it with the following code in a class:
print {
    "hallo"
    4
    6 + 7
}

And the result is the following:
public void print() {
   System.out.println([org.eclipse.xtext.xbase.impl.XStringLiteralImpl@20196ba8 (value: hallo)]);
   System.out.println([org.eclipse.xtext.xbase.impl.XNumberLiteralImpl@7d0b0f7d (value: 4)]);
   System.out.println([<XNumberLiteralImpl> + <XNumberLiteralImpl>]);}

Of course, I was hoping for:
public void print() {
   System.out.println("hallo");
   System.out.println(4);
   System.out.println(6+7);
}

I understand that I might have to call the compiler somehow in the inferrer for «printline.obj», but I am really not sure how.

A: i think you are doing this on a wrong basis. this sounds to me like an extension of xbase, not only a simple use.
import "http://www.eclipse.org/xtext/xbase/Xbase" as xbase

Print:
    {Print}
    'print'
        print=XPrintBlock
    ;

XPrintBlock returns xbase::XBlockExpression:
    {xbase::XBlockExpression}'{'
        expressions+=XPrintLine*
    '}'
;

XPrintLine returns xbase::XExpression:
    {PrintLine} obj=XExpression

;

Type Computer
class MyDslTypeComputer extends XbaseTypeComputer {

     def dispatch computeTypes(XPrintLine literal, ITypeComputationState state) {
        state.withNonVoidExpectation.computeTypes(literal.obj)
        state.acceptActualType(getPrimitiveVoid(state))
    }

}

Compiler
class MyDslXbaseCompiler extends XbaseCompiler {

    override protected doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) {
        if (obj instanceof XPrintLine) {
            appendable.trace(obj)
            appendable.append("System.out.println(")
            internalToJavaExpression(obj.obj,appendable);
            appendable.append(");")
            appendable.newLine
            return
        }

        super.doInternalToJavaStatement(obj, appendable, isReferenced)
    }

}

XExpressionHelper
class MyDslXExpressionHelper extends XExpressionHelper {

    override hasSideEffects(XExpression expr) {
        if (expr instanceof XPrintLine || expr.eContainer instanceof XPrintLine) {
            return true
        }
        super.hasSideEffects(expr)
    }

}

JvmModelInferrer
def dispatch void infer(Print print, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
    acceptor.accept(
        print.toClass("a.b.C") [
            members+=print.toMethod("demo", Void.TYPE.typeRef) [
                body = print.print
            ]
        ]

    )
}

Bindings
class MyDslRuntimeModule extends AbstractMyDslRuntimeModule {

    def Class<? extends ITypeComputer> bindITypeComputer() {
        MyDslTypeComputer
    }

    def Class<? extends XbaseCompiler> bindXbaseCompiler() {
        MyDslXbaseCompiler
    }

    def Class<? extends XExpressionHelper> bindXExpressionHelper() {
        MyDslXExpressionHelper
    }
}


Q: No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode Could not determine the dependencies of task :app:compileDebugJavaWithJavac.
> Could not resolve all task dependencies for configuration ':app:debugAnnotationProcessorClasspath'.
   > Could not resolve androidx.databinding:databinding-compiler:3.4.2.
     Required by:
         project :app
      > No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.
      > No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.
      > No cached version of androidx.databinding:databinding-compiler:3.4.2 available for offline mode.

A: Uncheck "Offline work" in Android Studio:

File -> Settings -> Gradle -> Global Gradle Settings

or in OSX:

Preferences -> Gradle -> Global Gradle Setting


Q: UNMET PEER DEPENDENCY ISSUE I have been trying to install the ngx bootstrap from [https://ng-bootstrap.github.io/#/getting-started]
by entering the command: npm install ngx-bootstrap --save
but the result is this:
+-- UNMET PEER DEPENDENCY @angular/common@2.4.10
+-- UNMET PEER DEPENDENCY @angular/compiler@2.4.10
+-- UNMET PEER DEPENDENCY @angular/core@2.4.10
+-- UNMET PEER DEPENDENCY @angular/forms@2.4.10
+-- UNMET PEER DEPENDENCY jquery@1.9.1 - 3
+-- ngx-bootstrap@2.0.0-beta.9
+-- UNMET PEER DEPENDENCY popper.js@^1.12.3
`-- UNMET PEER DEPENDENCY typescript@2.0.10

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN @ng-bootstrap/ng-bootstrap@1.0.0-beta.5 requires a peer of @angular/core@^4.0.3 but none was installed.
npm WARN @ng-bootstrap/ng-bootstrap@1.0.0-beta.5 requires a peer of @angular/common@^4.0.3 but none was installed.
npm WARN @ng-bootstrap/ng-bootstrap@1.0.0-beta.5 requires a peer of @angular/forms@^4.0.3 but none was installed.
npm WARN bootstrap@4.0.0-beta.2 requires a peer of jquery@1.9.1 - 3 but none was installed.
npm WARN bootstrap@4.0.0-beta.2 requires a peer of popper.js@^1.12.3 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/common@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/compiler@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/core@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of @angular/forms@>=4.3.0 || >5.0.0 but none was installed.
npm WARN ngx-bootstrap@2.0.0-beta.9 requires a peer of typescript@>=2.3.0 but none was installed.

I do not understand what's happening.
I am fairly new to Angular 2 and the relevant technologies. Would appreciate your help ! Thank you.

A: hello you need to install your perDependencies, if you install a package that depends on specific versions of other packages, If it didn't find the correct  version of package then "Peer dependency" is unmet, try this:
npm install -g npm-install-peers

npm-install-peers

this will install peerDependencies


Q: Port forwarding from Router 1 to router 2 not working? I have 2 routers.
router 1 IP : 192.168.4.1
router 2 IP : 192.168.5.1
I can easily forward port 8080 from router 1 to router 2 which routes it to a Tomcat server (port 8080 also).
I accesss this server via:

sampleurl.com:8080

When I change to Tomcat to port 5000, and reconfigure the routers, I can access the Tomcat instance using (inside my LAN)

TOMCAT_SERVER_IP:5000

But, accessing my Tomcat from outside doesn't seem to work at all! I just changed the port and it doesn't work anymore:

sampleurl.com:5000

I installed Wireshark on the server and using the URL above does trigger anything (so the server is not being hit). I've tripled checked port forwarding...
Is there a magic trick or something special to do to use any port other then 8080?
Thank you!

A: For some reason, this DD-WRT is not forwarding the ports correctly. I found that this obscure bug can occur but since I do not want to fiddle anymore with my router I just forwarded all ports to the same host. Not very clean but I'm just making tests.


Q: Wraping text within a table's td I am working on trying to clean up a customers evaluation software. In this example, the text doesn't wrap within the box. Adding a fixed size to the table doesn't help, as the information called from the SQL database just places it on top with no warping.

                ![enter image description here][1]

' . base64_decode($eval['note']) . '

What steps should I look at doing or code should I add to fix this formatting error? Attached is a screen shot of the UI.
Thank you,
Paul

A: You are inserting your data inside a
 block, effectively telling the browser not to wrap the text. I assume you do this so that literal newlines in the 'note' data are indeed printed.
To alter wrapping space-characters and newline functionality of an element, you can use the CSS white-space property. So, to get what you want (both wrapping AND literal newlines), you can set white-space to either pre-line or pre-wrap, depending on your need. Eg. change the
 to
...
' . base64_decode($eval['note']) . '
...

See the reference for more details
Good luck,
bob


Q: Presenting 3-manifolds by planar graphs From a planar graph $\Gamma$, equipped with an integer-valued weight function $d:E(\Gamma) \sqcup V(\Gamma) \to \mathbb{Z}$, one can build a $3$-manifold $M_{\Gamma}$ as follows.  For each vertex $v$, draw a small planar unknot centered at $v$.  For each edge $e$ connecting vertices $v$ and $w$, add a series of $d(e)$ clasps between the corresponding unknots (with positive weights represented by right-handed clasps and negative weights represented by left-handed clasps).  The result is a link with unknotted components - call it $L_{\Gamma}$.  To get the $3$-manifold $M_{\Gamma}$, perform Dehn surgery on each component of $L_{\Gamma}$, with framings
$$ f(v) = d(v) + \sum_{e \ni v} d(e). $$
In fact, every 3-manifold $M$ is diffeomorphic to a manifold of the form $M_{\Gamma}$.  This can be proved using ideas from a paper of Matveev and Polyak (A Geometrical Presentation of the Surface Mapping Class Group and Surgery), as follows.  Choose a Heegaard splitting for $M$, and write the gluing map as a composition of Lickorish twists.  Then use the graphical calculus in sections 3 and 4 of that paper (omitting the twists denoted $\epsilon_i$) to produce a tangle whose plat closure is a framed link of the form $L_{\Gamma}$, such that the result of surgery on this link is $M$.  This argument is given by Polyak in slides available on his website.[1][2]
There is another proof as well, which involves taking an arbitrary link surgery presentation and repeatedly simplifying it.  There is a natural way to measure the complexity of a link diagram, such that links of minimal complexity are of the form $L_{\Gamma}$.  It is always possible to reduce this complexity by adding cancelling unknotted components and doing handleslides.
One can take the idea further and show that there is a finite set of local moves which suffice to relate any two weighted planar graphs representing the same 3-manifold.  Indeed, this follows abstractly from the fact that the mapping class group is finitely presented.  However, the moves produced by Wajnryb's presentation (for example) are rather complicated and nasty-looking.  It is therefore natural to ask if one can find a more appealing set of moves.
One must certainly include the following moves (please excuse the lack of pictures):

*

*Self-loops and edges with weight $0$ can be eliminated.

*Any two parallel edges can be combined, at the expense of adding their weights.

*Suppose that $v$ is a vertex incident to exactly one edge $e$, with $d(e) = \pm f(v) = \pm 1$. Then $v$ and $e$ can be deleted, at the expensing of changing the framing on the other endpoint of $e$, call it $w$.  If $f(v) = 0$, then $w$ (and all of its incident edges) can be removed from the graph .

*Suppose that $v$ is a vertex incident to exactly two edges $e_1$ and $e_2$, with $d(e_1) = d(e_2) = - f(v) = \pm 1$, then the vertex $v$ can be replaced with a single edge joining the opposite endpoints of $e_1$ and $e_2$, call them $w_1$ and $w_2$. If $d(e_1) = - d(e_2)$ and $f(v) = 0$, then $e_1$ and $e_2$ can be contracted, with the resulting vertex having weight $d(w_1) + d(w_2)$.

*Suppose that $v$ is a vertex incident to exactly three edges, and suppose that $d(e_1) = d(e_2) = -d(e_3) = f(v)$.  Then $v$, together with all $e_i$, can be eliminated at the expense of adding a triangle connecting the opposite endpoints of the edges $e_i$.

Let's call any of the above moves a "blowdown", and let's call their inverses "blowups".  All of them can be easily deduced using Kirby calculus, or from relations in the mapping class group.

Question 1: Are blowups and blowdowns sufficient to relate
  any two planar graph presentations of a given $3$-manifold?

If the answer to this question is no, then there are additional non-local moves to consider:

*

*If two edges $e_1$ and $e_2$ connect the same pair of vertices (but are not necessarily parallel), then they can be combined, at the expense of adding their weights.

*If there is a vertex $v$ which divides $\Gamma$ into multiple components, those components can be "permuted around $v$".  Any of these components which is connected to $v$ by a single edge $e$ with weight $\pm 1$ can also be "flipped over", at the expense of changing the weight on $e$.

*If there are two vertices $v$ and $w$ which separate the graph into multiple components, then any component which is joined to both $v$ and $w$ by a single pair of edges with opposite weights in $\{\pm 1\}$ can be "flipped over", at the expense of changing the weights on the edges.

Let's call any of the above moves a ``mutation''.

Question 2: Are blowups, blowdowns, and mutations sufficient to relate any two
  planar graph presentations of a given $3$-manifold?

If the answer to this question is also no, then it would be good to have a nice answer to the following (admittedly vague) question:

Question 3: What is the "simplest possible" set of moves which are sufficient to relate any two planar graph presentations of a given $3$-manifold?

One argument in favor of a positive answer to Questions 1 or 2, or at least a very nice answer to Question 3, is that Kirby calculus itself admits a finite set of simple local moves.  One approach might be to find a canonical way of simplifying an arbitrary link surgery presentation to a planar graph presentation, and trace the effects of a Kirby move through the simplification process to see which graph moves are required to implement it.
There is also a relationship with double branched covers, which might be relevant.  If all vertex weights $d(v) = 0$, then $M_{\Gamma}$ can be identified (after doing surgery on an essential 2-sphere) with the double cover branched over a link $Z \subset S^3$, whose "checkerboard graph" is $\Gamma$.  In this picture, Reidemeister moves on $Z$ can be realized by blowdowns and blowups, and Conway mutations can be realized by graph mutations.  Note that these moves do not suffice to relate links with diffeomorphic double branched covers - this might be viewed as evidence in favor of a negative answer to Questions 1 and 2.

A: I'm pretty sure that the answers to Question 1 and part of Question 2 are no, and this does come from looking at double branched covers.
There are examples due to Watson (1) of pairs of knots with diffeomorphic double branched covers but different Khovanov homology. So to show that these moves do not suffice, we just need to write down a chain complex for each of these graphs $\Gamma$ that computes Khovanov homology of an appropriate link when all of the $d(v)$ are $0$, and is invariant under these moves.
To show that (odd, or $\mathbb{F}_2$ coefficient) Khovanov homology is mutation invariant, Bloom constructs a complex computing Khovanov homology from some basically linear-algebraic data, and a slight adaptation of this gives the needed chain complex here.
More specifically, for a graph $\Gamma$ as in the question, let $\hat{\Gamma}$ be a graph obtained by adding a vertex $v_*$ to $\Gamma$, adding an edge labelled $d(v)$ from $v$ to $v_*$ for each vertex $v \in \Gamma$, replacing every edge $e$ with $d(e) > 0$ with $d(e)$ edges labelled $1$, and replacing every edge with $d(e) < 0$ with $-d(e)$ edges labelled $-1$.
Then let $E$ and $V$ be the $\mathbb{F}_2$ vector spaces spanned by the edges and vertices of $\hat{\Gamma}$, and let $I: E \to V$ be the map sending each edge to the sum of its endpoints. For each subset $S$ of the edges of $\hat{\Gamma}$, let $E_S \subset E$ be spanned by the edges in $S$, and let $I_S$ be the restriction of $I$ to $E_S$. Finally, let $C_0(S) = \operatorname{coker} I_S \oplus (\ker I_S)^*$, and let $C(S) = \Lambda^*C_0(s)$. (Apologies for all the notation)
Using the snake lemma, one can show that if $S$ and $S'$ differ only in a single edge $e$, then either there is a canonical element $\phi_e \in C_0(S)$ with $C_0(S') \cong C_0(S)/\langle \phi_e \rangle$, or the reverse: a canonical element $\phi_e \in C_0(S')$ with $C_0(S) \cong C_0(S')/\langle \phi_e \rangle$.
With this data, we can build a complex just like the odd Khovanov complex: call an assignment of $\pm 1$ to each edge of $\hat{\Gamma}$ a state, and for a state $s$ let $S(s)$ be the set of edges where the number assigned to the set by the state agrees with the label of the state. If $s'$ differs from $s$ by changing the $-1$ on $e$ to a $+1$, let $$\psi_{s,s'}: C(S(s)) \to C(S(s'))$$ be the map induced by the projection $C_0(S(s)) \to C_0(S(s'))$ if $C_0(S(s')) \cong C_0(S(s)) / \langle \phi_e \rangle$, and if $C_0(S(s)) \cong C_0(S(s')) / \langle \phi_e \rangle$ let
$$ \psi_{s,s'}(x) = \phi_e \wedge x. $$
The chain complex then has the direct sum of all $C(S(s))$ where $s$ has $k$ ones in degree $k$, and the differential is the sum of all $\psi_{s,s'}$.
It's not hard to see that this complex computes the direct sum of two copies of the Khovanov homology of $L$ if $\Gamma$ was originally the checkerboard graph of $L$ (the two copies come from the extra vertex added). Any of the blowup or blowdown moves change $\hat{\Gamma}$ locally in exactly the way that a Redemeister move changes the checkerboard graph of a link, so the proofs that odd Khovanov homology is a knot invariant should work just as well for showing that this is invariant under blowups (this is the part of this argument that I'm least sure of). Similarly, the types of mutations that don't involve flipping an edge over and changing it's sign don't change $\hat{\Gamma}$ at all. Flipping an edge over seems more complicated to me, but I wouldn't be surprised if this still remains invariant.
With this set-up, I'd be really interested in other local moves on these graphs in order to better understand how Khovanov homology fails to be an invariant of the double branched cover.


Q: Android JSON Get via HttpURLConnection error 405 so I'm trying to do a GET Request to my web service, and since I saw that the HttpGet class is being deprecated, I try to use the HttpURLConnection class instead, and I used it successfully with a 'POST' method... however when I try to do a simple 'GET' request - I get a 405 error (bad method).
I tested the link in DHC, and the link is fine.
Here's my method:
    public JSONObject getClientByDeviceId (String link) {
    try {
        URL url = new URL(link);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    //            conn.setRequestMethod("GET");
    //            conn.setDoOutput(true);
    //            conn.setDoInput(true);
    //            conn.setUseCaches(false);
    //            conn.setAllowUserInteraction(false);
    //            conn.setRequestProperty("Content-Type", "application/json");

        OutputStream outputStream = conn.getOutputStream();
        outputStream.close();

        if (conn.getResponseCode() != 200) {
            Log.e("conn", "Error code: " + conn.getResponseCode());
            BufferedReader br = new BufferedReader(new  InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            conn.disconnect();

            JSONObject returnedObject = new JSONObject(sb.toString());

            if (returnedObject != null) {
                Log.e("conn", "If 400, this is the object gained: " +     returnedObject.getString("Message"));
            } else {
                Log.e("conn", "didn't get any JSON object");
            }

            conn.disconnect();
            return returnedObject;

        }
        else {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            Log.e("conn", "GREAT SUCCESS !!: " + conn.getResponseCode());
            StringBuilder sb = new StringBuilder();

            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            conn.disconnect();

            JSONObject returnedObject = new JSONObject(sb.toString());

            return returnedObject;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

Normally I would say that this problem is caused by trying to do a 'GET' request in a 'POST' URL. But without the two HttpGet and HttpPost classes I don't really know where to turn, all the properties that are commented out are like that because I tried them in the POST request and now I deleted one by one to try to get the method to work.
Any ideas ? or reference to an updated guide on how to properly use that HttpURLConnection class, since I couldn't find one.
Thanks in advance !

A: Solved it, apparently this code needed to be removed:
OutputStream outputStream = conn.getOutputStream();
    outputStream.close();

I guess it was because I gave a GET URL and put that outputStream in my code and that caused the issues.
I still however don't understand why I got the "405: method GET not allowed" whereas I think I should have gotten the opposite: "POST" not allowed...
Anyway that is my solution, thanks a lot for your help guys !

A: HTTP 405 is caused by bad method call (Method not Allowed). That means you called GET method on POST request or vice-versa. You should add handling for you GET method on your Web-Service to get it working.

A: For anyone still reaching here from a search engine, my solution was similar -
I removed the line "conn.setDoOutput(true);" (or set it to false)


Q: Angular 2 : How to keep two methods from repeating How can I implement my if/else statement only once so that I don't repeat this fragment of code in my header component as shown below:
export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuShown: false;

constructor(private layoutService: LayoutService, private renderer: Renderer) { }

menuToggle(event: any) {
    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}

onMenuSelect(event: any) {
    this.isMenuShown = false;

    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}

}

A: souldn't you just do this?
export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuShown: false;

constructor(private layoutService: LayoutService, private renderer: Renderer) { }

menuToggle(event: any) {
    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}

onMenuSelect(event: any) {
    this.isMenuShown = false;

    this.menuToggle(event); // Must apply the event binding as well
}

}


Q: Viewing Equirectangular Map I'm writing an equirectangular map viewer, all the stuff I have found so far are about the projection, conversions and inverse ones, which is the easiest part.
I don't want to use OpenGL or DirectX sphere texture solutions, I want to draw the image pixel by pixel. The only problem I have is in transformation of the viewer's camera rectangle.
I mean, I have a rectangle through which the viewer shows the equivalent pixels on the map. When viewer looks up or down, or left or right, this view changes, but the changes are not linear, even in a spherical coordination system. As the rectangle's dimensions should kept constant in a Cartesian sense, otherwise we will have a deformation.
Can anyone tell me how to solve this problem? A link to a good document, or a hint to where I start is all that I need. Thanks in advance.

A: Ok, nobody answered it, and I figured it out. There are two "practical" solutions, first one is using the Quaternions. You can define a 3d rectangle as a view and then rotate it using quaternions. After that you can sweep on the resulting rectangle, and use the reverse transforms to get the map coordinates. The other solution, which seems faster to me, is using Euler's rotation matrices. Just pay attention to use ArcTan2 instead of ArcTan function, because you need 2*PI coverage. That's all I wanted!


Q: jQueryUI add click function for multiple buttons I have a page with some number of info dialog boxes (5 in this example).  The objective is to have a variable number of info boxes on a page each called by a unique button.  When the button is clicked, any other box is closed and the current box appears. Instead of trying to keep track of which box was opened or about to open, I thought I'd simply close all the boxes and open the current info box.
The code below works: the first for loop initializes all of the dialog boxes and the closeBoxes() function closes any dialog that's open before opening the assigned dialog box.  However it seems like I should be able to loop through the .click(function()..) and add any number of info boxes.  I've tried $("#btn"+i)...("#info"+i) in a loop, but that simply doesn't work.
var TotalInfoBoxes=5;
for ( var i=1; i<=TotalInfoBoxes; i++) {
    $("#info"+i).dialog({ autoOpen: false });
}

$("#btn1").click(function() { closeBoxes(); $("#info1").dialog( "open" ); });
$("#btn2").click(function() { closeBoxes(); $("#info2").dialog( "open" ); });
$("#btn3").click(function() { closeBoxes(); $("#info3").dialog( "open" ); });
$("#btn4").click(function() { closeBoxes(); $("#info4").dialog( "open" ); });
$("#btn5").click(function() { closeBoxes(); $("#info5").dialog( "open" ); });

function closeBoxes() {
    for (var i=1; i<=TotalInfoBoxes; i++){
        $("#info"+i).dialog("close");
    }
}

The dialog box is an elegant solution, but I need some more generic code as I may have 20 or 30 info boxes on a given page.  Greatly appreciate your input.

A: for close dialog box simple use by this all dialog box close
they all inherit the same class, this is the best way to select all and close by:
$(".ui-dialog-content").dialog("close");

A: make sure that the buttons and dialogs have a common class say btn for buttons &  info for your dialogs
$(".btn").on('click',function(e){
     closeBoxes();
     var index=$(this).index();
     $(".info:eq("+index+")").dialog("open");
});


Q: How to cleanly stub out REST client when in test environment I have a basic model like the following
class MyModel
    def initialize(attrs)
        @attrs = attrs
        @rest_client = Some::REST::Client.new
    end

    def do_a_rest_call(some_str)
      @rest_client.create_thing(some_str)
    end
end

For testing purposes, I don't want @rest_client to make remote calls. Instead, in a test environment, I just want to make sure that @rest_client gets called with a specific some_str when it goes through certain branches of code.
In an ideal world, I'd have an assertion similar to:
expect(my_model_instance).to.receive(do_a_rest_call).with(some_str) where in the test I will pass some_str to make sure it's the right one.
What's the best way to do this using RSpec 3.8 and Rails 5.2.2?

A: A solution that should work without any additional gems:
let(:rest_client_double) { instance_double(Some::REST::Client, create_thing: response) }

it 'sends get request to the RestClient' do
  allow(Some::REST::Client).to receive(:new).and_return(rest_client_double)

  MyModel.new(attrs).do_a_rest_call(some_str)

  expect(rest_client_duble).to have_received(:create_thing).with(some_str).once
end

Basically, you are creating a double for REST client.
Then, you make sure that when calling Some::REST::Client.new the double will be used (instead of real REST client instance).
Finally, you call a method on your model and check if double received given message.


Q: Update databindings when a TextBox changes rather than loses focus I'm learning to develop for compact framework and I've come across an issue that's bugging me.
I've bound a couple of textboxes to some properties (firstname & lastname of a person class) and have a menuitem which just does a showmessage of the full name, and it works fairly well except that the properties only get updated once the textbox losses focus.  This means that if I change the firstname and press the show name menuitem, I get the old value of firstname.
Is there a way I can force an update of the databindings, or make it so that every time a character is changed in one of the textboxes the corresponding property is updated?

A: If you do this, you risk putting bad data into your data object, but here is how to do this:
In your MyTextBox.DataBinding.Add() method, use the this overload with OnPropertyChanged for the DataSourceUpdateMode param instead of the default OnValidate
I again say that this is one of those things that sounds really easy, but will likely cause issues in the long run as you are 'binding' to data that has never been validated.

A: Just call form's ValidateChildren() in the code on the button doing the save


Q: Fullscreen Frame Borders in Java LWJGL I want to make a game with Java and LWJGL. In many videogames you can see the black fields at the top and the bottom of the display, which is used to size the display in the resolution the game can work with.
I searched for this two days, but maybe I used wrong keywords.
So is there any possibility I can make this with LWJGL. Maybe a method I can use?


Q: Second date Picker should show dates after the date selected in first date picker I have two date pickers. In first I'm selecting a date, and I want second date picker to show the dates after that particular date. Previous dates should be disabled.

A: Use minimum date property of the date picker to disable the all date before the minimum date. The date picker would also allow you to define range as minimum and maximum date so that it can show the date from minimum to maximum date range and remaining all other date will be disabled in picker view.

A: swift 3
    datePickerEndDate.minimumDate = datePickerStartDate.date


Q: How can I apply MVVM and Commands in this specific WPF situation? I am having trouble with the MVVM pattern and Commands in my WPF app. The problem is not so much the MVVM pattern, but more the stuff that is going on on my GUI. I'll explain the situation:
My app can DoStuff to some files. I have a class with a function DoStuff(int limit). My user user interface has the following items:

*

*A Button DoStuffBtn to start parsing.

*A TextBox LimitTxt to fill in a limit.

*A CheckBox LimitChk to enabled or disable the limit.

When you would "uncheck" LimitChk, then LimitTxt.Text = "" and LimitTxt.IsEnabled = false. When you would "check" LimitChk, then LimitTxt.IsEnabled = false again, but the text remains empty until you fill something in.
I have read many tutorials on Commands in WPF and MVVM but I just can't seem to pour my case into that mold. The example I gave is actually just a small part of my UI, but I can't seem to do this nicely either.
I keep running into questions like:

*

*Do I need two Commands for LimitChk (enable and disable) or just one (toggle)?

*If I bind an int to LimitTxt, what happens if I make it empty and disable it?

*Is it a clean way to just use DoStuff(Int32.Parse(LimitTxt.Text)) when DoStuffBtn is pressed?

*If I use two commands on LimitChk, what happens with the CanExecute() function of ICommand that determines whether LimitChk is enabled?

So the main question is: How would the situation I described fit into a nice pattern using Commands in WPF?
Some links on WPF, Commands and MVVM i've looked at:

*

*http://www.devx.com/DevX/Article/37893/0/page/1

*http://msdn.microsoft.com/en-us/magazine/cc785480.aspx?pr=blog

*http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/432/MVVM-for-Tarded-Folks-Like-Me-or-MVVM-and-What-it-Means-to-Me.aspx

*http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

What I understand so far is that I have to keep as much as possible out of the UI. Even stuff like UI influencing the UI. I.e. unchecking LimitChk disables LimitText. Still, I think I should keep a difference between UI related information and actions and stuff that actually has to do with the actual work that has to be done.

A: I think you're getting confused... you don't need any commands here, you can just use bindings.

*

*Do I need two Commands for LimitChk (enable and disable) or just one (toggle)?

You need none. Just create a LimitEnabled property in your ViewModel, and bind the CheckBox to it (IsChecked="{Binding LimitEnabled}")

*

*If I bind an int to LimitTxt, what happens if I make it empty and disable it?

Disabling it has no effect. If you make the TextBox empty, the binding will fail because an empty string can't be converted to an int (at least not with the default converter)

*

*Is it a clean way to just use Parse(Int32.Parse(LimitTxt.Text)) when ParseBtn is pressed?

You don't need to. Just create a Limit property in your ViewModel, and bind the TextBox to it. You might want to add an ExceptionValidationRule to the Binding so that it highlights invalid input.
The button is not necessary, the parsing will be done automatically when the TextBox loses focus (if you use the default UpdateSourceTrigger). If you want to customize the way it's parsed, you can create a custom converter to use in the binding.

A: Just some high level thoughts, leaving out superfluous stuff like Color and alignment attributes, WrapPanels, etc.
Your ViewModel has a a couple properties:
public bool? LimitIsChecked { get; set; }
public bool LimitTextIsEnabled { get; set; }  //to be expanded, below
public ICommand ParseCommand { get; private set; } // to be expanded, below
public string LimitValue { get; set; } // further explanation, below

Your XAML has CheckBox and TextBox definitions something like:
<CheckBox Content="Limit Enabled" IsChecked="{Binding LimitIsChecked}" />
<TextBox Text="{Binding LimitValue}" IsEnabled="{Binding LimitIsEnabled}" />
<Button Content="Parse" Command="{Binding ParseCommand}" />

You'll want to initialize ParseCommand something like this:
this.ParseCommand = new DelegateCommand<object>(parseFile);

Now, let's fill in that LimitTextIsEnabled property too:
public bool LimitTextIsEnabled {
    // Explicit comparison because CheckBox.IsChecked is nullable.
    get { return this.LimitIsChecked == true; }
    private set { }
}

Your parseFile method would then pass the value of the LimitValue property to the logic doing the actual parsing.
I declared the LimitValue property as string here to avoid cluttering up the code with an explicit converter, or other validation code.  You could choose to handle that "LimitValue is a valid int" verification/conversion in several different ways.
Of course, I haven't implemented this in its entirety, but I wanted to outline a pattern where you are not using Commands to update the state of the other widgets.  Instead, bind those attributes to properties that are managed in your ViewModel.


Q: Angular component as the Mapbox control Does anybody know: can I use an angular component as the Mapbox custom control? I need to add a few buttons on the map, but I see I have to pass an HTML element.

A: I did this using https://stackoverflow.com/a/54561421/12302484. I've made the class that implements the IControl interface. Then returned the component from the onAdd method resolved by dynamic component service.
map.component.ts:
private configureControls(): void {
    this.map.dragRotate.disable();
    this.map.touchZoomRotate.disableRotation();
    this.map.addControl(new mapboxgl.NavigationControl({ showCompass: false }));
    this.map.addControl(new CustomMapControls(this.dynamicComponentService));
}

custom-map-controls.ts:
export class CustomMapControls {
    private _container: HTMLElement;
    private _switchColorButton: HTMLElement;

    private map: mapboxgl.Map;
    private dynamicComponentService: DynamicComponentService;

    constructor(dynamicComponentService: DynamicComponentService) {
        this.dynamicComponentService = dynamicComponentService;
        this._container = document.createElement('div');
        this._container.classList.add('mapboxgl-ctrl', 'mapboxgl-ctrl-group');
    }

    getDefaultPosition(): any {
        return undefined;
    }

    onAdd(map: mapboxgl.Map): HTMLElement {
        this.map = map;
        this._container.appendChild(this.dynamicComponentService.injectComponent(MapColorSwitcherComponent));
        return this._container;
    }

    onRemove(map: mapboxgl.Map): any {
    }
}

result:


Q: How to fix segfault caused by a realloc going out of bounds? Hello and TIA for your help. As I am new to to posting questions, I welcome any feedback on how this quesiton has been asked. I have researched much in SO without finding what I thought I was looking for.
I'm still working on it, and I'm not really good at C.
My purpose is extracting data from certain specific tags from a given XML and writing it to file. My issue arises because as I try to fill up the data struct I created for this purpose, at a certain point the realloc() function gives me a pointer to an address that's out of bounds.
If you look at this example
#include <stdio.h>

int main() {
    char **arrayString = NULL;
    char *testString;
    testString = malloc(sizeof("1234567890123456789012345678901234567890123456789"));
    strcpy(testString, "1234567890123456789012345678901234567890123456789");
    int numElem = 0;
    while (numElem < 50) {
        numElem++;
        arrayString = realloc(arrayString, numElem * sizeof(char**));
        arrayString[numElem-1] = malloc(strlen(testString)+1);
        strcpy(arrayString[numElem-1], testString);
    }
    printf("done\n");
    return 0;
}

it does a similar, but simplified thing to my code. Basically tries to fill up the char** with c strings but it goes to segfault. (Yes I understand I am using strcpy and not its safer alternatives, but as far as I understand it copies until the '\0', which is automatically included when you write a string between "", and that's all I need)
I'll explain more in dephth below.
In this code i make use of the libxml2, but you don't need to know it to help me.
I have a custom struct declared this way:
 struct List {
    char key[24][15];
    char **value[15];
    int size[15];
 };

struct List *list; //i've tried to make this static after reading that it could make a difference but to no avail

Which is filled up with the necessary key values. list->size[] is initialized with zeros, to keep track of how many values i've inserted in value.
value is delcared this way because for each key, i need an array of char* to store each and every value associated with it. (I thought this through, but it could be a wrong approach and am welcome to suggestions - but that's not the purpose of the question)
I loop through the xml file, and for each node I do a strcmp between the name of the node and each of my keys. When there is a match, the index of that key is used as an index in the value matrix. I then try to extend the allocated memory for the c string matrix and then afterwards for the single char*.
The "broken" code, follows, where

*

*read is the index of the key abovementioned.

*reader is the xmlNode

*string contained the name of the xmlNode but is then freed so consider it as if its a new char*

*list is the above declared struct

if (xmlTextReaderNodeType(reader) == 3 && read >= 0)
    {
        /* pull out the node value */
        xmlChar *value;
        value = xmlTextReaderValue(reader);
        if (value != NULL) {
            free(string);
            string=strdup(value);
            /*increment array size */
            list->size[read]++;
            /* allocate char** */ list->value[read]=realloc(list->value[read],list->size[read] * sizeof(char**));
            if (list->value[read] == NULL)
                return 16;
            /*allocate string (char*) memory */
            list->value[read][list->size[read]-1] = realloc(list->value[read][list->size[read]-1], sizeof(char*)*sizeof(string));
            if (list->value[read][list->size[read]-1] == NULL)
                return 16;
            /*write string in list */
            strcpy(list->value[read][list->size[read]-1], string);
        }
        /*free memory*/
        xmlFree(value);
    }
    xmlFree(name);
    free(string);

I'd expect this to allocate the char**, and then the char*, but after a few iteration of this code (which is a function wrapped in a while loop) i get a segfault.
Analyzing this with gdb (not an expert with it, just learned it on the fly)  I noticed that indeed the code seems to work as expected for 15 iteration. At the 16th iteration, the list->value[read][list->size[read]-1] after the size is incremented, list->value[read][list->size[read]-1] points to a 0x51, marked as address out of bounds. The realloc only brings it to a 0x3730006c6d782e31, still marked as out of bounds. I would expect it to point at the last allocated value.
Here is an image of that: https://imgur.com/a/FAHoidp
How can I properly allocate the needed memory without going out of bounds?

A: Your code has quite a few problems:

*

*You are not including all the appropriate headers. How did you get this to compile? If you are using malloc and realloc, you need to #include <stdlib.h>. If you are using strlen and strcpy, you need to #include <string.h>.

*Not really a mistake, but unless you are applying sizeof to a type itself you don't have to use enclosing brackets.

*Stop using sizeof str to get the length of a string. The correct and safe approach is strlen(str)+1. If you apply sizeof to a pointer someday you will run into trouble.

*Don't use sizeof(type) as argument to malloc, calloc or realloc. Instead, use sizeof *ptr. This will avoid your incorrect numElem * sizeof(char**) and instead replace it with numElem * sizeof *arrayString, which correctly translates to numElem * sizeof(char*). This time, though, you were saved by the pure coincidence that sizeof(char**) == sizeof(char*), at least on GCC.

*If you are dynamically allocating memory, you must also deallocate it manually when you no longer need it. Use free for this purpose: free(testString);, free(arrayString);.

*Not really a mistake, but if you want to cycle through elements, use a for loop, not a while loop. This way your intention is known by every reader.

This code compiles fine on GCC:
#include <stdio.h> //NULL, printf
#include <stdlib.h> //malloc, realloc, free
#include <string.h> //strlen, strcpy

int main()
{
    char** arrayString = NULL;
    char* testString;
    testString = malloc(strlen("1234567890123456789012345678901234567890123456789") + 1);
    strcpy(testString, "1234567890123456789012345678901234567890123456789");
    for (int numElem = 1; numElem < 50; numElem++)
    {
        arrayString = realloc(arrayString, numElem * sizeof *arrayString);
        arrayString[numElem - 1] = malloc(strlen(testString) + 1);
        strcpy(arrayString[numElem - 1], testString);
    }
    free(arrayString);
    free(testString);
    printf("done\n");
    return 0;
}


Q: Are there really people who spend all day going through StackOverflow, closing people's questions, and costing them points? What is the "subjective" tag for, if not to ask subjective questions?  "This question is ambiguous, vague, incomplete, or rhetorical and cannot be reasonably answered in its current form." sounds Subjective to me.  Who are these lovely people?  Is SO meant to be a grim, colorless place?

A:
Is SO meant to be a grim, colorless place?

No. You're thinking of Meta.
BTW, welcome to Meta...

A: Your question: What Should Be The Punishment for this? was a great question, for a discussion forum.
Stack Overflow is the place to get your programming questions answered, not a place to chew the fat.  You can even see it in the way the site is structured: It's really hard to have a conversation, but really easy to ask a question and have n people answer that question.


Q: Displaying images and their accompanying information from a database with codeigniter Ok so im uploading images to a folder on my server, and then trying to re-display them with their information.
This is the function in my model that i am using to pull the info:
    public function pull_all(){

    $this->db->select('file_name, file_type, full_path, image_type');
    $query = $this->db->get('img');
    $dbInfo = $query->result_array();
    return $dbInfo;

}

The controller implements the function like so:
function show_all(){

    $this->load->model('image_work');
    $data = array('dbInfo' => $this->image_work->pull_all());

    $data['title'] = "Uploads";
    $this->load->view('templates/header', $data);
    $this->load->view('show_all',$data);
    $this->load->view('templates/footer', $data);
}

The problem iv been having is in the view. I want each image to be shown with its info in  this format:

$image_name

$image_type

$image_size

$image_dimensions

Iv tried many different ways to do it for example nested foreach statements, but I just cant seem to get it right. Any help would be appreciated.
thanks

A: You can do like this:
<?php foreach($dbInfo as $image): ?>

        <img src="<?php echo $image['full_path']; ?>"/>

<?php echo $image['image_name']; ?>

<?php echo $image['image_type']; ?>

<?php echo $image['image_size']; ?>

<?php echo $image['image_dimensions']; ?>

<?php endforeach; ?>


Q: Cocoapods Error - Trouble in installing MapboxNavigation podfile -Mapboxnavigation sdk In order to implement MapbocNavigation podfile according to mapboxnavigationsdk official documentation.adding Mapbox-iOS-SDK and MapboxNavigation through Cocoapods, always get error, shown bellow.enter image description here
Also tried: Generate access token and use secret key from Mapbox account and also configure .nertc file with secret key, follow all the steps of .nertc file configuration and research more about this error and implement all the possible ways but yet I am facing this error...

A: First, please remove already created .netrc files with this command.
sed -i '' '/^machine api.mydomain.com$/{N;N;d;}' ~/.netrc

Then Try To create new .netrc file with this steps:
To create .netrc file do next
Fire up Terminal
cd ~ (go to the home directory)
touch .netrc (create file)
open .netrc (open .netrc)
Set required data.
Save

.netrc file should be like this
machine api.mapbox.com
login mapbox
password <secret_key_created_from_your_mapbox_account>

May be it will help to you. If Its Help then please upvote to my answer.


Q: Could be in Optional really anything I found implemented this code (method where this part of code is used is returning Optional<File>, this part of code had to be added for verification if values are correct and case can be saved):
if (!CaseChecker.checkValues(case)) {
    return Optional.of(new File("FALSE"));
}

When I asked the person, why he is returning something like this. The answer was "Optional can contain any value". To be honest I don't agree with this, because type of Optional is for some reason. So I wanted to confirm if Optional can be really anything and if yes, then what's the reason to write Optional type.

A: The whole point of Optional is to avoid the situation where you return a bogus value (like null, or like returning -1 from String.indexOf in order to indicate it didn't find anything), putting the responsibility on the caller to know what is bogus and to know to check for it. Returning Optional lets the caller know it needs to check whether a valid result came back, and it takes away the burden of the caller code needing to know what return values aren't valid.
Optional was never meant as a wrapper for a bogus value.
And yes you can return anything. The api doesn't stop you from doing nonsensical things.
Also consider that flatMap doesn't know what to do with this weird thing, it will treat the contents as nonempty. So now how you can use this value is limited. You have a multistage validation process where it might be something you can handle with operations chained together using flatMap, but this fake file has made that harder. It's limited your options.
Return Optional.empty() if you don't have a valid value to return.