Add KDE on to a histogram

Question: I would like to add a density plot to my histogram diagram. I know something about pdf function but I've got confused and other similar questions were not helpful.
from scipy.stats import *
from numpy import*
from matplotlib.pyplot import*
from random import*

nums = []
N = 100
for i in range(N):
    a = randint(0,9)
    nums.append(a)

bars= [0,1,2,3,4,5,6,7,8,9]
alpha, loc, beta=5, 100, 22

hist(nums,normed= True,bins = bars)

show()

I'm looking for something like this
Comment: You might be interested in seaborn's [``kdeplot``](https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.kdeplot.html) function.
Comment: See https://stackoverflow.com/questions/33203645/how-to-plot-a-histogram-using-matplotlib-in-python-with-a-list-of-data/33203848#33203848
Answer: from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(41)

N = 100
x = np.random.randint(0, 9, N)
bins = np.arange(10)

kde = stats.gaussian_kde(x)
xx = np.linspace(0, 9, 1000)
fig, ax = plt.subplots(figsize=(8,6))
ax.hist(x, density=True, bins=bins, alpha=0.3)
ax.plot(xx, kde(xx))

Comment: in "plt, ax = plt.subplots(figsize=(8,6))", you might want to replace "plt" with "fig" on the LHS.
Comment: After version 3.1.1 or so, `normed` keyword is no longer there, should use `density` instead. [commit link](https://github.com/matplotlib/matplotlib/commit/c015c4aae7338b58f3aa677e57fb82e8755ecc6e#diff-9e2655db1b2a6796cb9bacd9400e3ac063f5c8de8f6c81537df2591629e6fb5aR56)
Comment: Shouldnt it be ax.plot(xx, kde) on last line instead?
Comment: @ErroriSalvo, think of a `kde` as a fitted function. In the last line we evaluate `kde` at all positions in the array `xx`. It's similar to plotting a quadratic function: `plot(x, lambda x: x**2)`
Comment: @SolomonVimal, thanks for catching that. That was a typo!
Answer: Here's a solution using seaborn 0.11.1 and pandas 1.1.5:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

N = 100
nums = [np.random.randint(i-i, 9) for i in range(N)]
df = pd.DataFrame(nums, columns=["value"])

fig, ax1 = plt.subplots()
sns.kdeplot(data=df, x="value", ax=ax1)
ax1.set_xlim((df["value"].min(), df["value"].max()))
ax2 = ax1.twinx()
sns.histplot(data=df, x="value", discrete=True, ax=ax2)

Note how I use numpy to generate the random values because I need actual values, not generators. The discrete=True in the last line assures that the ticks are centered.
Answer: distplot from Seaborn offers histogram plot as well as distribution graph together:
sns.distplot(df)

Comment: Note that it returns the plot where y-axis  *Count*  instead of *Density*.
Comment: or sns.displot(df, kde=True) for displot, which supersedes distplot

Add KDE on to a histogram


How to display one row from a HTML table and change to next?

Question: I have a HTML table with 2 columns, 5 rows.
Answer: you can do this:
<code>function findMyRow(el)(){
    if(!el.parentNode) return null;
    else if(el.parentNode.tagName.toLowerCase()=="tr") return el.parentNode;
    else return findMyRow(el.parentNode);
}
for(var i=0;i<tbl.rows.length;i++){
    tbl.rows[i].onclick = function(e){
        var selectedRow = null;
        if(e.target.tagName.toLowerCase()=="tr") selectedRow = e.target;
        selectedRow = findMyRow(e.target);
        //this is just for preventing false event raising
        if(!selectedRow) return false;
        var rowIndex = Array.prototype.indexOf.call(tbl.rows, selectedRow);
        for(car j=0;j<selectedRow.cells.length;j++){
            var cell = selectedRow.cells[j];
            //let's say your inputs each has an unique ID based on your columns index
            //like <input id="cellData0" ttype="text" />
            //or <input id="cellData1" ttype="text" /> and so on
            document.getElementById("cellData" + j).value = cell.innerText;
        }
    }
}
</code>
although you can do this more easier than with jQuery.
Answer: With Jquery you could do something like:
<code>$(document).ready(function(){
    window.rowIndex = 0; // gobal variable

    function displayRow(){
        var tableRows = $('#mytable tr');
        if(tableRows.length <= window.rowIndex) {
            window.rowIndex = 0;
        }
        var rowCells = $(tableRows[window.rowIndex]).find('td');
        $('.cellone').val($(rowCells[0]).html());
        $('.celltwo').val($(rowCells[1]).html());
        window.rowIndex = window.rowIndex + 1;
    };

    $('.next').click(function(event){ displayRow(); });
    displayRow();
});
</code>
There is a live demo here Hope it helps!


Class-level variable doesn't stay set

Question: I have a .net website I am working on which uses repeaters to build out several tables. As part of the Databind, I am adding keys to a class-level dictionary object so that later I can recall them and check if they have been changed. Below is my code:
<code>public partial class pointsEdit : System.Web.UI.Page
{

    public Dictionary<Int32, TextBox[]> PointsValues;

    protected void Page_Load(object sender, EventArgs e)
    {
        Int32 clientID = 0;
        if (Request.QueryString["id"] != null)
        {
             if (Int32.TryParse(Request.QueryString["id"], out clientID) == true) {
                 //try
                 //{
                     if (!IsPostBack)
                     {
                         btnReturn.HRef = "clientEdit.aspx?id=" + clientID;

                         PointsValues = new Dictionary<int, TextBox[]>();
                         using (var db = new db())
                         {

                             var ev = db.activityPoints.Where(x => x.ClientID == clientID).ToArray();
                             tblEvent.DataSource = ev;
                             tblEvent.DataBind();

                         }

                     }
                 //}
                 //catch
                 //{

                 //}
             }
        }

    }

    protected void tblEvent_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

            using (var db = new db())
            {
                Int32 TypeKey;
                Int32 ActivityID;
                Int32.TryParse(DataBinder.Eval(e.Item.DataItem,"TypeKey").ToString(),out TypeKey);
                Int32.TryParse(DataBinder.Eval(e.Item.DataItem, "ActivityID").ToString(), out ActivityID);

                var ev = db.events.Where(x => x.ID == TypeKey).First();
                ((Label)e.Item.FindControl("lblEvent")).Text = ev.name.ToString();
                ((TextBox)e.Item.FindControl("tbPointValue")).Text = DataBinder.Eval(e.Item.DataItem, "MaxPointsEach").ToString();
                ((TextBox)e.Item.FindControl("tbMaxScored")).Text = DataBinder.Eval(e.Item.DataItem, "MaxAttempts").ToString();

                PointsValues.Add(ActivityID, new TextBox[] { ((TextBox)e.Item.FindControl("tbPointValue")), ((TextBox)e.Item.FindControl("tbMaxScored")) });

            }
    }

   protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Int32 ActivityID;
        TextBox[] TextBoxes;
        Int32 clientID = 0;
        Int32 ParseResult = 0;
        Int32 MaxPoints = 0;
        Int32 MaxAttempts = 0;
        Boolean NeedsUpdate = false;

          if (Request.QueryString["id"] != null)
          {
              if (Int32.TryParse(Request.QueryString["id"], out clientID) == true)
              {
                  //try
                 //{

                      using (var db = new db())
                      {
                          var s = db.activityPoints.Where(x => x.ClientID == clientID).ToArray();

                          for (int i = 0; i < s.Length; i++)
                          {
                              ActivityID = s[i].ActivityID;
                              TextBoxes = PointsValues[ActivityID];
                          }
                      }

                  //} catch {

                  //}

                  }
              }

        }
 }
</code>
There is more code in the block which actually updates the values, but my loop only gets this far so I am removing that for simplicity's sake. When it gets to the "TextBoxes = PointsValues[ActivityID];" line of the submit method, it seems like the Dictionary object is no longer populated.
I have verified that there is an activity ID when it is added to the dictionary, and the count is correct for the number of objects that should have been added. At the Textboxes line, though, it tells me that "The given key was not present in the dictionary" and when I try to get a count, it gives the "object reference not set to an instance of an object" error. If I set the dictionary object to a new dictionary object just before that line, it allows me to get a count (of 0). It seems like the object is somehow being reset after being set up. Any ideas?
Comment: You are working with ASP.NET Web which means you would loose your object context once the request is processed. This would mean you dictionary would be lost. You should either save it in session of some sort to maintain it across requests.
Comment: Glad I could help, have posted it as answer, please accept. Thanks!
Comment: This seems like it was my problem. Thank you!
Answer: You are working with ASP.NET Web which means you would loose your object context once the request is processed. This would mean you dictionary would be lost. You should either save it in session of some sort to maintain it across requests.
You can find details on how to implement session @ https://msdn.microsoft.com/en-us/library/ms972429.aspx?f=255&MSPPError=-2147217396

Class-level variable doesn't stay set


rollback mechanism for chunk oriented processing strategy of Spring Batch

Question: As we  all know, spring batch uses chunk oriented processing since the version 2.0.
Does it mean that, if an exception occurs in the item writer, the Data Source Transaction manager will roll back the whole chunk or only the related item?
Actually, I gave it a try and saw that the framework rolls back the whole chunk. That's not what I need because I do not want, let's say, 499 items which have been processed successfully to be rolled back in a chunk consisting of 500 items when the last item causes an exception to be thrown.
The only solution I was able to find is to add the attribute below to my tasklet. However, I am not sure if this is the right thing to do.
<code><batch:transaction-attributes propagation="NOT_SUPPORTED"/>
</code>
Another opinion was to simply reduce the chunk size to 1 (one) but that one also doesn't make much sense.
Maybe Spring Batch is not suitable for my problem domain. If so, please tell me so I won't be struggling with those kind of framework specific behaviour anymore.
Any suggestions would be greatly appreciated.
Answer: Your right : the whole chunk lot is rollbacked.
I faced the same problem and did the following :

adapt the batch size according to the database (I was using batch statement to save my updates). 25 was a good value for us: better than 1 (batch benefits), not too much (huge transactions).
relaunch this step a limited times : we enabled re-executing this task 3 times maximum.

This was well working because corrections could happen during the batch processing (corrections done by GUI).
At the end of our process, all datas marked as failed and retried 3 times were definitively marked as failures in our batch report : then need a human correction or a special process.
Answer: The solution might be to stop propagating the exception in writer and catch it. This will prevent batch from rolling back as you catch the exception and do your custom handling.
Answer: You can open an different transaction inside the writer method with Propagation.REQUIRES_NEW to handle this use case.


How to mark my current position on the osm map?

Question: I want to do a simple thing. I would like to mark a point of my current location.
At the moment I have osm map that display the screen with my current location, on top of this I can see my current position (longitude and latitude), but I don't know how to mark the current location.
Comment: Dear Anna, please avoid crossposts as they consume a lot of energy of the community that likes to help everybody on solving problems.
http://gis.stackexchange.com/questions/81960/how-to-mark-my-current-position-on-the-osm-map
Answer: I've not used OSMDroid a huge amount but you could mark your location using an ItemizedIconOverlay. This sample should show you how to create the overlay, and then instead of creating an overlay list containing the cities, it instead should just have a single item which is your current location.
Answer: It's a little unclear what you are asking but you are probably looking for the MyLocationNewOverlay. This will monitor the GPS and plot an icon at your location. The OpenStreetMapViewer sample covers this. The icon will move as your location moves so if you are looking to put a permanent marker that stays put then you want to use an ItemizedIconOverlay.
Answer: This seems to be the minimum amount of code to get a point to display. You need a "blue_pin" image in drawable and a layout with "mapview" component.
public static final GeoPoint berlinGeoPoint = new GeoPoint(52.516667, 13.383333);
OverlayItem overlayItem = new OverlayItem("Berlin", "City", berlinGeoPoint);
Drawable markerDrawable= this.getResources().getDrawable(R.drawable.blue_pin);
overlayItem.setMarker(markerDrawable);

ArrayList<OverlayItem> overlayItemArrayList = new ArrayList<OverlayItem>();
overlayItemArrayList.add(overlayItem);
ItemizedOverlay<OverlayItem> locationOverlay = new ItemizedIconOverlay<OverlayItem>(this, overlayItemArrayList, null);

MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.getOverlays().add(this.locationOverlay);


Set variable different values depending on IF ELSE condition in batch file

Question: My goal is to set %PF% variable to C:\ProgramFiles(x86)\MSBuild\ on x64 machines and to C:\ProgramFiles\MSBuild\ on x86 machines.
I can easily achieve that such way
IF DEFINED ProgramFiles(x86) SET PF=%ProgramFiles(x86)%\MSBuild\
IF NOT DEFINED ProgramFiles(x86) SET PF=%ProgramFiles%\MSBuild\

But I want to do that in a single IF ELSE statement.
That one
IF DEFINED ProgramFiles(x86) (SET PF=%ProgramFiles(x86)%\MSBuild\) ELSE (SET PF=%ProgramFiles%\MSBuild\)

fails with unexpected "\MSBuild\" error.
That one
IF DEFINED ProgramFiles(x86) (SET PF="%ProgramFiles(x86)%\MSBuild\") ELSE (SET "PF=%ProgramFiles%\MSBuild\")

runs without errors.
But the result value is not what I need ("%ProgramFiles(x86)%\MSBuild\" - instead of "C:\ProgramFiles(x86)\MSBuild\" on x64 machine for example).
So is that possibe?
Comment: Currently you can solve your problem with the answer of Stephan, but when you embedd your code into a code block you should also read [SO: What syntax will check if a variable name containing spaces is defined?](http://stackoverflow.com/questions/8254571/what-syntax-will-check-if-a-variable-name-containing-spaces-is-defined), as you will get problems with the closing bracket in `if defined ProgramFiles(x86)`
Comment: Thx for that information
Answer: use this syntax:
SET "PF=%ProgramFiles(x86)%\MSBuild\"

Note the position of the quotes.


PHP unlink not working in codeigniter

Question: codeigniter folder structure
application
system
user_guide
uploads

Code:
unlink('http://sale.coupsoft.com/uploads/'.$checkbox[$i]['Image']);

I want to remove file from uploads folder but I am an unable to delete file by using HTTP.How can I remove file? my coding is correct but I am using HTTP so this displaying error. I am weak in English. so please apologize me if I made any Grammatical or spelling mistakes.
Comment: You have to provide relative path in unlink().
Comment: can you explain me how to write?
Comment: For example if you have windows system you have to write path like c://xampp/htdocs/projectfolder/uploads/filename instead of http://localhost/projectfolder/uploads/filename
Answer: you can not use image full path please add image full path /var/www/html/projectfolder/uploads/filename.
See Below Codeigniter Example:
<?php
  $url = FCPATH . 'uploads/filename';
 if (unlink($url)) {
  echo "File Successfully deleted.";
 }
?>

Answer: Unlink does not work like that, its works on relative path, try it like this :
unlink('./uploads/'.$checkbox[$i]['Image']);

Answer: Unlink does not working like this . You should pass relative path of your file rather than absolute path.
Also For any file three step neccessary as:
file_exists
realpath
is_writable

After this unlink for delete file
unlink('./uploads/'.$checkbox[$i]['Image']);

Answer: You can try this, it's working for mine:
$url = FCPATH.'uploads/'.$checkbox[$i]['Image'];
if (unlink($url)) {
  echo "Deleted!";
}

PHP unlink not working in codeigniter


Problem with binding Nullable value to WPF ComboBox

Question: I am binding a WPF ComboBox to a nullable property of type MyEnum? (where MyEnum is an enumerated type)
I am programmatically populating the ComboBox items like this:
// The enum type being bound to
enum MyEnum { Yes, No }

// Helper class for representing combobox listitems
// (a combination of display string and value)
class ComboItem {
  public string Display {get;set}
  public MyEnum? Value {get;set}
}

private void LoadComboBoxItems()
{
  // Make a list of items to load into the combo
  var items = new List<ComboItem> {
    new ComboItem {Value = null, Display = "Maybe"},
    new ComboItem {Value = MyEnum.Yes, Display = "Yes"},
    new ComboItem {Value = MyEnum.No, Display = "No"},};

  // Bind the combo's items to this list.
  theCombo.ItemsSource = items;
  theCombo.DisplayMemberPath = "Display";
  theCombo.SelectedValuePath = "Value";
}

Also in the code-behind, I am setting the DataContext to an instance of a class with a property called TheNullableProperty (for this example anyway) of type MyEnum?.
The binding of theCombo's SelectedValue is done in my XAML file.
<ComboBox
  Name="theCombo"
  SelectedValue="{Binding Path=TheNullableProperty,
                          UpdateSourceTrigger=PropertyChanged}"/>

Problem:
When the value of the bound property is initially non-null, the combo box displays the value properly.
But when the value of the bound property is initially null, the combo box is blank.
It looks like every aspect of data binding is working apart from the representation of the null value when the combobox is first shown.
For example: you can select Maybe from the dropdown, and the bound property is correctly set to null. It's just that initial loading that's failing. Maybe I need to just manually set the SelectedValue initially...
What I Ended Up Doing

Add a hidden textblock databound to the underlying nullable enum value via a Converter that converts from the nullable enum to a string (enum.ToString, or "null").
Load up the combo box with 'ComboItems' each having a string Label (displayed in the combo) and a string Value equal to the enum values as strings (and "null" for the null value).
Data-bind the combo box to the textblock.
///
/// Convert from EnumeratedType? to string (null->"null", enum values->ToString)
///
public class EnumConverter<T> : IValueConverter where T:struct
{
  public static string To(T? c)
  {
    if (c == null)
      return "null";
    return c.ToString();
  }

  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return To((T?)value);
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var s = (string) value;
    if (s == "null")
      return null;
    return (T?)Enum.Parse(typeof(T), s);
  }
}

public class MyEnumConverter : EnumConverter<MyEnum>
{
}

public class ComboItem
{
  public string Value { get; set; }
  public string Label { get; set; }

  public ComboItem(MyEnum? e, string label)
  {
    Value = MyEnumConverter.To(e);
    Label = label;
  }
}

static IEnumerable<ComboItem> GetItems()
{
  yield return new ComboItem(null, "maybe");
  yield return new ComboItem(MyEnum.Yes, "yup");
  yield return new ComboItem(MyEnum.No, "nope");
}

private void SetupComboBox()
{
  thecombo.ItemsSource = GetItems().ToList();
}

Answer: You cannot bind to a null value by design in WPF (at least 3.5 SP1). This means that at the moment Source gets a Null as a value your Binding will be automatically broken and won't work even if you specify a valid value for the Source. You need to provide some "heart beating" mechanism for your binding via Value Converter. So that Converter transforms null value to some "Undefined" (non-null) for the Targets and than is able to convert your "Undefined" back to null...
Comment: I think null is a special value in the case of ItemsControls. You can bind null to eg a TextBlock as long as you provide a converter. A converter is no help with making ItemsControls accept null as a selected item AFAICS.
Answer: There seem to be many issues with having null be a valid value for a ComboBox or ListBox, as similar questions have been asked here, here and here.
There hasn't been a superb, ogre-slaying answer to any of those.
My own suggestion is to add Maybe as a member of MyEnum.  I know it's just an example but if everything with a MyEnum has it as nullable, then maybe MyEnum should have an Undefined member (or something similar), this is pretty common with enums anyway.
Comment: In this case MyEnum is generated from an XSD, and the property of type MyEnum being bound to is 'optional', so null represents 'attribute not present'. It's a pretty good way of representing the property in C#, but if WPF ComboBox can't handle it I'll have to do something else I suppose.
Answer: I found this solution online, which I think is pretty deck.  I don't fully understand the implementation -- it's some pretty serious .NET kung fu -- but it's great from my perspective as a user.  Give it a try:
http://philondotnet.wordpress.com/2009/09/18/how-to-select-null-none-in-a-combobox-listbox-listview/
Answer: DependencyProperty.UnsetValue Field
using System;

using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace MyConverters
{
  [ValueConversion(typeof(DateTime), typeof(String))]
  public class StringToIntConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      int number;

      return int.TryParse(value.ToString(), out number) ? number : DependencyProperty.UnsetValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      return value.ToString();
    }
  }
}

Answer: Here's a veryy simple solution to this problem:
Instead of having an item with a value of null in your ItemsSource, use DbNull.Value as item or as the item's value property.
I described this approach in detail here: https://stackoverflow.com/a/44170898/6713814


Unable to send message from API Gateway to FIFO SQS

Question: I have integrated a API Gateway with FIFO SQS queue using below link
https://medium.com/@pranaysankpal/aws-api-gateway-proxy-for-sqs-simple-queue-service-5b08fe18ce50
Below is the snippet of role policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "sqs:SendMessageBatch",
                "sqs:ReceiveMessage",
                "sqs:SendMessage"
            ],
            "Resource": "arn:aws:sqs:*:12345678:Stg"
        }
    ]
}

Whenever is try to test it from API Gateway it throws below error:-
"Message": "The request must contain the parameter MessageGroupId."
So I tried to send it via query string but still the error persist.
I have followed the same steps as per the above link for body template and header.
MessageGroupId=098

Simply passing above value in query string and body is below
{"ty":"ui"}

Comment: Can you put the whole code you are using?
Comment: There is no code. My Api Gateway is unable to send message to SQS wit the provided error:- ```"Message": "The request must contain the parameter MessageGroupId."```
Answer: You need to add MessageGroupId, and MessageDeduplicationId to the URL Query String Parameters in Method Execution. Same way you did for MessageBody.
You'll also need to add MessageGroupId, and MessageDeduplicationId to Integration Request. Again the same way you did with MessageBody.
Comment: Body template will be. Action=SendMessage&MessageGroupId=$input.params('MessageGroupId')&MessageDeduplicationId=$input.params('MessageDeduplicationId')&MessageBody=$input.body
Answer: You can extract the MessageGroupId and MessageDeduplicationId from the response of API gateway. eg: if the payload is something like below, you can extract the any properties from the payload.
Clear video tutorial here. https://www.youtube.com/watch?v=dXa9KA-G9Dg
Assume the payload is like this:
{
  "data" :{
    "jobNumber": "123456"
  }
}

Then the template in api gateway is below. It extract the jobNumber from the payload and set to MessageGroupId. Here the MessageDeduplicationId is   getting from the context.
#set($dedupId = $context.requestId)
#set($groupId = $input.json('$.data.jobNumber'))
Action=SendMessage&MessageBody=$input.body&MessageGroupId=$groupId&MessageDeduplicationId=$dedupId

Comment: This should be the accepted answer.


Is this question on non singular matrix valid?

Question:
If A is a non singular matrix satisfying $AB- BA = A$, then prove that $\det(B+I) =\det(B-I)$

But is this question even valid because if we take the determinant of both sides of the first equation we get:
$\det(AB- BA)= \det(A) \implies \det(AB)- \det(BA)= \det A \implies \det (A)= 0 $ but $\det (A) \ne 0$ for A to be non singular. So I think this question is wrong. Can someone please verify?
Comment: $AB-BA=A$ implies $AB=BA+A=(B+I)A$ etc.
Comment: Determinant is NOT a linear map.
Comment: $\det(AB - BA) \neq \det(AB) - \det(BA)$ in general.
Answer: The determinant is multiplicative, not additive.
In this case, we must bring up multiplicativity somewhere, clearly. Note that $AB - BA = A$. To bring multiplicativity here, note that $AB = BA + A $, so that $\det(AB) = \det((B+I)A)$. Then,  by multiplicativity,  $\det A\det B = \det A \det(B+I)$.
Similarly, we have $AB -BA = A$ so $AB - A = BA$, so $\det (A(B-I)) = \det A \det B$. Consequently, we get that $\det A \det (B+I) = \det A \det(B-I)$. Why can we conclude that $\det A \neq 0$? (Look at hypotheses). Now conclude.


How to group mysql inner join results from rows into columns

Question: Maybe my question isn't so clear, please let me explain:
What I need is to get a list of all users along with a corresponding client number/wholesaler combination, every client has 1 up to 4 different client number/wholesaler combo
In my db I have 2 tables
USERS
id | name
---------
1  | a
2  | b

CLIENT_NUMBERS
id | user_id | number | wholesaler
----------------------------------
1  | 1       | ac1    | aw1
2  | 1       | ac2    | aw2
3  | 2       | bc1    | bw1

Using a simple INNER JOIN I got client rows duplicated, one for each corresponding client number/wholesaler
I've managed to fix the results using GROUP_CONCAT in this query:
SELECT a.id AS user_id, a.name AS Name
GROUP_CONCAT(b.client_no, ', ', b.wholesaler SEPARATOR '; ') AS client_no_wholesaler
FROM users AS a
INNER JOIN client_numbers AS b ON a.id = b.user_id
GROUP BY ID

user_id | name | client_no_wholesaler
--------------------------------------------
1       | a    |  ac1, aw1; ac2, aw2
2       | b    |  bc1, bw1

So far so good, but I need to "explode" the client number/wholesaler combination into different columns so my results can look like this:
user_id | name | client_no_wholesaler1 | client_no_wholesaler2 | ...up to 4
----------------------------------------------------------------------------
1       | a    |  ac1, aw1             | ac2, aw2              |
2       | b    |  bc1, bw1             |                       |

Doing this after getting the query results with a simple PHP explode is not an option because I'm using a class to generate a XLS file and its based on my query result columns, any ideas will be appreciated.
Answer: What you want is generally called a "pivot".
Here's how you code it in sql using an extra join for each extra column:
SELECT
    a.id AS user_id,
    a.name AS Name,
    CONCAT(b1.client_no, ', ', b1.wholesaler) AS client_no_wholesaler1,
    CONCAT(b2.client_no, ', ', b2.wholesaler) AS client_no_wholesaler2,
    CONCAT(b3.client_no, ', ', b3.wholesaler) AS client_no_wholesaler3,
    CONCAT(b4.client_no, ', ', b4.wholesaler) AS client_no_wholesaler4
FROM users AS a
JOIN client_numbers AS b1 ON b1.user_id = a.id
LEFT JOIN client_numbers AS b2 ON b2.user_id = a.id and b2.id > b1.id
LEFT JOIN client_numbers AS b3 ON b3.user_id = a.id and b3.id > b2.id
LEFT JOIN client_numbers AS b4 ON b4.user_id = a.id and b4.id > b3.id
GROUP BY 1, 2

Note that the extra joins avoid duplicate joins by the addition of an ever-increasing id condition in the ON clause for the extra joins. If id isn't a suitable ordering column, chose something else to separate the joins.
Comment: "Pivot" i've learned something new today, thanks a lot, your query works as i needed


on click  select all value and copy to clipboard (cross browser support)

Question: I want to select all and copy to clipboard the value of input when the user clicks on the input itself with cross browser support.
Example:
onClick this:
<input value="Generated Value: www.google.com" />

it will SelectAll and copy the Generated Value: www.google.com to the clipboard
I have tried a few jquery ready made scripts but i can't get them to work this way as they only work if the user clicks on a button or href link.
Answer: Check the javascript library ZeroClipboard at davidwalsh.name/clipboard
I hope it will help you :-)


how do I split this curve?(Image Processing thing trying to find a math solution)

Question: I'm a newbie here please correct or guide me if i'm wrong.
I just want to find a solution for my problem
Here's the picture.
Curve to be split
I have the (x,y) coordinates of the curve.
I want to split the curve where the red line passes through in the image.
Would appreciate any guidance
Don't mean to be rude but, to the person who down voted me. Let me know where I can post this question if you have any idea of what I have here, or at least have courtesy to ask what my question exactly is if you couldn't understand the question I posted. Down voting certainly is not helpful
Comment: Welcome to stackexchange. You are more likely to get answers rather than downvotes if you edit your question to provide more information, and show us what you have tried and where you are stuck. Perhaps show us the table of values. Describe what it means to "split the curve". Perhaps tell us why you want to know. Without that kind of information the question is likely to be closed.
Comment: @EthanBolker Thank You. I'm doing image processing, which I know clearly is not related to this blog. I have the (x,y) coordinates for the white colour curve you can see on the image link. I would like to split the curve where the red line is passing through because they are edges of two entirely different objects. I though Mathematics would help me in this than the image processing group.
Answer: If you loop along the curve looking at adjacent pairs of points and compute the slope of the line joining each pair there will be a sudden jump when the curve changes direction sharply.
If the points are close together you might have to worry about numerical instability. Maybe pick points on the curve further apart. You might also have to worry about (nearly) vertical tangents. I think that's a solvable problem too.
Perhaps calculate the angle between successive secants rather than successive slopes. That means no division, so no division by (close to) $0$.
You could take pairs of points  a little farther apart in a first pass. When you identify the region with the cusp calculate more accurately there to find the actual point.
Edit in response to comment.
Using the bearing is possible - but calculating it when the direction is close to vertical might be a problem. You are probably better off watching directly for a change in angle between successive secants. To do that use the dot product.
At this point it probably makes sense to code up some possible algorithms and try them out on a variety of examples. That will give you a sense of what might work.
Comment: I can't skip any points on the curve. If I pick points further apart I might loss the actual point where I get a huge change in the direction of the curve.
Comment: See my edits. All I've provided is a strategy. You'll have to experiment with implementations to find one that works.
Comment: Thank You @Ethan Bolker. How about select discrete points on the curve. Then find the [bearing angle](http://www.mathsteacher.com.au/year7/ch08_angles/07_bear/bearing.htm) of the next point with respect to the present point. A sudden decrease or increase in the bearing might give me point where I need to split the curve. What do you think?
Comment: See my edit. I've retagged your question. If you want to do serious image processing I think you will have to know when linear algebra can help you.
Answer: This figure seems to be part of two egg shaped curves.
See How to place random points on an egg? for further reference.
Work with a coordinate system such that you can fix the points you have.
The red line seems to be a symmetry axis.
Where does this curve come from?
Comment: These do seem symmetric, but I guess I got lucky that I got such an edge while selecting a random edge that was detected after filtering of the image. There's no symmetry here, the red line is not a symmetry line. Got this from a random picture of a heap of potatoes I found online.


Missing Partial for render in rails

Question: I create partial which calling _topics_list.form.html.erb and have some code

    Name
    Description

  <% @topics.each do |topic| %>

      <%= topic.name %>

        <%= link_to topic.description, topic_path(topic), class:"link_for_column_problem" %>

      <%= topic.created_at.strftime("%d %b, %Y") %>

  <% end %>

Also I connect this partial with my index-file by <%= render 'topics_list'%>
When I try it I have error
Missing partial topics/_topics_list, application/_topics_list with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :arb, :jbuilder]}. Searched in:
  * "/home/dse/BlackListV2/app/views"
  * "/home/dse/.rvm/gems/ruby-2.7.0/gems/activeadmin-2.6.1/app/views"
  * "/home/dse/.rvm/gems/ruby-2.7.0/gems/kaminari-core-1.2.0/app/views"
  * "/home/dse/.rvm/gems/ruby-2.7.0/gems/devise-4.7.1/app/views"
  * "/home/dse/.rvm/gems/ruby-2.7.0/gems/actiontext-184.108.40.206/app/views"
  * "/home/dse/.rvm/gems/ruby-2.7.0/gems/actionmailbox-184.108.40.206/app/views"

UPDATE

<%= notice %>

All Topics

<%= render 'topics_list'%>

    <% @topics.each do |topic| %>

        <%= link_to 'Show', topic %>
        <%= link_to 'Edit', edit_topic_path(topic) %>
        <%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %>

    <% end %>

<%= link_to 'New Topic', new_topic_path %>

Code where I render partial
Comment: can you share code from where you are trying to render `topics/_topics_list`
Comment: Yes,sure, updated
Answer: Try changing

<%= notice %>

All Topics

<%= render 'topics_list'%>

to

<%= notice %>

All Topics

<%= render 'topics/topics_list' %>

Also, a good idea will be to always pass local variables to partials instead of using global variables, that way you have an absolute control over values in partials.
<%= render 'topics/topics_list', topics: @topics %>
and then in partial use

    Name
    Description

  <% topics.each do |topic| %>

      .....
      .....

  <% end %>

Answer: Your partial name is _topics_list.form.html.erb. To render this, you need to call render 'topics_list.form', not render 'topics_list'.

Missing Partial for render in rails


asp.net core 1.0 mvc. Get raw content from Request.Body

Question: I am trying to get the raw content of Request.Body in asp.net core 1.0 and I was wondering what the proper way of getting the entire body as a byte[] is. If you have any experience with similar situation and know the "proper" way of doing it, please share.
Answer: Request.Body is a Stream. The stream has the Read method that takes a buffer which is a byte array you can read the data into. Since you may not know the size of the stream and even not all the content can be available you need to do this in the loop until you read all the data from the stream - this stackoverflow answer shows how to do that (if you don't want to block your thread could use ReadAsync). Alternatively - if you would like to read content to a String you could use the StreamReader class.
Answer: I used this code...
using (var requestBodyStream = new MemoryStream())
{
    var body = request.Body;
    await request.Body.CopyToAsync(requestBodyStream);
    requestBodyStream.Seek(0, SeekOrigin.Begin);
    requestPayload.Body = await new StreamReader(requestBodyStream).ReadToEndAsync();
}


What is this foil-backed bitumen in my garden. Asbestos risk?

Question: I am clearing some old paving slabs which have been overgrown and covered with soil.  I keep coming across patches of thin (<1mm) black material, looks like bitumen, with some kind of foil backing.  It's possible they were stuck to the paving slabs (60cm square smooth concrete slabs) at some point, but if so they have delaminated. I also keep finding bits of broken horticultural glass in the same area which may or may not be related.
Any ideas what this might have been?  My concern is whether it could be an ACM.  Obviously testing is the way to be sure.  But having some idea what it could be will help in working out where else I might find it.
Comment: ACM = Asbestos Containing Material, I guess. Anyway, While asbestos is certainly a possibility, it certainly looks like bog-standard roofing felt with aluminum flashing tape. Common when re-roofing and cleanup is not done throughly.Or Aluminium, depending...
Comment: What is an ACM?
Comment: I had a roof put on 15 years ago and still find nails and bits of roofing in the soil.
Answer: It tested negative for asbestos, though the surveyor (in to check out the house) did recommend testing as it was reinforced with some kind of fibre so potentially asbestos.  I've dug up several large sections so I think Ecnerwal was right - old shed roofing.
Comment: Thanks for coming back to let us know the result. Please be sure to give yourself a check mark so everyone knows this question has an acceptable answer.


Use MySQL to Find Duplicates and Display on One Line

Question: I'd like to use MySQL to find duplicates and then display those items as one, combined record. For example, I have two columns: Name and Fruit. A sampling of records might look like this:
Joe - Peaches
Faye - Bananas
Joe - Starfruit
Sam - Apples
I want to display this data as:
Joe - Peaches, Starfruit
Faye - Bananas
Sam - Apples
Is that possible? Could you help me with the MySQL query to start? I'm using VB.NET for my application. Thank you.
Answer: Use GROUP_CONCAT for that.
SELECT personName, GROUP_CONCAT(fruitName) fruitList
FROM tableName
GROUP BY personName

Answer: You'll want to use group_concat here.
SELECT name, group_concat(fruit)
FROM table
GROUP BY name


How to ask a user which factors are most important to them when calculating weights in a model?

Question: I'm creating an index related to "walkability". By walkability I mean:

Length of sidewalk available
User perception rating on various measures of performance
Many other factors

Some users may not care if there are only dirt trails and no sidewalks on a path while other users in a wheelchair can only take the route if there is 100% sidewalks so this metric would be more the most important.
What are some methods for changing the weights assigned to each factor based on user input?
Comment: Welcome to UX SE @Pramesh - the questions and answers here are focused around user experience.  If you are looking for a way to implement weights in an algorithm then that is an implementation question of multiplying each factor by a percentage and belongs on another forum.
Comment: I've edited the question to be more UX focused and hope you find the answer you're looking for.
Comment: Ideally, use https://en.wikipedia.org/wiki/Choice_modelling . Ask user to choose between scenarios, calculate weights after several choices. Would need R or similar
Comment: [This question](http://ux.stackexchange.com/q/82466/21857) might provide some insight. It's about letting users manipulate distinct controls that are factored together in the end to reach a total of 100%. The same model would allow you to infer a hierarchy of preferences.
Answer: According to User Centered Design, you should ask yourself what are the users' goals.
You gave a very good example of a person in a wheelchair. I would try to find out what are those goals, and let the users filter by them directly. This would spare users having to consider every factor independently, and save a lot of mental work (a.k.a. Don't Make Me Think!).
Consider the following examples:

download bmml source – Wireframes created with Balsamiq Mockups
Answer: This can be as simple or as rigorous as you want it to be. I would start by card sorting and come up with as many items as can be thought of.

width of sidewalk
is it in good repair?
can one walk with high heals, push a stroller, can kids use their scooter
garbage
slope (how steep is it going on hills)
dogs
crime
smell (garbage, sewage, wonderful flowers)
flowers and greenery
scenic views

Come up with EVERYTHING you can think of. Ask people. Get "semantic answers."

What we love about the semantic scale is the absence of any prejudgement about the topic in question. In contrast to the Likert, you do not have to take a position on the question to gain an agreement level, you simply ask the respondent for their response without any pre-judgement compared to two different value extremes.

Then, next step, start asking people and find out how relevant the questions are in order to winnow down and identify the most important questions. Maybe only 5 items are necessary; maybe much more; maybe the questions will change based on location (city versus rural) or whatever.
Get these items down. Then start seeing how people rate things and decide between point/star systems or Likert scales: for instance

I believe this walking down this side walk is very safe (from crime)
Strongly agree / agree / don't know / disagree / strongly disagree

or

When walking down this sidewalk I feel
SAFE  [ ]  [ ]  [ ]  [ ]  [ ]  [ ]  [ ]  [ ]  [ ]  [ ]  FEARFUL
Comment: Hi, thanks for your prompt reply. I really appreciate that. I know which factors have to be considered. But the problem is how to include each factor in one index? How to assign weights to the different factors as some may be important than others?
Comment: Could you come up with examples?  You mean clean streets v width of sidewalk?
Answer: Only show users something they can easily relate to
Think about the scenario of a user wanting to delete a file on their computer.  You could show them all the 1's and 0's along with a key of which bits are most or least important on the disk while letting them select the beginning sector and ending sector to erase.
For most people this would be information overload which is why simply showing a recycle bin is a great abstraction.  Users quickly learn that dragging a file to the recycle bin makes it go away leaving more free space for other files.
You should also try and abstract away as much information as you can about walkability.  People can relate to sidewalks, dirt trails, gravel roads, etc. so maybe you can simply tell them how much of each is between the start and end points allowing them to tweak the thresholds like so...

By allowing a user to set certain criteria to "none" your algorithm can adjust accordingly to only show results that line up to what is important to the user.
Answer: Looking at the way you've posed this bit of the question...

Some users may not care if there are only dirt trails and no sidewalks
  on a path while other users in a wheelchair can only take the route if
  there is 100% sidewalks so this metric would be more the most
  important.

...I get the impression that what you need isn't so much a way for users to see what everybody in the world thinks about the "walk-ability" (traverse-ability?) of a route, but a way for them to see what people who understand their situation think about the walkability.
After all, somebody on crutches or with a walking frame is very likely to have quite a different idea of walkability to somebody on a mobility scooter, somebody who has balance issues and needs to stop often or somebody able-bodied but who has to use a stoma-bag when they're out and about (so may need to stop and deal with it with very short notice).  Their concerns are just different.
So how about we turn the question on it's side and look at it from that direction instead, and look at a way to match user concerns and then aggregate a walkability score only from closely matching people.
To that end, a user would be able to specify what their needs are. Being able to specify what their concerns are (not necessarily specific - just "can't be too far from plumbing", "need to sit often", "I move quite slowly", etc...) and see comments and an aggregate "walkability" score from people who closely match themselves...
It'd be worth having the ability to fill in specific details as well, but social proof like this works best when the user knows that the people who's opinions they're seeing have concerns that are close to their own.


Filebeat 7.3.0 not parsing multiline json

Question: I started with ELK 7.3.0 for SIEM feature. I now need to integrate Cloudflare logs which is in JSON format. I'm pretty sure that filebeat can do that.
I have installed filebeat rpm package on my CentOS 7 Server
What I have done so far...
Elastic port changed to : 1300
Logstash port changed to: 2300
Kibana port changed to: 3300
filebeat.yml as follows
filebeat.config.inputs:
   enabled: true
   path: configs/*.yml
   reload.enabled: true
   reload.period: 10s

setup.kibana:
   host: "10.139.111.216:3300"

output.elasticsearch:
   hosts: ["10.139.111.216:1300"]

I have placed my config in /etc/filebeat/modules.d/cloudflare-FW.conf directory as this will reload if any config changes made as I have mentioned in filebeat.yml
cloudflare-FW.conf
filebeat.inputs:
- type: log
  enabled: true
  paths:
  - /var/crons/logs/*.json
  multiline.pattern: '^{'
  multiline.negate: true
  multiline.match:  after

processors:
- decode_json_fields:
 fields: ['message']
 target: json

output.elasticsearch:
  hosts: ["10.136.111.216:1300"]
  index: "cloudflare-FW-%{+yyyy.MM.dd}"
  setup.template.enabled: true
  setup.template.name: "cloudflare-FW"
  setup.template.pattern: "cloudflare-FW-*"

This is my target json file to parse
{
  "ray_id": "501dxxxxxxxx0ce1b",
  "kind": "firewall",
  "source": "bic",
  "action": "drop",
  "rule_id": "bic",
  "ip": "161.00.6.8",
  "ip_class": "noRecord",
  "country": "GB",
  "colo": "LHR",
  "host": "site.com",
  "method": "POST",
  "proto": "HTTP/1.1",
  "scheme": "https",
  "ua": "Jakarta Commons-HttpClient/3.1",
  "uri": "/nxxxxxxx/senxxxxxxxxail.php",
  "matches": [
    {
      "rule_id": "bic",
      "source": "bic",
      "action": "drop"
    }
  ],
  "occurred_at": "2019-08-06T03:28:57Z"
},
{
  "ray_id": "501dxxxxxxxxxx6ce27",
  "kind": "firewall",
  "source": "bic",
  "action": "drop",
  "rule_id": "bic",
  "ip": "220.127.116.11",
  "ip_class": "noRecord",
  "country": "GB",
  "colo": "LHR",
  "host": "site.com",
  "method": "POST",
  "proto": "HTTP/1.1",
  "scheme": "https",
  "ua": "Jakarta Commons-HttpClient/3.1",
  "uri": "/nxxxxxxx/senxxxxxxxxail.php",
  "matches": [
    {
      "rule_id": "bic",
      "source": "bic",
      "action": "drop"
    }
  ],
  "occurred_at": "2019-08-06T03:02:52Z"
}

When I run filebeat -e it should create a index named cloudflare-FW-%{+yyyy.MM.dd} and should ingest the data from the json file to the index. In the end JSON key should be the fields which can be queried on.
But it is not happening. Any help is greatly appreciated. Keep in mind this is filebeat 7.3.0
Thanks
Comment: have you had any success with my answer?
Comment: Sorry for not reverting for so long. I have noted the mistake you highlighted in the config file; Thanks for that

But I solved my problem by reading the logs from http response rather than from file using logstash http input plugin and using split logstash filter to split the json subkeys; Its working good.
Answer:
I have placed my config in /etc/filebeat/modules.d/cloudflare-FW.conf directory

In your filebeat.yml you specified a totally different path:
filebeat.config.inputs:
  enabled: true
  path: "configs/*.yml" <--
  reload.enabled: true
  reload.period: 10s

Seems to me like your configuration is not even loaded because its in the wrong location.
Also notice the file extension you specified (*.yml).


Are there 3D effects on Xubuntu? (hardware-accelerated graphics)

Question: Does the default XFCE's window manager offer any 3D eye candy? If it does, how do I enable it after installing the relevant drivers?
I want to install Nouveau's experimental 3D driver (which worked great for me under Ubuntu), libgl1-mesa-dri-experimental, in Xubuntu. But I don't know if just installing it will enable any 3D effects.
Comment: The reason you *don't* see 3D effects is because [XFCE is designed to be light weight in both footprint and system load](http://www.xfce.org/).
Answer: Xubuntu doesn't come with Compiz so no 3D effects out of the box, but turning on the Composite feature gives you many effects like transparency and shadows plus it allows you to use 3D programs like Docky...
To enable go to:  Applications -> Settings -> XFCE Settings Manager
Then run:  Window Manager Tweaks - Compositor (tab) and Enable
...and from there play with the settings and fancify your desktop :)
Comment: Does installing the necessary drivers enable them?
Comment: @Oxwivi no, they are CPU based if you don't have the right drivers.
Comment: @RolandTaylor, that's what I'm asking, if I've the right drivers, will it be automagically enabled.
Comment: I found that having the necessary driver will enable compositing. Please add that to your answer so I may choose it.
Answer: Xfce by design leaves out much of the eye candy of other systems. There aren't even fancy animations. The most you can get is 2D accelerated compositing if your driver supports it (most do), unless you are willing to install other software.
You have to enable the compositing feature in XFCE's settings manager, and to my memory it will use hardware acceleration automatically. (You may need to do this manually but I am on unity so I cannot test it).
Answer: In xubuntu 12.10 go to:
Settings Manager -> Window Manager Tweaks and navigate to the last pane "Compositor".
Check the "Enable display compositing"
I know, its not of direct use for a one year old question - but I got stuck in 12.10 and landed on this site. Consider this an update of TenPlus1's answer.
Answer: AFAIK only KWin and compiz offer opengl/3d based compositing. xfwm4 (i.e. the default window manager of xfce) offers fancy stuffs such as transparency/shadows only. And as far as your drivers question goes installing necessary drivers makes your hardware ready, you still need to enable what is in offer i.e. What @TenPlus suggests in context with xfwm4 to enjoy. You can look into cairo-compmgr for some additional compositing as well which can easily run in top of xfwm4.
Comment: You are forgetting Mutter, but good answer.
Answer: It's four years old, but there was "Xubuntu + Compiz = Pretty pretty Xubuntu" at http://xubuntublog.wordpress.com/2007/12/09/xubuntu-compiz-pretty-pretty-xubuntu/
Comment: I would like to avoid Compiz, if possible. I like it's collection of candy, but the less extra software I need to install, the better.


Strategy to find out about user goals after the product is made

Question: I'm a coder, I made a product long back and I just read my first UX book.
I learned about 'user goals'.
I do not assume anymore that my product solves them.

I am unable to make a strategy for going ahead and fixing the entire website so it actually helps its visitors.
How can I setup a survey to honestly learn about user goals/expectations?

The product is non-profit/activism.
Comment: Looks like you first need to know what problem your product is supposed to solve, who your audience is, and then whether or not your users are having issues. Then you can start resolving potential problems, because otherwise it's purely based on your gut feeling. Users won't really tell you what their goal is in the sense that UX'ers create them. You'll have to listen to what they say and then figure out the actual intent behind their words. Do you have any insight in who's using your product and how to reach them?
Comment: I have the problem why I made the product. But realised its may not a popular one. The users have not been using as I expected them. What questions can I ask users? I have little traffic but composing a survey questions seems pretty hard.
Answer: if you have sustantial traffic going into your website/ product you can do a log analysis of usage patterns on your application. The log analysis can give you ideas on the following:

why users visit your website
which features/ buttons that your website users click most often
where users drop off, this will show you where the gap in solving the problem is

If the traffic statistics are not sustantial to give you an idea of the above, you can talk to other people who had the same problem as you that led you to create the web application. The important points to take note when talking to people with the same problem would be:

what are the main causes that led to the same problem you and other users faced
how other users mitigate the issues currently without the use of the application

Hope these points help!
Answer: 01. Fix the objective

Understand the motives behind creating the product and what specific problems you tried to solve through the product

02. User research

Understand the user base again. Cover user behavior, benchmarking and motivation.

03. Conduct a usability study

Since the product is already released you can opt for this. This will help you to understand the current user behavior, what is redundant and what is useful, flaws inflows, IA etc.

04.Prepare a prototype and test

Go for an early prototype and test it rapidly


How to format embedded if statements in javascript

Question: What would be the best way to format this code?
It looks a bit messy to me, in regard to indentation, etc.
    if (typeof _srwc != 'undefined') {
        for (var i=0; i < _srwc.length; i++){
             var currentArg = _srwc[i];;
              if (typeof window[currentArg[0]] == 'function') {
                 window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
                 } else {
                 console.log('The Setter method: "' + currentArg[0] + '" is undefined');
                 }
        }
    }

Comment: http://codereview.stackexchange.com/
Answer: Try indenting the code inside the if, like this:
    if (typeof _srwc != 'undefined') {
        for (var i = 0; i < _srwc.length; i++) {
            var currentArg = _srwc[i];;
            if (typeof window[currentArg[0]] == 'function') {
                window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
            } else {
                console.log('The Setter method: "' + currentArg[0] + '" is undefined');
            }
        }
    }

Also, JSBeautifier is very useful for indenting JavaScript.
Answer: You can also use:
if (typeof _srwc != 'undefined')
{
    for (var i = 0; i < _srwc.length; i++)
    {
        var currentArg = _srwc[i];
        if (typeof window[currentArg[0]] == 'function')
        {
            window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
        }
        else
        {
            console.log('The Setter method: "' + currentArg[0] + '" is undefined');
        }
    }
}

That way all opening brackets are on the same vertical line as the closing ones and you can easily track which closing bracket is the one for a selected opening one (the first one below it on the same spacing distance). It's easier to trask the code that way if you're not using an IDE that is coloring the coresponding brackets.
Answer: When coding any language, normally entering a new block would cause indentation and exiting the same block does the opposite.  (JS indentation should be 4 spaces)
ie
function xyz(){
    alert("xyz");
}

and
function abc(){
    if(true){
        alert("true");
    }else{
        alert("false");
    }
    alert("abc");
}

..but like me if you get lazy and stop indenting using a tool like JSBeautifier whcih are available in most languages online just give it a search.
Comment: Note: Code blocks are {}


Control PC from Android phone?

Question: I always wanted to control my Linux PC via my smartphone, and found a way to do it. It's called CRC Remote. I could have several profiles with buttons, and on the press of one it would run the configured key press sequence. However, as I recently reinstalled Linux, I didn't have the program on my PC anymore. I then visited the homepage, just to find out that the page doesn't exist anymore. And I can't find the app in the Play Store. So I couldn't use it anymore. Are there any good alternatives that can send keystrokes to the PC? Because I was using it with many programs and didn't have to memorize all of the keyboard shortcuts.
Comment: I use connectbot on my phone to ssh into my Ubuntu boxes. https://play.google.com/store/apps/details?id=org.connectbot&hl=en_US≷=US
Answer: KDE Connect can do a lot of what you ask about. You may want to look into that.

Control PC from Android phone?


data retrieval from database showing error

Question: I am trying to get data from the database and pass it to javascript to show as markers on google maps. When I use the javascript var markers variable, it works fine but when I try to get the database data,pass it to the array, encode it and use it in javascript it creates this unclear error
error);
$coordinates = array(); // Select all the rows in the markers table
$query = "SELECT `locationLatitude`, `locationLongitude`,'ID' FROM `location_tab` ";
$result = $mysqli->query($query) or die('data selection for google map failed: ' . $mysqli->error);
while ($row = mysqli_fetch_array($result)) {
    $latitudes = $row['locationLatitude'];
    $longitudes = $row['locationLongitude'];
    $ID= $row['ID'];
    $coordinates[]= array('id'=>$ID,'lat'=>$latitudes,'lng'=>$longitudes );
    print_r($coordinates);
}
$markerss= json_encode($coordinates);
?>

this is my code
<?php
/* Database connection settings */
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'location_db';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

$coordinates = array();

// Select all the rows in the markers table
$query = "SELECT  `locationLatitude`, `locationLongitude`,'ID' FROM
`location_tab` ";
$result = $mysqli->query($query) or die('data selection for google map
failed: ' . $mysqli->error);

while ($row = mysqli_fetch_array($result)) {

    $latitudes = $row['locationLatitude'];
    $longitudes = $row['locationLongitude'];
    $ID= $row['ID'];
    $coordinates[]= array('id'=>$ID,'lat'=>$latitudes,'lng'=>$longitudes );
}
$markerss= json_encode($coordinates);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Add Google Map with multiple markers to your website</title>

Answer: You have a string 'ID' without alias this produce an error for invalid index  in $rows array (could be you trying to select the column ID but wrongly you add  single quotes then change  SELECT locationLatitude, locationLongitude, 'ID' AS ID
with SELECT locationLatitude, locationLongitude,  ID   )
<?php

$coordinates = array();
// Select all the rows in the markers table
$query = "SELECT locationLatitude, locationLongitude, 'ID' AS ID FROM location_tab ";
$result = $mysqli->query($query) or die('data selection for google map failed: ' . $mysqli->error);
while ($row = mysqli_fetch_array($result)) {
    $latitudes = $row['locationLatitude'];
    $longitudes = $row['locationLongitude'];
    $ID= $row['ID'];
    $coordinates[]= array('id'=>$ID,'lat'=>$latitudes,'lng'=>$longitudes );
    print_r($coordinates);
}
$markerss= json_encode($coordinates);
?>

and in your javascript  use
        var markerss= <?= $markerss; . ';\n' ?>

Comment: hello scaisEdge I tried your code snippet but the error is still the same. Any suggestions?
Comment: error); $coordinates = array(); // Select all the rows in the markers table $query = "SELECT locationLatitude, locationLongitude, 'ID' AS ID FROM location_tab "; $result = $mysqli->query($query) or die('data selection for google map failed: ' . $mysqli->error); while ($row = mysqli_fetch_array($result)) { $latitudes = $row['locationLatitude']; $longitudes = $row['locationLongitude']; $ID= $row['ID']; $coordinates[]= array('id'=>$ID,'lat'=>$latitudes,'lng'=>$longitudes ); print_r($coordinates); } $markerss= json_encode($coordinates); ?>
Answer: Replace following code from.
//google maps data from database
<?php
        echo "var markerss=$markerss;\n";
    ?>

To
//google maps data from database
var markerss = <?php echo $markerss; ?>


AttributeError: 'list' object has no attribute 'dist'

Question: I have been working on an assignment for one of my introductory classes. I am almost done with my code and but I keep getting "AttributeError: 'tuple' object has no attribute 'dist'." I understand that the problem starts from midpt function and that I need to return an instance of the class instead of the tuple; however, I have not been able to do that. Could you please take a look at my code? It would be much appreciated.
'''
import math
class Point(object):

    # The contructor for Point class
    def __init__(self, x = 0, y = 0):
        self.x = float(x)
        self.y = float(y)

    # The getter for x
    @property
    def x(self):
        return self._x
    # The setter for x
    @x.setter
    def x(self, value):
        self._x = value

    # The getter for y
    @property
    def y(self):
        return self._y
    # The setter for y
    @y.setter
    def y(self, value):
        self._y = value

    # Function for getting the distance between two points
    def dist(self, other):
        xVar = (other.x - self.x) ** 2
        yVar = (other.y - self.x) ** 2
        equation = xVar + yVar
        distance = math.sqrt(equation)
        return distance

    # Function for getting the midpoint
    def midpt(self, other):
        xVar = (other.x - self.x) / 2
        yVar = (other.y - self.y) / 2
        midpoint = (xVar,yVar)
        return midpoint

    # Magic function for printing
    def __str__(self):
        return "({},{})".format(self.x, self.y)

##########################################################
# ***DO NOT MODIFY OR REMOVE ANYTHING BELOW THIS POINT!***
# Create some points
p1 = Point()
p2 = Point(3, 0)
p3 = Point(3, 4)
# Display them
print("p1:", p1)
print("p2:", p2)
print("p3:", p3)
# Calculate and display some distances
print("distance from p1 to p2:", p1.dist(p2))
print("distance from p2 to p3:", p2.dist(p3))
print("distance from p1 to p3:", p1.dist(p3))
# Calculate and display some midpoints
print("midpt of p1 and p2:", p1.midpt(p2))
print("midpt of p2 and p3:", p2.midpt(p3))
print("midpt of p1 and p3:", p1.midpt(p3))
# Just a few more things...
p4 = p1.midpt(p3)
print("p4:", p4)
print("distance from p4 to p1:", p4.dist(p1))

Comment: Your very last line is the problem! `p4` is a tuple and it does not have a `dist` method
Comment: Change `midpoint = (xVar,yVar)` to `midpoint = Point(xVar,yVar)` in your `Point.midpt` function.
Answer: You might want to change midpoint = (xVar,yVar) to midpoint = Point(xVar, yVar).
In this way, p4 is a Point (and not a tuple!) instance, and you can call the dist method on it.


installing theme manually

Question: I am using Ubuntu 14.04.  I found a great theme I would really like and downloaded it.  It is in a zip file and I cannot figure out how to install it.
I tried the /usr/shared/themes but it tells me I do not have permission to do this.
Answer: You need to extract it first.
To install globally (i.e. to install it such that it is available for all users, you need to place it in /usr/share/themes.
For this you need root privileges. A simple way to achieve this would be to open nautilus as root and then copy paste the extracted theme folder.
Type Ctrl+Alt+T to open a terminal window.
In the terminal window that opens do:
sudo nautilus

A window will show up. Copy your extracted theme folder and paste it into /usr/share/themes. (Close the window when you're done.)
If you do not have root privileges, copy your extracted theme folder to ~/.themes/ where ~ stands for your home and . makes the folder hidden – simply create one if there isn't any.
After all, you need apps such as Unity Tweak Tool to select the theme.

installing theme manually


How do I redefine a fill attribute in SVG using the set tag? I thought I knew, but

Question: I am working with the standard blank map 6 svg from wikimedia commons. I added a list of languages and I am trying to make it so that when I hover over a language the corresponding countries light up, change colour, or in some way indicate that they are 'selected'. Here is the code I am using.
<set
attributeName="fill"
 from="#E0E0E0"
 to="#FF8888"
begin="tEnglish.mouseover"
end="tEnglish.mouseout"
/>

where tEnglish is the text object that says 'English'. No luck.
Whether with  or  or any other method, I can not get the svg to change an attribute that has been defined. Meaning that if I delete the fill="#E0E0E0" attribute from one of the s, I can get it to work (altho then the default is black instead of grey, which does not fit the style of the website I'm working on), but if the  already contains a fill= attribute, it will not change as directed by the  tag.
I have also tried deleting the fill="#E0E0E0" and defining it in a stylesheet - same problem.
So, is it completely impossible to redefine an attribute of a path once it is declared? Does  only work if the attribute has not been defined elsewhere? Is my idea even possible? I appreciate any help that can be proffered.
I would also welcome any suggestions as to other methods (jquery, javascript) that you might have; although I am not so experienced with any of them I can do some research, any lead is appreciated.
Comment: Does the behavior change if you add `attributeType="CSS"`?
Comment: Is the element with id="tEnglish" in the svg file or is it in another document?
Comment: Could you take a look to my answer ? Was it what you are looking for ? If not, please, let me know.
Answer: It works if you put the set tag inside the element:
<rect
   width="248.57143"
   height="225.71428"
   x="137.14285"
   y="395.21933"
   id="myrect"
   style="fill:#800000;">
    <set
        attributeName="fill"
         to="#008000"
        begin="mouseover"
        end="mouseout"
        />
</rect>

You can also achieve it using simple CSS:
#myrect {
    fill: #800000;
}

#myrect:hover {
    fill: #008000;
}

Example with css: http://fiddle.jshell.net/7dcnZ/2/
Of course, JavaScript is also an option:
$('#myrect').hover(function() {
    $(this).css('fill', '#008000');
},
function() {
    $(this).css('fill', '#800000');
});

Example with JavaScript: http://fiddle.jshell.net/7dcnZ/3/


React js setstate not working in nested axios post

Question: I am trying to access the res.data.id from a nested axios.post call and assign it to 'activeId' variable. I am calling the handleSaveAll() function on a button Click event. When the button is clicked, When I console the 'res.data.Id', its returning the value properly, but when I console the 'activeId', it's returning null, which means the 'res.data.id' cannot be assigned.
I just need to assign the value from 'res.data.id' to 'metricId' so that I can use it somewhere else in another function like save2() function.
Does anyone have a solution? Thanks in advance
const [activeId, setActiveId] = useState(null);

useEffect(() => {}, [activeId]);

const save1 = () => {
      axios.get(api1, getDefaultHeaders())
        .then(() => {
          const data = {item1: item1,};

          axios.post(api2, data, getDefaultHeaders()).then((res) => {
            setActiveId(res.data.id);
            console.log(res.data.id); // result: e.g. 10
          });
      });
};

const save2 = () => {
  console.log(activeId); // result: null
};

const handleSaveAll = () => {
  save1();
  save2();

  console.log(activeId); // result: again its still null
};

return (
  <button type='submit' onClick={handleSaveAll}>Save</button>
);

Comment: `save2()` won't wait for `save1()` to resolve
Comment: setState function is asynchronous. It's not updated straight away. Also, your axios calls are promises, so it takes some time to resolve them.

Put that console.log in your useEffect that you have, and you will see the value of activeId being updated
Comment: Actually If I put it in the useEffect, it wouldn't solve my problem because I need the value of 'activeId' in save2() function, i console it just to confirm that the value is assigned or not. How can I get value of 'res.data.id' from the save1() function and assign it to 'metricId' so that I can use this value inside the save2()?
Comment: so it will be better to understand if you show your complete code ( component )
Comment: It is almost the complete code @DeepKakkar
Comment: Why don't you call `save2()` in the `then` of `axios.post` in `save1()` and by passing a parameter to `save2`? That's how you deal with promises, you do something once it resolves, not before. Or as others have suggested, you'll have to use `async/await`.
Answer: This part of code run sync
const handleSaveAll = () => {
  save1();
  save2();

  console.log(activeId); // result: again its still null
};

but there you run async
axios.get(api1, getDefaultHeaders())
        .then(() => {

You can refactor your code to async/await like this:
const save1 = async () => {
      const response = await axios.get(api1, getDefaultHeaders());
      const response2 = await axios.post(api2, { item1: response.data.item1 }, getDefaultHeaders());
      return response2.data.id;
};

const save2 = (activeId) => {
  console.log(activeId); // result: null
};

const handleSaveAll = async () => {
  const activeId = await save1();
  save2(activeId);
  setActiveId(activeId);
  console.log(activeId); // result: again its still null
};

or to chain of promises, like this:

const save2 = (activeId) => {
  console.log(activeId); // result: null
};

const save1 = () => {
  return axios.get(api1, getDefaultHeaders())
    .then(({ data }) => {
      const data = {item1: item1,};
      return axios.post(api2, {item1: data.item1}, getDefaultHeaders())
    })
    .then((res) => res.data.id);
};

const handleSaveAll = () => {
  save1()
    .then((res) => {
      setActiveId(res.data.id);
      console.log(res.data.id); // result: e.g. 10
      return res.data.id;
    })
    .then(save2);
};


Are big-list questions inappropriate for this forum?

Question: Before using the Psychology and Neuroscience stackexchange I was more familiar with the MathOverflow which is a more mature member of the stackexchange community. This platform is used by professional mathematicians that practice both pure and applied mathematics. Furthermore, on the MathOverflow it isn't uncommon and it isn't considered unproductive to ask questions which involve a big list.
Consider the following examples:

Big list of repositories of mathematical preprints and postprints
Proofs without words

Now, I recently asked a specific question on the existence of good neuroscience research blogs. I gave concrete examples in the case of AI to clarify what I meant, distill being an example. After a couple days without an answer I decided to share the question with a neuroscientist I have communicated with in the past, Konrad Kording.
Dr. Kording, runs a well-known neuroscience lab and isn't merely providing a list of opinions. If you check each of the blogs in his answer they are all neuroscience research blogs. I must add that the first link to https://bitsandbrains.io/ fits the question description in particular.
Consider these posts taken from bitsandbrains:

Some thoughts on building interdisciplinary biological/data science teams
Bilateral Homology
Connectome Coding: Discovering the Missing Link between Genotypes and Phenotypes

This leads me to the following questions:

Before downvoting the question, was any detailed consideration given to the answer of Dr. Kording?
Is my question, which I discussed with other neuroscientists, imprecise?
Comment: Thanks. You have to realize our site is haunted by poor Qs and broad questions are one of the culprits. The Q hasn't been close-voted though so I guess there's no big deal here anyway. Qs are downvoted en mass across the SE network, including mine when I enter a new site for the first time. Every site is different in many ways. Having said that, your Q seems well researched and I would reckon the Q to be valid (I +1d, for what it's worth).
Comment: @AliceD I am trying to encourage some of my neuroscientist friends to join. https://psychology.stackexchange.com/questions/13232/how-can-higher-concepts-get-unrolled-with-upward-and-feedback-connections-differ?stw=2 was answered by a colleague, Christian Jarvers, after I shared it with him and a few other neuroscientists.
Comment: I'd say that I'm more concerned that neuroscientists I share the site with end up being discouraged and abandon this SE site.
Comment: I think it is essential to keep 'list' questions _"Not overly broad"_. You do exactly that by being quite detailed in the type of blogs you are interested in. Good question! Welcome to this stack!
Comment: @AidanRocke I think a better way to attract people and not have them be discouraged is to ask "research level" questions that the people you are talking to would be excited to answer instead of showing them the weakest side of the SE system.
Comment: Agreed with @AliceD.  An example on this site is: https://psychology.stackexchange.com/q/9149/7001.  I would generally recommend avoiding subjective criteria such as "good", "interesting", or "important" (though the example I gave uses "interesting"); specify more objective criteria in the question content instead.
Comment: Thank you Steven. I appreciate the efficient process for addressing this issue.
Comment: @StevenJeuris I like your answer on the other meta question, but the one answer on the question in question does not explain why/how, is short, and doesn't really share experiences and I find it hard to believe that the question will attract good answers by the standards you laid out.
Comment: @AliceD I have added an addendum to my answer in order to address the points raised by StrongBad, Bryan Krause and yourself.
Answer: Like StrongBad mentioned in a comment on the original question, questions where any answer is correct are not a good fit for SE.
In fact, in the help under "Don't Ask" the very first item is:

To prevent your question from being flagged and possibly removed, avoid asking subjective questions where …
every answer is equally valid: "What's your favorite ______?"

Different sites have different levels of permissiveness of certain questions that don't follow this rule, but that's probably where the downvotes come from.
Answer: As I said in my comment explaining my down vote and VTC, while the question is clear and limited in scope, I think every answer will be equally correct. The example I gave was consider the following two answers

Alice's blog cover neurotransmitters in depth. I really like her post on GABA and anxiety

and

Bob's blog covers deep learning at an introductory level. I really like his post on using PyTorch for object identification.

I think both would be valid answers, but how do we judge which is "correct". This is a clear cut example of a don't ask question.
Now of course we can make exceptions, but I am always a little hesitant about requests for exceptions from relatively new users. I also think justification based on practices at MO are not good since they are historically different from the rest of the SE system. Of course other sites in the SE system allow big list questions. In fact, I recently asked about creating a big list question on a site I moderate.
In summary. I think big list type questions should be the exception and not the rule. We should make a case-by-case determination for each request and we should attempt to come to a consensus regarding what the answers will look like prior to asking the question. If we choose to make a big list question, I think it should be made community wiki and the first comment shold link back to a meta discussion.
Comment: I would add to this that in other places like StrongBad is describing, the 'big list questions' tend to arise from related common questions where the community decides consolidation into a single resource makes sense, rather than generated "bottom up," and tend to be community wikis. There are also exceptions to the rules in places like Stats.SE with https://stats.stackexchange.com/questions/423/what-is-your-favorite-data-analysis-cartoon and https://stats.stackexchange.com/questions/1337/statistics-jokes
Answer: To be fair, I understand where users like Bryan Krause and StrongBad are coming from. Unlike the MathOverflow or the Theoretical Computer Science stackexchange the average quality of most questions on this site isn't research-level. I am hopeful this will change and I am actively trying to convince friends of mine that are neuroscientists and cognitive scientists to contribute here. However, I think we should avoid categorically downvoting 'big-list' questions because they can be useful if worded carefully.
I worded my question carefully. The term 'best' and 'favorite' were consciously avoided and I laid out a specific set of criteria to qualify 'good research blog'. It has to cover:

methods for experimental, computational and theoretical neuroscience
comprehensive reviews of basic neuroscience research

To provide a lower-bound on the quality I expect I gave concrete examples. Distill being the ideal I had in mind.
Finally, I must note that Memming Park who runs a lab at Stony Brook has previously made a case for the value of such questions. (He uses an example from the MathOverflow to back his point.)
Addendum:
From what I can gather from AliceD, Bryan Krause and StrongBad I understand that there is a fear that on this forum a big list type question would invite spammy answers. I must clarify that from the beginning I wanted to know whether an online journal like distill existed for neuroscience research. I passed this question to both Konrad Kording and Adam Marblestone who both have a very broad understanding of neuroscience research.
Now, to avoid the 'big list' conundrum I decided to add the reference request tag. I am indeed looking for a particular kind of reference and what you can infer from Konrad's answer is that an online journal like distill doesn't exist for neuroscience research.
I think this should allow me to accept Konrad's answer and also avoids the risk of spammy answers.
Comment: If you are looking for a journal like Distill, that doesn't seem like a big list question, because I just don't think there are going to be that many. That is a very different question, however, from what you have asked and if you want to ask that, you should point out the features of Distill you want to see.
Comment: Also note, I am not trying to attack you or discourage you or other to participate here. If the community decides that your question, or big lists questions in general, are on topic, great. Regardless of the outcome, I hope you will continue to participate in the community and reach out to colleagues to try and grow the community.
Comment: _"Now, to avoid the 'big list' conundrum I decided to add the reference request tag."_ I feel this is a misuse of the [tag:reference-request]. From the description: _"It should NOT be applied merely because answers with references are desired. "_
Comment: Ok. In this case I will remove it.


How do I build OpenCV's single module (e.g. legacy) for my development in Ubuntu?

Question: I revised some source code of OpenCV's legacy module. My project is coded based on the new legacy module and I want to debugging it. One way that I can think out is using my revised legacy source code to replace the original legacy module, then compile and reinstall the whole OpenCV. I think this way is too waste of time and other modules(e.g. imgproc, highgui, etc) haven't any change and don't need to be reinstalled. I think there must have an easier way to solve it.
My developing environment is VIM && GDB && opencv 2.4.13. I am a green-hand of linux-opencv. How do I build OpenCV's single module in Ubuntu? If I want keep the original legacy module and the new legacy module in case of other usage, how should I do?
Comment: i don't think that's feasible to do. There are too much dependencies and you will have to figure out each one of them to do it
Comment: @ArpitSolanki  Thanks for your answer. You mean I must reinstall the whole opencv project even I did just a little revision.
Comment: i am not 100% sure but i pretty much think that it will be very tough to manage depecdencies
Comment: I doubt your assumption, suppose you built `highgui`, `imgproc` modules, the include file [`cv2.hpp`](https://github.com/opencv/opencv/blob/master/include/opencv2/opencv.hpp) would have the include paths of those modules, and again when you build `core` module, then it would override the `cv2.hpp`. You can Do what you want to, But it won't be smooth. You may manually need to edit some include files and copy `.so` files as well.
Comment: @ZdaR All right. I think maybe I have some misunderstanding in how opencv build && run. I'll install the different version for different opencv sources and change the environmental variables for different application. I think it is the best way.:)
Answer: There is a way to actually build a single module without building the entire source from the beginning. I guess you would have followed this procedures to install OpenCV in your machine OpenCV Installation in Linux.
After the modifications in OpenCV's legacy module, you can build just that module by using the commands.
# Go to the build directory. If you followed the tutorial I shared then it is the release folder
cd release

# And build only the module you want to (For example, legacy model as in your case)
make opencv_legacy
sudo make install

Comment: Am I need to use the 'sudo make install' to install the original OpenCV to my pc? Or I just need to execute directly the make command and replace legacy source code, then run 'make opencv_legacy&&sudo make install'?
Comment: replace the source code and then build using the command 'make opencv_legacy&&sudo make install'


Are Ord and Enum sometimes incompatible in Haskell?

Question: Could Ord and Enum be one typeclass? Why doesn't Enum require Eq?
Answer: There are things that can be enumerated without an order. For example:
data Color = Red | Green | Blue deriving Enum

Which order should colors have? There is no inherent order, even though the colors can be enuemrated.
There are also things that can be enumerated but not compared for equality. Floats, for example, have a NaN value that isn't equal to anything. Floats can be enumerated, however.
Comment: Why isn't the ordering simply the sequential order? So `compare Red Green` is `LT`, `compare Green Blue` is `LT`.
Comment: @TianxiangXiong, it could be, but in a given use case it doesn't necessarily make sense for it to be.
Answer: Enum represents types that can be mapped to/from integers. This doesn't say anything about how those types should be sorted, merely that you can represent them with integers.
Ord represents ordered types. This is different than types that can be mapped to integers. For example, you can't map arbitrary-precision floating point values to integers, but you can order them. And while you technically could try and map Floats to integers, nobody in their right mind would do so.
As for Eq, Ord requires this because it doesn't make sense to have a totally ordered datatype that doesn't support equality. However, Enum has no need for Eq. Since Enum doesn't provide any ordering guarantees, it doesn't provide equality guarantees either.
Comment: @L01man: If you want that, just use `sortBy (comparing fromEnum)`.
Comment: It's not quite true that it wouldn't make sense to have `Ord` without `Eq`, take floating point numbers for example.
Comment: Enum represents types that can be mapped to/from integers. Integers can be tested for equality. Is there an instance of `Enum` which doesn't want `Eq`?
Comment: @TiloWiklund well if you're saying that floating point numbers shouldn't have an `Eq` instance, then they shouldn't have an `Ord` instance, either. They should instead only have `Min` and `Max` [Semigroup](http://hackage.haskell.org/packages/archive/semigroups/latest/doc/html/Data-Semigroup.html#Semigroup) instances.
Comment: @L01man: I don't know, but if `Enum` depended on `Ord` that would imply it relies upon the specific implementation of `Ord`, and yet your datatype may want to sort differently than the `Enum`-mapped integers do.
Comment: @KevinBallard: You can still define your own instance of `Ord`. What about `Eq` and `Enum`?
Comment: @L01man: What about it? Why would `Enum` necessarily require `Eq`?
Comment: @KevinBallard Good point, had a brain fart and didn't think of antireflexivity :)
Comment: @KevinBallard: If things can be enumerated, they have their own place in the enumeration, thus they can be compared for equality with their place as the criteria... Maybe.
Answer: Though I'm not sure to what extent this is generally accepted, but I've always viewed Enum as a typeclass describing types with canonical total preorders (i.e. there might be a loop) such that the sequence of terms "between" any pair of terms is finite (witnessed by enumFromTo).
Ord, on the other hand, describes types with canonical total orders, without any requirement that the set of elements between any pair of terms be finite.


PHP Slim Framework Create Controller

Question: I am creating an API using the Slim framework.  Currently I use a single file to create the route and pass a closure to it:
$app->get('/', function($req, $resp){
//Code...
})

But I realise that my file has grown rapidly.  What I want to do is use controllers instead, so I will have a controller class and just pass the instance/static methods to the route, like below
class HomeController
{
   public static function index($req, $resp){}
}

and then pass the function to the route
$app->get('/', HomeController::index);

I tried this, but it does not work, and I wonder if there is a way I can use it to manage my files.
Answer: Turn the controller into a functor:
class HomeController
{
    public function __invoke($req, $resp) {}
}

and then route like this:
$app->get('/', HomeController::class);

For reference, see

http://www.slimframework.com/docs/objects/router.html#how-to-create-routes
http://www.slimframework.com/docs/objects/router.html#route-callbacks.
Comment: Which folder is used for add controller ?
Answer: PHP 5.6
Slim 2.6.2
require 'vendor/autoload.php';

class HelloController {
    public static function index()  {
        global $app;

        echo "
";
        var_dump($app->request);
        echo "
";
    }
}

$app = new \Slim\Slim();
$app->get('/', 'HelloController::index');
$app->run();

Update: PHP 5.6 Slim 3.0.0

require 'vendor/autoload.php';

class HelloController {
    public static function hello(\Slim\Http\Request $req, \Slim\Http\Response $response, $args)  {
        echo "
";
        var_dump($args);
        echo "
";
    }
}

$app = new \Slim\App();
$app->get('/hello/{name}', 'HelloController::hello');
$app->run();

The problem with class based routing in Slim 3.0 is access to $this/$app. I think you will need to use global $app to access it.
In my pet project I use route groups with require_once. Something like
$app->group('/dashboard', function () {
    $this->group('/auctions', function () use ($app){
        require_once('routes/dashboard/auctions.php');
    });
    $this->group('/rss', function () {
        require_once('routes/dashboard/rss.php');
    });
    $this->group('/settings', function () {
        require_once('routes/dashboard/settings.php');
    });
});

Looks not as beauty as could be with pure classes but works like expected with all features accessible without additional coding.
Comment: If you subclass slim\application and include the route file inside there then you can use $this consistently throughout the route configuration. I added an example here http://stackoverflow.com/questions/41981048/how-can-i-create-middleware-on-slim-framework-3/42022544#42022544

Also, it would be possible to have a route configuration class that takes the Application as a constructor dependency
Comment: @Roman when you use proper namespace and using composer, you do not need to call require() on your own because autoload.php will do it for you.
Answer: Smooth & short way to use a controller as an object (not a static way)

in index.php

namespace MyApp;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require __DIR__ . '/../vendor/autoload.php';

$app->get('/myroute', [new Controller\MyClass, 'get']); // <=== that is pretty short  and neat
$app->post('/myroute', [new Controller\MyClass, 'post']);
$app->map(['GET', 'POST'], '/myotherrout', [new Controller\MyOtherClass, 'run']);

in Controller/MyClass :

namespace MyApp\Controller;

class MyClass{

    public function __construct(){
       //some code
    }

    public function get(\Slim\Http\Request $request, \Slim\Http\Response $response, $args = []) {
       //some super foobar code
    }

    public function post(\Slim\Http\Request $request, \Slim\Http\Response $response, $args = []) {
       //some other code
    }

The Controller\MyClass is resolved through the use of PSR autoload

in Controller/MyOtherClass :

namespace MyApp\Controller;

class MyOtherClass{

    public function __construct(){
       //some code
    }

    public function run(\Slim\Http\Request $request, \Slim\Http\Response $response, $args = []) {
       //some amazing foobar code
    }

Comment: Very nice indeed! Thanks! How would you inject a service directly into the controller without going through the container using this?
Comment: While this works, controller instance creation should be done inside dependency container registration
Answer: Here's an example:
Controller
<?php

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;

/**
 * @property LoggerInterface $logger;
 */
class Controller
{
    /**
     * @var LoggerInterface
     */
    protected $logger

    /**
     * @param LoggerInterface $logger
     */
    public function __construct($logger)
    {
        $this->logger = $logger;
    }

    public function action(ServerRequestInterface $request, ResponseInterface $response, $args=[])
    {
        $this->logger->info((string)$request->getUri());
        /* some actions */
        return $response;
    }
}

Application
<?php

use Slim\App;
use Slim\Container;
use Psr\Container\ContainerInterface;

$autoloader = require(__DIR__.'/vendor/autoload.php');

$container = new Container();

$container['logger'] = function($container) {
    return new Logger();
}

$container['some.controller'] = function ($container) {
    /**
     * @var ContainerInterface $container
     */
    $logger = $container->get('logger');

    return new Controller($logger);
};

$app = new App($container);
$app->get('/some/route', 'some.controller:action');

$app->run();

Profit!
This method is described in the documentation click me
Comment: I see you pass $logger to the controller, should you not pass the container?
Comment: @crafter passing a container to a controller is a bad practice. see https://en.wikipedia.org/wiki/Single_responsibility_principle and https://en.wikipedia.org/wiki/Dependency_injection
Comment: I hear you. You are correct, that container is too large to drag along into your classes.
Answer: Nikic's Fast Route is a very minimal router, so some of the niceties of the bigger frameworks are removed. Here's a basic solution:
routes.php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app->get('/', function($req, $resp, $args) use ($app){return FooBar::asdf($app, $req, $resp);});

controller
    use \Psr\Http\Message\ServerRequestInterface as Request;
    use \Psr\Http\Message\ResponseInterface as Response;
class FooBar{
    static public function asdf(Slim\App $app, Request $req, Response $resp, $args = [])
    {
        return $resp->withJson(['asf']);
    }
}

PHP Slim Framework Create Controller


there is not any errors in validationResult

Question: I used express-validator (6.2.0) in my nodejs project:
I have a form element like this:
<form method="POST" action="/register" novalidate>
    <input type="email" name="email" >
  </form>

and register route is:
   router.post('/register',registerController.registerProcess);

and finally, registerController:
 const { check, validationResult } = require('express-validator');
     registerProcess(req, res, next) {

      check('email', 'Email Error ').isEmail();

      const errors = validationResult(req);
            if (!errors.isEmpty()) {
               res.json({ errors: errors.array()  });
             } else {
               res.json(req.body);
             }

     }

validationResult(req) always is empty: what is my problem?
could you please help me?
Answer: I could solve it.
in  previous versions there is request.checkBody() function but it has not been used in this new version.
we have to use from
post('/action-route' , check() , check(), check() , (req,res) =>{
const errors = validationResult(req);
        if (!errors.isEmpty()) {
            res.json({ errors: errors.array()  });
        } else {
            res.json(req.body);
        }
});

actually . in my idea it is a ridiculous way.


Changing electric plug fixtures outside plate that was painted over and pulled off - nothing fits

Question: I have a house built in 1960. I'm changing some electric plugs. Not the problem exactly. While I was ill some friends painted some of the rooms and painted over the plate rather than taking it off. I'm having problems finding outlets and plates that fit. The ones I find are two small. And a couple of plates were ripped off the wall. Big problem for me. I am a woman without a lot of extra money but if I know where to buy what I need, I'm good to go. And I have fixtures I need to get off the wall that have been painted over. I need a way to get them off without ripping part of the dry wall.
Comment: Where are you on this planet?  And can you post photos of the damaged receptacles?
Comment: We need more info to help you. Where in the world are you? Can we have some pictures of the old outlets, plates, and preferably the wall boxes with a tape measure next to it for scale?
Answer: Removing cover plates that have been "stuck" to the drywall by being painted over can be fairly simple. I'd suggest purchasing a simple utility knife from your local hardware store and carefully running that around the edge of the plate where it meets the drywall. This will cut the paint membrane and prevent the painted drywall surface from peeling or tearing when you remove the plate. Once you've done that, just unscrew the plate and remove.
As for replacing the plate, there are oversized replacement wallplates available to conceal larger openings. Just search for "oversized outlet plate" online to see some examples.


How can I sell an item on behalf of my corporation?

Question: In EVE online there is a role called 'Trader' - which allows you to buy and sell items on behalf of your corporation. I have this role on my character, but whenever I try and sell an item from a corporate hangar at one of our offices, I only have the option to sell the item on behalf of myself.
Have I misunderstood the purpose of this option? Ideally I'd like to be able to list items on the market, but then once these items have sold I'd like the payment to be provided straight to the corporation wallet, rather than to my character.
Is this possible within EVE online?  How can I sell an item on behalf of my corporation?
Answer: You must have access to one of the corporate wallets to buy/sell on behalf of your corporation. Make sure to set that wallet as your active corporate wallet (wallet/corporation tab). You should see a small box at the bottom of the buy/sell window saying "Use corporation account X" where X is the current corporate wallet you have active, tick that and it goes on the corporation's tab.
Additionally, note that any item bought using the corporate wallet will appear in the 'Deliveries' hangar at a station - not your personal hangar.
Comment: Will this result in the payment when an item is purchased being deposited into your corporate wallet?
Comment: Into whichever corporate wallet you have set as active, yes. If you tick the box, any funds needed to complete the transaction will be drawn from the corporate account, if it has enough liquid ISK (in the case of a buy).
Comment: I confirm this. +1 for telling about the "deliveries" thing when *buying* for your corporaion, this puzzled me for a few days when I first tried...


How many binary sequences of length 7 have at least two 1's?

Question: How many binary sequences of length 7 have at least two 1's? Can someone please explain the procedure in detail please. I tried solving it using the "count what you do not want" procedure, but I got nowhere. Thank you in advance
Comment: What do you get if you count those that have exactly zero or exactly one 1?
Answer: The number of $7$-digit sequences is $2^7=128$
The number of $7$-digit sequences with $0$ occurrences of "one" is $\binom70=1$
The number of $7$-digit sequences with $1$ occurrence  of "one" is $\binom71=7$
The number of $7$-digit sequences with $2$ or more occurrences of "one" is $128-(1+7)=120$
Comment: @MathLover95: You're welcome :)