How can I make Logitech Media Server available without specifying a port number?

Question: Logitech Media Server is a streaming audio server formerly by Slim Devices known as SlimServer. It streams audio to Squeezebox devices (by Logitech), and third party devices, like Raspberry Pi-based PiCorePlayer.
When installed with default options, the Logitech Media Server is available on port 9000. The default URL is http://myserver:9000.
I would like to rewrite the URL as http://myserver/music.
From peers, I understand a reverse proxy server is required. I've attempted to use nginx for this without success. I am quite sure Apache could work for this, but have not been successful with either solution. I am eager to learn!
This article, on the SlimDevices wiki, explains the process using Apache. I followed the article, but have not been successful.
The article states to install the package libapache2-mod-proxy-html, which is not found. I understand from this article, it is no longer required. Following the instructions, it seems libapache2-mod-proxy-html is not the cause of my problem. I'm the one asking for help, so I defer to others.
The article's configuration file is:
# Slimserver Reverse Proxy Configuration
# Prepared by BV January 2008
#
# Make sure that the server cannot be abused
#
ProxyRequests Off

# The Proxy section below allows internet users
# to access the internal server

ProxyPass /slimserver/ http://localhost:9000/
ProxyHTMLURLMap http://localhost:9000 /slimserver
<Location /slimserver/>
    Order allow,deny
    Allow from all
    ProxyPassReverse /
    SetOutputFilter proxy-html
    ProxyHTMLURLMap / /slimserver/
    ProxyHTMLURLMap /slimserver /slimserver
    RequestHeader unset Accept-Encoding
</Location>

When I implement the article's solution and attempt to access the Logitech Media Server on http://myserver/slimserver or http://myserver/slimserver, I get the proper page background, but the main content only says Loading Logitech Media Server....
Loading Logitech Media Server... screen image
The URL http://myserver:9000 works. I can interact with the logitech media server normally.
I would prefer to learn the way to do this in nginx, as that's what my coworkers use today and are most familiar with. If I am shown how to do this in Apache2, I could attempt to duplicate the functionality in nginx myself as a learning experience. Once shown the right way, I will go into the Apache or nginx docs and research the details of the solution. Rewriting the URL as described above is something I've wanted to do for years [insert embarrassed face emoji here] but have not been successful.
Answer: You can use iptables to do map requests to port 80 back to 9000:
sudo iptables -I PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-port 9000

This will allow you to request http://myserver/ without the port number.  In order to make this persistent across reboots, you'll need to install iptables-persistent
sudo apt-get install iptables-persistent

Answer: I haven't tried it yet, but why not just set the port to 80 when slimserver.pl is started. I run it on my work machine where I only basic user permissions.
Everything runs out of my home dir.
I have a completely standalone installation, no priviledged user to start/stop etc. It's very flexible if you dig into it.
This is a guidance for the usage of the command:
Usage: ./slimserver.pl [--audiodir ] [--daemon] [--stdio] [--logfile ]
                       [--user ]
                       [--group ]
                       [--httpport  [--httpaddr ]]
                       [--cliport  [--cliaddr ]]
                       [--prefsfile  [--pidfile ]]
                       [--d_various]
                       --help           => Show this usage information.
                       --audiodir       => The path to a directory of your MP3 files.
                       --logfile        => Specify a file for error logging.
                       --daemon         => Run the server in the background.
                                           This may only work on Unix-like systems.
                       --stdio          => Use standard in and out as a command line interface
                                           to the server
                       --user           => Specify the user that server should run as.
                                           Only usable if server is started as root.
                                           This may only work on Unix-like systems.
                       --group          => Specify the group that server should run as.
                                           Only usable if server is started as root.
                                           This may only work on Unix-like systems.
                       --httpport       => Activate the web interface on the specified port.
                                           Set to 0 in order disable the web server.
                       --httpaddr       => Activate the web interface on the specified IP address.
                       --cliport        => Activate the command line interface TCP/IP interface
                                           on the specified port. Set to 0 in order disable the
                                           command line interface server.
                       --cliaddr        => Activate the command line interface TCP/IP
                                           interface on the specified IP address.
                       --prefsfile      => Specify the path to the preferences file
                       --pidfile        => Specify where a process ID file should be stored
                       --quiet          => Minimize the amount of text output
                       --playeraddr     => Specify the _server's_ IP address to use to connect
                                           to players
                       --streamaddr     => Specify the _server's_ IP address to use to connect
                                           to streaming audio sources
                       --nosetup        => Disable setup via http.

Comment: I tried that, but it changed the port for music to be broadcast to devices also. On a device, it appeared the music was playing, but no audio.


addEventListner is not working second time

Question: So I have this fiddle -> https://jsfiddle.net/u73azkLd/1/
I want to make a question generator.
I have that eventListner on +qustion button. Everything is working fine, until the eventListner is finished.
After that, If I want to add another question, after I'm presing +question button, the Question? input appears and after that I can't click on Continue button. I don't get any error in console.
My english is bad and I can't describe it better than that.
Click on +question, click on Continue, after that click on Continue again. Now I want to add another question, so let's click again on +question button and after that the continue button is not working.
I tryed this:
on line 23,24,25:
var ctnBtn1 = document.getElementById("ctnBtn1");
    ctnBtn1.addEventListener("click", function(e) {
      if (e.target && e.target.id == "ctnBtn1") <- This is what i tryed and is not working.
    ctnBtn1.style.display = "none";
    etc ....

Comment: Why are you testing the ID of the target? You're setting the listener specifically on the element, you shouldn't need to check the ID.
Comment: Please provide your HTML and use a JS/CSS/HTML Code Snippet that can be run, that will help people answer your question
Comment: Problem is this statement --> `var ctnBtn1 = document.getElementById("ctnBtn1");` You already have a `Continue` button created and stored in `continueBtnQuestion` variable. You don't need to access the DOM and get the button with the id of `ctnBtn1`. Because doing so will give you the first `Continue` button instead of the newly created one.
Answer: You just hide the button instead of removing it. In result when you search for a button with given id you get the first one (the one that is already hidden).
You can replace ctnBtn1.style.display = "none"; with
ctnBtn1.parentNode.removeChild(ctnBtn1);

Comment: Thank you so much <3333


why a list in python can be changed using the a[1] = a[1][0]?

Question: (I am a beginner)
Here is a code using concept of list and the question is asking to print out the following result:
[1, 'A', 3,] [1, 'A', 3,]

as shown in the below screenshot:

Given that the option being chosen is a correct one.
**What bother me is that why the code in that option works...
especially the code "a[1 ] = a[1 ][0]"
**
I searched in the internet but I have not found a concrete description about it.
Can anyone provide some help?
Thank you very much!
Comment: Useful reading: https://nedbatchelder.com/text/names.html
Comment: they are not the same! What I want to know is the chosen code works. I don't know why "a[1] = a[1][0]" works actually
Comment: Then please [edit] to clarify what you still don't understand.
Comment: I have edited. Please see the bold sentence in my post!
Comment: Why wouldn't it? What precise part of it don't you understand? Have you tried running it in a debugger or on e.g. http://pythontutor.com/ or just adding a `print` between the two lines?
Comment: I have edited the post again. The code I don't know is "a[1] = a[1][0]". I have tried and checked all your suggestions but I still don't know why. I spent about an hour on only this line of code but I still couldn't figure out the principle behind...
Answer: Because lists are mutable objects in python. You are creating list by declaring
 a = [1,2,3]

and then declaring that b = a, at which point both a and b point to the same list. (note that this does not work with immutable types, such as integers in python).
Comment: Maybe my original question is not that clear. I have just edited it a bit. Sorry about that.

What question is actually, why the following code works?

b[1] = 'AB'
a[1] = a[1][0]
Comment: Because a[1] points to the newly created 'AB', which itself can be accessed by indexing, which means that a[1][0] points to 'A'.


Access computer on internal network from Internet

Question: My setup: Ubuntu 13.10 server with ufw, facing outside world on eth0, IP forwarding and masquerading working OK. Internal network 192.168.0/24 on eht1, no problem accessing the internet. I need to access ports 81, 8000 and 554 on 192.168.0.101 coming to/from the internet (it's a DVR for a CCTV system, which I need to monitor remotely). How can I achieve this? Thanks in advance for the help.
Comment: If you're having problems, you may need a static IP.
Answer: Let's solve:

the ports under 1024 (like 554) are reserved to the Administrator (root), so any software which uses them must be executed as root (or safer with the sudo software). It's a safety measure.
the ports you want to use should be opened, execute those commands:
sudo ufw default deny
sudo ufw enable

...to enable the ufw iptables wrapper. Then execute:
sudo ufw allow <port number>

...for any port number you want to open (81,8000 and 554) to any type of connection from any host (the sintax may vary from version to version, always read man ufw).
The sintax to control the ufw interface is reported here, I suggest to read it.

After that you need to open the ports on your default gateway (a router or a switch) if it features an hardware firewall (like the Netgear and Belkin routers).
Now you have the desired remote access. :-)
Let us know by commenting down here if it's all ok & have a nice experience.
Answer: Update:
This is how solved it:
1) Insert rules for three ports:
ufw allow 81
ufw allow 8000
ufw allow 554

2) in /etc/ufw/before.rules I added the following lines in the NAT section (just before POSTROUTING):
:PREROUTING - [0:0]
-A PREROUTING -p tcp --dport 81 -j DNAT --to-destination 192.168.0.101:81
-A PREROUTING -p tcp --dport 8000 -j DNAT --to-destination 192.168.0.101:8000
-A PREROUTING -p tcp --dport 554 -j DNAT --to-destination 192.168.0.101:554

3) Reload the firewall:
ufw reload

In Firefox I type http//myserver.com:81 (http://myserver.com is our regular webpage) and I'm redirected to the DVR on the internal network which runs the CCTV programs I need to access from the internet (ports 8000 and 554 are used to access the system using a smartphone)
Again, thanks for the help.


Set Font Size Dynamically in WPF

Question: I'm trying to set font size dynamically in WPF. Here what i did so far.
App.xaml

Set Font Size Dynamically in WPF


Is there anything special about the blue mutants?

Question:
I wonder why do some of the mutants have blue skin rather than pink. Is it just for variety or does it mean something?
Comment: Is the whole game really dark like the screenshot? I can barely see anything...
Comment: At night when you have no lighter, torch, or flashlight, yes. Survival-horror crafting game. Of course the game has plenty of light sources and it's day half the time. Speaking of the darkness in the screenshot though, is it possible the mutants only look blue because of lighting?
Answer: according to this wiki https://theforest.gamepedia.com/Mutant

Blue Armsys are identical to regular Armsy's with the exception of
  greater damage and health. It is possible they may be faster.

Basically the blue mutants are harder to kill.


Check if value exists in row, then delete

Question: I have always to delete thirty values from a column, I have managed to "create" a code, that does that, however when one of the values is not found, the code bugs and deletes the entire column.
I'm looking for some piece of code that ckecks if the values exists, if not it just skips it.
I'd rather not use that kinda code that prompts a text box to input the value, since I have to delete 30 of them, which have different names.
While writing this question I tried this so far, however the codes  keeps asking for the next object, which requires me to click at lest 29 times
Sub IfContains()
    If InStr(ActiveCell.Value, "string1") > 0 Then
        ActiveCell.Delete = True
    Else
        If InStr(ActiveCell.Value, "string2") > 0 Then
            ActiveCellDelete = True
        End If
    End If
End Sub

Comment: Could you share the complete code for context? `ActiveCell` is a macro-recorder thing and there is no place for it in a proper code. Also, `ActiveCellDelete` is not a thing at all. A 'natural' way would be to write the thirty values to a data structure (array, dictionary) and test each cells value against the values in the data structure. Another way would be to use the data structure to filter the data using `AutoFilter`.
Answer: This might be a better approach.  You have only one string to configure, delimited by the tilde (~) character.  Then split that into an array of individual values and use a loop to look for every value of the array.
Sub IfContains()
    Dim x As Integer
    Dim values As Variant
    values = "string1~string2~string3" ' using a tilde (~) to separate the values
    values = Split(values, "~") ' make an array of individual values

    For x = 0 To UBound(values)
        If InStr(1, ActiveCell.Value, values(x)) > 0 Then ActiveCell.Delete
    Next

End Sub


How to set a default to a forms.ChoiceField()?

Question: I am trying to set a default selection for payment choices to be Stripe, but I keep getting an errorTypeError: __init__() got an unexpected keyword argument 'default'
Here is the forms.py
PAYMENT_CHOICES = (
    ('S', 'Stripe'),
    ('P', 'Paypal')
)

class CheckoutForm(forms.Form):
    payment_option = forms.ChoiceField(
        widget=forms.RadioSelect, choices=PAYMENT_CHOICES, default='Stripe')

Answer: At first, form.*Field classes has no default attribute. However, it has initial attribute represents a value which will be displayed after rendering a page.
Also in PAYMENT_CHOICES you should use in your code first values of tuples since these tuples contain real value in first place and verbose name in second.
That is how working version of your code may looks:
PAYMENT_CHOICES = (
    ('S', 'Stripe'),
    ('P', 'Paypal')
)

class CheckoutForm(forms.Form):
    payment_option = forms.ChoiceField(
        widget=forms.RadioSelect,
        choices=PAYMENT_CHOICES,
        initial='S')

Comment: Hi I added it but it does not this make it a default, if no selection by the user took place does it auto selects the 's' ?
Comment: No, it only declares initial value of html ``. If you want to always save `'S'` when the  user selected empty value, you can redefine `clean` methods of your Form or use signal handlers.


Seaborn plot with shared x axis

Question: I am trying to plot 2 columns of a dataframe (one as a bar plot and the other as a scatterplot). I can get this working with Matplotlib, but I want it with Seaborn.
This is the code:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'Announced Year': [2016, 2017, 2018, 2019],
              'Amount Awarded': [12978216, 11582629, 11178338, 11369267],
              'Number of Awarded': [18, 14, 13, 13]})

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

sns.scatterplot(x="Announced Year", y="Number of Awarded", data=df, ax=ax2)
sns.barplot(x="Announced Year", y="Amount Awarded", data=df, ax=ax1)

fig.tight_layout()  # otherwise the right y-label is slightly clipped

plt.title('2016 to 2019 Announcements')

Comment: A `scatterplot` is a numerical plot, a barplot is a `categorical` plot, so it's hardly possible to put them on the same graph. Matplotlib's `bar` and `scatter` are both numerical, so that works fine.
Comment: Does this answer your question? [How can I overlay two graphs in Seaborn?](https://stackoverflow.com/questions/32899463/how-can-i-overlay-two-graphs-in-seaborn)
Comment: Nope. That's exactly what I do in my code and doesn't work.
Answer: You can plot with shared x-axis using x=np.arange(0,len(df)) instead of x="Announced Year" for scatterplot.
fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

sns.barplot(x="Announced Year", y="Amount Awarded", data=df, ax=ax2, alpha=.5)
sns.scatterplot(x=np.arange(0,len(df)), y="Number of Awarded", data=df, ax=ax1)

fig.tight_layout()  # otherwise the right y-label is slightly clipped

plt.title('2016 to 2019 Announcements')

Seaborn plot with shared x axis


How to assert JSON equality in python-behave with diffs on failing tests?

Question: How do I assert JSON equality in python-behave and get a diff as output when assertion fails?
In Ruby I use: https://github.com/collectiveidea/json_spec , so I am basically looking for similar functionality in Python.
With a normal assert statement the output is very unhelpful.
Answer: I needed a similar functionality a while back. The easiest way I found was to use https://github.com/ChannelIQ/jsoncompare. You can install it with:
$ pip install jsoncompare

Then in your step code you can make an assert like this:
from jsoncompare import jsoncompare

if jsoncompare.are_same(json1, json2):
    assert True
else:
    print (jsoncompare.are_same(json1, json2))
    assert False

By default, behave does not display print statements unless there is a failure, you must make the test fail in order to get the diff output to display.


How to use Spring MVC @JsonView when returning an object hierarchy from a Rest Controller

Question: I'm building an application which uses Spring MVC 4.10 with jackson 2.3.2.
I have a Project class which has children Proposal objects and a Customer object. These Proposal objects are complex and I want to return a summarized JSON view of them. A similar situation happens with the Customer object. I'm trying to implement this with @JsonView annotations.
I wanted to ask if extending the views of the member object classes in the container object class view is the way to do this or, if not, if there is a cleaner way to implement this that I am unaware of.
Context
Before today, I was under the false impression that you could annotate your controller with multiple views and that the resulting JSON representation would be filtered accordingly.
@JsonView({Project.Extended.class, Proposal.Summary.class, Customer.Summary.class})
@Transactional
@RequestMapping(value="/project", method=RequestMethod.GET)
public @ResponseBody List<Project> findAll() {
    return projectDAO.findAll();
}

Where each class had its own JsonView annotations and interfaces
e.g.:
public class Customer {
    ...
    public interface Summary {}
    public interface Normal extends Summary {}
    public interface Extended extends Normal {}
}

Nevertheless, it is only the first view in the array that gets taken into account. According to https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

Only one class or interface can be specified with the @JsonView
  annotation, but you can use inheritance to represent JSON View
  hierarchies (if a field is part of a JSON View, it will be also part
  of parent view). For example, this handler method will serialize
  fields annotated with @JsonView(View.Summary.class) and
  @JsonView(View.SummaryWithRecipients.class):

and the official documentation in http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-jsonview

To use it with an @ResponseBody controller method or controller
  methods that return ResponseEntity, simply add the @JsonView
  annotation with a class argument specifying the view class or
  interface to be used:

So, I ended up extending the views of the members in the view of the container object, like this
@Entity
public class Project {
    ...
    public static interface Extended extends Normal, Proposal.Extended {}
    public static interface Normal extends Summary, Customer.Normal {}
    public static interface Summary {}
}

and changed my controller to this
@JsonView(Project.Extended.class)
@Transactional
@RequestMapping(value="/project", method=RequestMethod.GET)
public @ResponseBody List<Project> findAll() {
    return projectDAO.findAll();
}

This seems to do the trick, but I couldn't find documentation or discussion about this situation. Is this the intended use of JsonViews or is it kind of hackish?
Thank you in advance
-Patricio Marrone
Answer: I believe you have configured your views as necessary.  The root of the issue is not Spring's @JsonView, but rather Jackson's implementation of views.  As stated in Jackson's view documentation:

Only single active view per serialization; but due to inheritance of Views, can combine Views via aggregation.

So, it appears that Spring is simply passing on and adhering to the limitation set in place by Jackson 2.
Answer: I use Jersey+Jackson but issued just the same problem.
That's a trick that I'm doing for my application to let me require for several JSON Views during serialization. I bet it is also possible with Spring MVC instead of Jersey, but not 100% sure. It also does not seem to have performance issues. Maybe it is a bit complicated for your case, but if you have large object with big amount of possible views, maybe it's better than doing a lot of inheritance.
So I use the Jackson Filter approach to require several views in serialization. However, I haven't found the way to overcome the issue of putting @JsonFilter("name") above the classes to map, which does not make it so clean. But I mask it in custom annotation at least:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonFilter(JSONUtils.JACKSON_MULTIPLE_VIEWS_FILTER_NAME)
public @interface JsonMultipleViews {}

The filter itself looks like this:
public class JsonMultipleViewsFilter extends SimpleBeanPropertyFilter {

    private Collection<Class<?>> wantedViews;

    public JsonMultipleViewsFilter(Collection<Class<?>> wantedViews) {
        this.wantedViews = wantedViews;
    }

    @Override
    public void serializeAsField( Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer ) throws Exception {
        if( include( writer ) ) {
            JsonView jsonViewAnnotation = writer.getAnnotation(JsonView.class);
            // serialize the field only if there is no @JsonView annotation or, if there is one, check that at least one
            // of view classes above the field fits one of required classes. if yes, serialize the field, if no - skip the field
            if( jsonViewAnnotation == null || containsJsonViews(jsonViewAnnotation.value()) ) {
                writer.serializeAsField( pojo, jgen, provider );
            }
        }
        else if( !jgen.canOmitFields() ) {
            // since 2.3
            writer.serializeAsOmittedField( pojo, jgen, provider );
        }
    }

    private boolean containsJsonViews(Class<?>[] viewsOfProperty) {
        for (Class<?> viewOfProperty : viewsOfProperty) {
            for (Class<?> wantedView : wantedViews) {
                // check also subclasses of required view class
                if (viewOfProperty.isAssignableFrom(wantedView)) {
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    protected boolean include( BeanPropertyWriter writer ) {
        return true;
    }

    @Override
    protected boolean include( PropertyWriter writer ) {
        return true;
    }
}

I can use this filter like this:
public static String toJson( Object object, Collection<Class<?>> jsonViewClasses) throws JsonProcessingException {
    // if no json view class is provided, just map without view approach
    if (jsonViewClasses.isEmpty()) {
        return mapper.writeValueAsString(object);
    }
    // if only one json view class is provided, use out of the box jackson mechanism for handling json views
    if (jsonViewClasses.size() == 1) {
        return mapper.writerWithView(jsonViewClasses.iterator().next()).writeValueAsString(object);
    }

    // if more than one json view class is provided, uses custom filter to serialize with multiple views
    JsonMultipleViewsFilter jsonMultipleViewsFilter = new JsonMultipleViewsFilter(jsonViewClasses);
    return mapper.writer(new SimpleFilterProvider() // use filter approach when serializing
                .setDefaultFilter(jsonMultipleViewsFilter) // set it as default filter in case of error in writing filter name
                .addFilter(JACKSON_MULTIPLE_VIEWS_FILTER_NAME, jsonMultipleViewsFilter) // set custom filter for multiple views with name
                .setFailOnUnknownId(false)) // if filter is unknown, don't fail, use default one
                .writeValueAsString(object);
}

After that, Jersey allows us to add Jersey Filters on the point of running the application (it goes through each endpoint in each Controller in start of application and we can easily bind the Jersey filters at this moment if there is is multiple value in @JsonView annotation above the endpoint).
In Jersey filter for @JsonView annotation with multiple value above endpoint, once it's bint on startup to correct endpoints depending on annotations, we can easily override the response entity with calling that utils method
toJson(previousResponeObjectReturned, viewClassesFromAnnoation);

No reason to provide the code of Jersey Filter here since you're using Spring MVC. I just hope that it's easy to do it the same way in Spring MVC.
The Domain Object would look like this:
@JsonMultipleViews
public class Example
{
    private int id;
    private String name;

    @JsonView(JsonViews.Extended.class)
    private String extendedInfo;

    @JsonView(JsonViews.Meta.class)
    private Date updateDate;

    public static class JsonViews {
        public interface Min {}
        public interface Extended extends Min {}
        public interface Meta extends Min {}
        //...
        public interface All extends Extended, Meta {} // interfaces are needed for multiple inheritence of views
    }
}

We can ommit putting Min.class in my case on those fields that are always required not depending on view. We just put Min in required views and it will serialize all fields without @JsonView annotation.
View All.class is required for me since if we have, for example, a specific set of views for each domain class (like in my case) and then we need to map a complex model consisting of several domain objects that both use views approach - some view for object one, but all views for object two, it's easier to put it above endpoint like this:
 @JsonView({ObjectOneViews.SomeView.class, ObjectTwoViews.All.class})

because if we ommit ObjectTwoViews.All.class here and require for only ObjectOneViews.SomeView.class, those fields that are marked with annotation in Object Two will not be serialized.


User Activity Tracking using javascript library

Question: Is it possible to track every action of a user on a webpage and creating log of it? The idea is to transfer log of user actions to server via AJAX and saving it. On each event for each element I can write code/logic to write some log in console, but I was wondering if there is any library/shortcut available which can log all actions on webpage at client side including events and actions such as copy, paste, click, double click, selection etc. with their element reference.
Comment: So basically you want to re-create Google Analytics?
Comment: Just logging as of now :) creating analytical reports are too far to think.
Comment: I found something here http://stackoverflow.com/a/7439584/1356109 but its for single element. I'm looking for some dynamic solution. I guess $( "*" ) should work.
Comment: You might find this [blog post](https://www.techighness.com/post/javascript-track-user-activity-on-webpage-with-custom-script/) useful. It shares custom JavaScript code to track user activity on a webpage.
Answer: You can use ready-made solutions:

http://www.google.com/analytics/
http://www.clicktale.com/
https://segment.io/
http://www.extrawatch.com/
http://mouseflow.com/
https://www.seevolution.com/
http://clicky.com/

You can do amazing stuff with Google Analytics and its Event Tracker:

https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
http://searchenginewatch.com/article/2287906/10-Google-Analytics-Custom-Events-That-Track-the-Untrackable

If you're looking for a custom-made solution, you can try the following one with PHP and JavaScript:

http://css-tricks.com/tracking-clicks-building-a-clickmap-with-php-and-jquery/

Keep in mind that using third-party solutions is better performance-wise. Writing the coordinates of the mouse movements in a database in real time, needs a lot of resources.
Comment: A few words to describe what each of these links are would be very helpful.
Answer: Personally I hate 3rd party like google analytics and similar company. Because I dont want to share my web analytics with them. Anyway there is a very very lightweight (about 5KB minified) and easily extendable javascript library.
Here is git repo: https://github.com/greenstick/interactor
and you can see a preview of it: http://greenstick.github.io/interactor/
What Data is Provided?
General Data:

Which page is loaded
When the user loaded the page
When the user left the page
The URL of the loaded page
The previous page location
The title of the page
The language settings of the user
The user's platform
The port used to access the web server
The inner and outer width and height of the web browser

Interaction / Conversion Data:

The interaction type (i.e. general interaction or conversion)
The time of the interaction
The event that triggered interaction
The target HTML element tag
The target HTML element classes
The target HTML element content (i.e. text, etc.)
The cursor position relative to client
The cursor position relative to screen

Example:
var elementsToTrack = [
{
    element: "element1",
    events : ["mouseup", "touchend"]
},
{
    element: "element2",
    events : ["mouseup"]
},
{
    element: "element3",
    events : ["mouseup"]
}
];

for (var i = 0; i < elementsToTrack.length; i++) {
var e = elementsToTrack[i];
new Interactor({
    interactionElement  : e.element,
    interactionEvents   : e.events
});
}

I Hope this information will be helpful.
Answer: I don't think that this kind of javascript library exist, you could easily build one with jquery, just listen to all the event (blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup  mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error)
and than send them to the server side using web sockets
Answer: Have you look at Google Analytic Event Tracking?
You need to embed the tracking function within your javascript but it is very convenience to use.
// Google API
_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)

// Example
_trackEvent('checkout' 'remove-item' 'poodle skirt')

Update: 2017
New Analytics Api
// Api
ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);

// Example remove product id#27
ga('send', 'event', 'ecart', 'remove-item', 'poodle skirt', 27);
   // OR
ga('send', {
      hitType: 'event',
      eventCategory: 'ecart',
      eventAction: 'remove-item',
      eventLabel: 'poodle skirt'
   });


producer consumer synchronizing11

Question: #include <stdio.h>
#include <pthread.h>
#define MAX 10                                  /* maximum iterations */
int number;                                     /* the resource */
pthread_mutex_t mu= PTHREAD_MUTEX_INITIALIZER;  /* to protect the resource*/
/*
    Condition variable to signal consumer that a new number is available for
    consumption.
*/
pthread_cond_t sig_consumer= PTHREAD_COND_INITIALIZER;
/*
      Condition variable to signal the producer that
      (a) the new number has been consumed,
      (b) generate another one.
*/
pthread_cond_t sig_producer= PTHREAD_COND_INITIALIZER;
void *consumer(void *dummy)
{
      int printed= 0;
      printf("Consumer : \"Hello I am consumer #%ld. Ready to consume numbers"
             " now\"\n", pthread_self());

      while (1)
      {
         pthread_mutex_lock(&mu);
         /* Signal the producer that the consumer is ready. */
         pthread_cond_signal(&sig_producer);
         /* Wait for a new number. */
         pthread_cond_wait(&sig_consumer, &mu);
         /* Consume (print) the number. */
         printf("Consumer : %d\n", number);
         /* Unlock the mutex. */
         pthread_mutex_unlock(&mu);

         /*
           If the MAX number was the last consumed number, the consumer should
           stop.
         */
         if (number == MAX)
         {
           printf("Consumer done.. !!\n");
           break;
         }
      }
}
        /**
          @func producer
          This function is responsible for incrementing the number and signalling the
          consumer.
        */
void *producer(void *dummy)
{
      printf("Producer : \"Hello I am producer #%ld. Ready to produce numbers"
             " now\"\n", pthread_self());
      while (1)
      {
            pthread_mutex_lock(&mu);
            number ++;
            printf("Producer : %d\n", number);
            /*
              Signal the consumer that a new number has been generated for its
              consumption.
            */
            pthread_cond_signal(&sig_consumer);
            /*
              Now wait for consumer to confirm. Note, expect no confirmation for
              consumption of MAX from consumer.
            */
            if (number != MAX)
              pthread_cond_wait(&sig_producer, &mu);

            /* Unlock the mutex. */
            pthread_mutex_unlock(&mu);

            /* Stop if MAX has been produced. */
            if (number == MAX)
            {
              printf("Producer done.. !!\n");
              break;
            }
      }
}

void main()
{
      int rc, i;
      pthread_t t[2];
      number= 0;
      /* Create consumer & producer threads. */
      if ((rc= pthread_create(&t[0], NULL, consumer, NULL)))
        printf("Error creating the consumer thread..\n");
      if ((rc= pthread_create(&t[1], NULL, producer, NULL)))
        printf("Error creating the producer thread..\n");

      /* Wait for consumer/producer to exit. */
      for (i= 0; i < 2; i ++)
        pthread_join(t[i], NULL);

      printf("Done..\n");
}

Question:  If the consumer thread is started before the producer thread, then the program will provide the expected result, but if the producer is started first, then the consumer will start consuming from number 2 onwards; the consumer is unable consume number 1. How to correct the program even though the producer thread starts first, without introducing any additional variable or sleep?
Comment: Note that `void main()` is not permissible when you're using POSIX threads.  It is only permissible on Windows systems, and is an aberration even there (but a documented aberration).
Comment: That's not how you use `pthread_cond_wait`. You need to call it in a loop (it may return spontaneously) and each time round the loop you need to test, with the lock held, whether you are in fact able to proceed.
Comment: possible duplicate of [pthread\_cond\_wait for 2 threads](http://stackoverflow.com/questions/13675132/pthread-cond-wait-for-2-threads)
Comment: @AlanStokes, your example contains one more additional global variable named as enum { STATE_A, STATE_B } state = STATE_A;. My intention is without any additional variable how to overcome my problem.
Comment: You can't. The answer to that question, and the answer below, explain that.
Answer: The problem with pthread_cond_t is its name.  Despite being nominally a "condition", it has no state... in particular, it does not remember that it has been signalled at all -- if you thought it might count how many times it has been signalled, you will be disappointed (for that you need a semaphore).  To put that another way, if there is no pthread waiting on a condition when it is signalled, the signal has no effect and is forgotten.
The "condition" is better thought of as a "wait queue", where pthreads wait for some state to be updated.  So usually you have some state, protected by the mutex.  If the state is not as required for the pthread to continue, then the pthread waits on the "condition".  When the state is updated, the "condition" can be signalled.  When the waiter wakes up, it must check the state, and decide whether everything is now ready to continue.
Where there are two or more pthreads waiting, the standard allows pthread_cond_signal() to wake up one, two or more, or all, the waiters.  The mutex ensures that the waiters' access to the state is serialised, but the waiter cannot (in general, and for this reason in particular) assume that the state is unchanged since the signal.  So, it is common to write the waiter:
pthread_mutex_lock(&mutex) ;
....
while(...what we need to continue...)
  pthread_cond_wait(&cond, &mutex) ;
....
pthread_mutex_unlock(&mutex) ;

Which reflects the importance of the state, and how little the "condition" contributes.

producer consumer synchronizing11


In Highcharts, how to make box plot outliers transition from light to dark colors?

Question: Is it possible to make the outliers color transition from light to dark? I am using box plot chart from Highcharts and want my outliers to render from light red to dark red. Any outliers above 100k needs to display in a darker red.

https://jsfiddle.net/samwhite/9amz3y7x/1/
    Highcharts.chart('container', {
        chart: {
            type: 'boxplot',
            zoomType: 'xy'
        },
        title: {
            text: 'Boxplots for Buzz'
        },
        credits: {enabled: false},
        legend: {
            enabled: false
        },

        xAxis: {
            categories: categories,
            title: {
                text: 'Stock Symbol'
            }
        },

        yAxis: {
            title: {
                text: 'Buzz'
            },
        },

        plotOptions: {
            boxplot: {
                fillColor: 'red',
                // medianColor: '',
                // stemColor: '',
                // whiskerColor: ''
            }
        },

        series: [{
            name: 'Buzz',
            data: box_dat,
            color: 'red',
        }, {
            name: 'Outliers',
            color: 'red',
            type: 'scatter',
            data: outliers,
            marker: {
                fillColor: 'white',
                lineWidth: 1,
                lineColor: 'red'
            },
            tooltip: {
                pointFormat: 'Observation: {point.y}'
            }
        }]

    });

Comment: look at this example. You have to use zones http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/series/color-zones-simple/
Comment: @BernhardBeatus thanks for the response. I tried to used zones with my code but it doesn't work for me.
Answer: You should use zones or color axis, but they only change point.color, which, in your case is replaced by marker.lineColor. Add the below plugin to allow changing line color by zones.
(function(H) {
    H.wrap(H.Point.prototype, 'getZone', function(proceed) {
        proceed.apply(this, Array.prototype.slice.call(arguments, 1));

        this.options.marker = {
            lineColor: this.color
        };
    });
}(Highcharts));

Live demo: https://jsfiddle.net/BlackLabel/sc2hk1b9/
Docs: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts
Comment: I am amazed by your experience with Highchart library. Thank you so much!


Is this full or partial specialization of class template?

Question: In the following example:
template <class T, int n>
class MyContainer{
public:
    T myArray[size];
    int size;
    MyContainer() : size(n){}
};
// full or partial specialization?
template <int n>
class MyContainer <double, n>{
public:
    double myArray[n];
    int size;
    MyContainer() : size(n){}
    double sum();
    double average();
};

I just started learning full and partial template specializations and this confuses me a bit. Generally, I would say this is a full template specialization since the parameter T is defined as double and there are no other formal parameters left. But, I'm not sure if parameter n makes any difference here?
Comment: yes it does, it isn't a full specialization until all parameters in the template parameter list have been specialized/specified
Comment: Partial. Hint, full specialisation would look `template <>`, i.e. all the parameters have been specialised.
Comment: If it's a type, it's full specialization; if it's a template, it's partial specialization.
Comment: So, If I remove **int n** then it would be a full template specialization?
Answer: Yes it does, it isn't a full specialization until all parameters in the template parameter list have been specialized/specified, e.g.
template <>
class MyContainer <double, 4> { // Full specialization
....

template <int n>
class MyContainer <double, n> { // Partial specialization
....

template <class T, int n> // Partial specialization (adds something to the base template parameter list: '*')
class MyContainer<T*,n> {
....

it doesn't matter if the template parameter is a type or non-type, if you don't specialize all the parameters in the list you won't have a complete specialization.
Answer: It is not a full specialization unless all template parameters have been specialized.
template <> introduces full specializations.


Ubuntu: how to enter a directory in shell

Question: On my Desktop I have created a folder called "Files", I would like to know how to access that folder through a shell script
Comment: Useful information for askers: https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/
Comment: Uh... English please.
Comment: Ok, done.  Show your effort please?
Comment: @user202729 is already in English
Answer: When in Linux file system using bash you can navigate to the home directory in many ways:
After you reach the home directory everything is easy from there including reaching Desktop.

The ~ or $HOME reference:
  In Linux based systems  the keyword ~ or $HOME refers to the home directory of the computer.

For example say you are currently at /bin, to navigate to home if you know your username you would do :
$ cd /home/yourusername
#The directory is now switched to :
$ pwd #This command stands for print working directory
'/home/yourusername'

Now you can do it alternatively by:
(Again assuming you are in /bin)
$ cd $HOME
$ pwd
'/home/yourusername'
#Alternatively
$ cd /bin
$ cd ~
$ pwd
'/home/yourusername'

These shortcuts let you go to home without writing much and are even recommended.
Now for your problem you can easily navigate to your folder by:

cd ~/Desktop/Files/
Comment: Your outputs may not have prompts `$` before them `;-)` Anyways elaborate enough. ++
Comment: Yeah sorry, i'll fix it!


how to install libgnutls26 in Ubuntu 15.04 or higher

Question: I am having problem installing libgnutls26. I tried searching but didn't helped. I am using 32 bit sys. While installing a program it says following :
Building dependency tree
Reading state information... Done
Building data structures... Done
Building data structures... Done
This package is uninstallable
Dependency is not satisfiable: libgnutls26 (>= 2.12.14-0)

I tried installing with gdebi but it also didn't helped. Can anyone help me to fix it? BTW my Ubuntu is 15.04.
Comment: Try  `sudo apt-get install libgnutls26:i386`
Comment: I already tried that one. it says

E: Package 'libgnutls26' has no installation candidate.

I think I need to add repo but which one I dont know
Comment: what do you get when you type `apt-cache policy libgnutls26` ?
Comment: This is what I get :

libgnutls26:
  Installed: (none)
  Candidate: (none)
  Version table:
Comment: The program's dependencies appear to be targeted at Ubuntu 14.04: in 15.04 the main GNU TLS runtime library is [libgnutls-deb0-28](http://packages.ubuntu.com/vivid/libgnutls-deb0-28)
Comment: It says libgnutls-deb0-28 is already the newest version
Comment: So? that won't help if the "program" you are trying to install wants libgnutls26
Answer: Actually, I see you point. In my case, after updating to Ubuntu 15.04 my Evernote (running on Wine 1.7.44) stopped working - when trying to log in or to synchronize notes I've been receiving INTERNET_SECURITY_CHANNEL_ERROR from TLS. I believe that might be due to libgnutls API change - in Ubuntu 14.10 its version was libgnutls26 (based on GnuTLS 2.12), while in 15.04 it's libgnutls-deb0-28 (based on GnuTLS 3.3).
If you want to install 32-bit libgnutls26 (from Ubuntu 14.10) in Ubuntu 15.04 try these:
wget http://security.ubuntu.com/ubuntu/pool/main/libg/libgcrypt11/libgcrypt11_1.5.4-2ubuntu1.1_i386.deb
wget http://mirrors.kernel.org/ubuntu/pool/universe/g/gnutls26/libgnutls26_2.12.23-15ubuntu2_i386.deb

sudo dpkg -i libgcrypt11_1.5.4-2ubuntu1.1_i386.deb
sudo dpkg -i libgnutls26_2.12.23-15ubuntu2_i386.deb

Other mirrors you can find here and here.
After installing these by myself, when I call lsof -P -T -p $(pidof Evernote.exe) | grep gnutls while running Evernote I get:
Evernote. 11332 xxx  mem    REG                8,6   805808  1052438 /usr/lib/i386-linux-gnu/libgnutls.so.26.22.6
Evernote. 11332 xxx  mem    REG                8,6  1306528  1052404 /usr/lib/i386-linux-gnu/libgnutls-deb0.so.28.41.0

which means that Evernote/Wine is currently using libgnutls26 library.
Bare in mind that you won't receive any security updates for libgnutls26 as it has been released for 14.10, but removed completely from Ubuntu 15.04.

Editor's Note
Since 15.04 is not a LTS release, these can disappear (indeed those did). So, you should find and install from last LTS version i.e. Trusty 14.04. Find the two libraries from these two links:

http://packages.ubuntu.com/trusty/i386/libgnutls26/download (libgnutls26)
http://packages.ubuntu.com/trusty/i386/libgcrypt11/download (libgcrypt11)
Comment: It seems that the links for Trusty 14.04 are now dead too. I might be ok though, I was trying to install a very old BricsCAD13, I will just try a newer BricsCAD.
Answer: I was looking for libgnutls.so.26 on 16.04, I fixed it by copying 14.04 lib in to 16.04
You can find the version for 14.04 from here

32bit - http://packages.ubuntu.com/trusty/i386/libgnutls26/download
64bit - http://packages.ubuntu.com/trusty/amd64/libgnutls26/download
Comment: Welcome to Ask Ubuntu! I recommend [edit]ing this answer to expand it with specific details about how to do this. (See also [How do I write a good answer?](/help/how-to-answer) for general advice about what sorts of answers are considered most valuable on Ask Ubuntu.)
Answer: Add this line deb http://security.ubuntu.com/ubuntu trusty-security main
 to your /etc/apt/sources.list and run sudo apt-get update and sudo apt-get install libgbutls26
Comment: you might `apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3B4FE6ACC0B21F32`


Starcraft 2: is it possible to switch languages?

Question: I have bought what appears to be Polish version of Starcraft 2, will I be able to play it in English? Interfaces, sounds, etc.?
Just wanna be sure before I open the case and install it, so that I could ask for refund in the worst case.
Answer: Yes, it is possible. Your game license should allow you to download any language available in your region. As your region would be EU, you would have access to the great britain version of the client. If for some reason you have any issues, you can also follow the instructions located here to work around it.
Of note though, the actual DVD's will probably contain only the polish version, so you will need to download the english language pack. I presume you'll have no problem accessing an internet connection though.
Comment: Apparently this is the only "official" way :(
Answer: From my DVD copy of the English version, it only contains the enUS "asset" and "data" files on the media.  The collective localized files are relatively large, and I doubt multiple languages would be able to fit onto one DVD, assuming the videos are re-rendered for a different language versus just dubbing or subtitling (I wouldn't know).
As you suggested, you may be able to get around it by downloading the installer in whichever language from Blizzard, but some platforms (Valve's Steam) won't let you use CD-keys outside of the proper region.  If you're in Europe though, it should be fine.


How to see the visibility of my secret religion?

Question: Is there a way (that does not involve the console/cheating) to see the current visibility of my secret religion?
Answer: Outside of the console or mods, I don't think there's a way to see exactly how much visibility you have. You can get an estimate of how much visibility you have via the "under suspicion" and "highly_suspect" modifiers. If you know what events/decisions raise/lower visibility, you could manually keep track of it.
Estimating:
Whenever a character gains suspicion, the game then checks for 3 breakpoints: 15, 25, and 40.
At 15 visibility, they gain the "under suspicion" modifier.  (-0.5 monthly prestige )
At 25 visibility, they gain the "highly suspect" modifier   (-1 monthly prestige, -1 monthly piety)
At 40 visibility, if the character is an independent ruler, they auto-reveal. If they're christian, they get excommunicated . If they're a devil worshiper, they gain the "known satanist" modifier  (-50 general opinion, -1 monthly prestige, -3 monthly piety). If they're not a devil worshiper, they gain the "accused apostate" modifier  (-10 general opinion, -0.5 monthly piety).

note: answered on version 188.8.131.52


Replace pasted range on a slide with an updated version

Question: I have a sub() to replace a shape on a ppt slide. The existing shape is a range of cells pasted from Excel (PasteSpecial DataType:=0).
I am trying to replace the pasted range on the slide with an updated version of that same range. I believe my existing code is correct, except for the .TextEffect.Text line where I recieve

Type Mismatch error

Is this because it is not a single cell, but rather a range of cells?
Sub ReplaceTable()
    Dim PowerPointApp As PowerPoint.Application
    Dim myPresentation As PowerPoint.Presentation
    Dim i As Object

    Set PowerPointApp = GetObject(, "PowerPoint.Application")
    Set myPresentation = PowerPointApp.ActivePresentation

    Dim SlideIndex
    Dim SlideShape
    Dim ShapeContent

    For Each i In Worksheets("Sheet1").Range("H2:H" & Worksheets("Sheet1").Range("H" & Rows.Count).End(xlUp).Row)

        SlideIndex = Worksheets("Sheet1").Range("H" & i.Row) 'moves to defined slide index
        SlideShape = "Content Placeholder 3" 'selects shape
        ShapeContent = Worksheets("Sheet2").Range("D9:V24") 'copies new tabular data to replace current table on slide
        myPresentation.Slides(SlideIndex).Shapes(SlideShape).TextEffect.Text = ShapeContent

    Next i

End Sub

Comment: Solved by deleting shape and then replacing, as so:

`ShapeContent.Copy
    myPresentation.Slides(SlideIndex).Shapes(SlideShape).Delete
    myPresentation.Slides(SlideIndex).Shapes.PasteSpecial`
Comment: You're implicitly trying to assign the `.Value` of a multi-cell range, which is a 2D array, to `.Text`. [`.Text`](https://learn.microsoft.com/en-us/office/vba/api/powerpoint.texteffectformat.text) expects a `String`, not an array. I'm not very strong in PPT, but I expect you want a different approach for a range of Excel cells.
Comment: Is there an alternative approach? I saw .TextFrame.TextRange out on the web, but even when I set the ShapeContent to a range and adjust the end of the code `myPresentation.Slides(SlideIndex).Shapes(SlideShape).TextFrame.TextRange = ShapeContent'
`
I'm still receiving an error. Likely because I'm not applying it correctly.
Comment: Any reason you're not using `PasteSpecial` as you mention early in the question body?
Comment: I was unfamiliar with approach, as in the `PasteSpecial` scenario mentioned, I'm creating a new slide (not replacing existing content) like this:

`'Add a slide to the Presentation
  Set mySlide = myPresentation.Slides.Add(1, 16) '11 = ppLayoutTitleOnly

'Copy Excel Range
  Rng.Copy

'Paste to PowerPoint and position
  mySlide.Shapes.PasteSpecial DataType:=0  '0 = ppPasteDefault - if image = 2
  Set myShape = mySlide.Shapes(mySlide.Shapes.Count)`
Answer: Solved by deleting original shape and then replacing, as so:
ShapeContent.Copy
myPresentation.Slides(SlideIndex).Shapes(SlideShape).Delete
myPresentation.Slides(SlideIndex).Shapes.PasteSpecial DataType:=0


Get last distinct set of records

Question: I have a database table containing the following columns:
id   code   value   datetime   timestamp

In this table the only unique values reside in id i.e. primary key.
I want to retrieve the last distinct set of records in this table based on the datetime value. For example, let's say below is my table
id   code   value   datetime               timestamp
1    1023   23.56   2011-04-05 14:54:52    1234223421
2    1024   23.56   2011-04-05 14:55:52    1234223423
3    1025   23.56   2011-04-05 14:56:52    1234223424
4    1023   23.56   2011-04-05 14:57:52    1234223425
5    1025   23.56   2011-04-05 14:58:52    1234223426
6    1025   23.56   2011-04-05 14:59:52    1234223427
7    1024   23.56   2011-04-05 15:00:12    1234223428
8    1026   23.56   2011-04-05 15:01:14    1234223429
9    1025   23.56   2011-04-05 15:02:22    1234223430

I want to retrieve the records with IDs 4, 7, 8, and 9 i.e. the last set of records with distinct codes (based on datetime value). What I have highlighted is simply an example of what I'm trying to achieve, as this table is going to eventually contain millions of records, and hundreds of individual code values.
What SQL statement can I use to achieve this? I can't seem to get it done with a single SQL statement. My database is MySQL 5.
Answer: This should work for you.
 SELECT *
 FROM [tableName]
 WHERE id IN (SELECT MAX(id) FROM [tableName] GROUP BY code)

If id is AUTO_INCREMENT, there's no need to worry about the datetime which is far more expensive to compute, as the most recent datetime will also have the highest id.
Update: From a performance standpoint, make sure the id and code columns are indexed when dealing with a large number of records. If id is the primary key, this is built in, but you may need to add a non-clustered index covering code and id.
Comment: +1 for avoiding datetime testing if autoincrement... I took the liberty to reformat the answer.
Comment: @smdrager, Very Nice... saved my time.
Comment: I had to implement this into Eloquent ORM... worked first try, thank you
Comment: What If one did not have an ID column?
Comment: @trainoasis, then something like `SELECT * FROM [tableName] WHERE (code, timestamp) IN (SELECT code, MAX(timestamp) FROM [tableName] GROUP BY code)`
Answer: Try this:
SELECT *
  FROM <YOUR_TABLE>
 WHERE (code, datetime, timestamp) IN
 (
   SELECT code, MAX(datetime), MAX(timestamp)
     FROM <YOUR_TABLE>
    GROUP BY code
 )

Comment: @Krtek: Agreed, but that requires an assumption of the id being auto increment.
Comment: Since the table have a primary key, you don't have to do such a complicated where clause. see my answer.
Comment: not at all, smdrager answer does, the subquery in mine returns the good id to use because of the `having` clause
Answer: It's and old post, but testing @smdrager answer with large tables was very slow. My fix to this was using "inner join" instead of "where in".
SELECT *
 FROM [tableName] as t1
 INNER JOIN (SELECT MAX(id) as id FROM [tableName] GROUP BY code) as t2
 ON t1.id = t2.id

This worked really fast.
Comment: Thanks. I'll give it a try when next I need to use this.
Answer: I'll try something like this :
select * from table
where id in (
    select id
    from table
    group by code
    having datetime = max(datetime)
)

(disclaimer: this is not tested)
If the row with the bigger datetime also have the bigger id, the solution proposed by smdrager is quicker.
Answer: Looks like all existing answers suggest to do GROUP BY code on the whole table. When it's logically correct, in reality this query will go through the whole(!) table (use EXPLAIN to make sure). In my case, I have less than 500k of rows in the table and executing ...GROUP BY codetakes 0.3 seconds which is absolutely not acceptable.
However I can use knowledge of my data here (read as "show last comments for posts"):

I need to select just top-20 records
Amount of records with same code across last X records is relatively small (~uniform distribution of comments across posts, there are no "viral" post which got all the recent comments)
Total amount of records >> amount of available code's >> amount of "top" records you want to get

By experimenting with numbers I found out that I can always find 20 different code if I select just last 50 records. And in this case following query works (keeping in mind  @smdrager comment about high probability to use id instead of datetime)
SELECT id, code
FROM tablename
ORDER BY id DESC
LIMIT 50

Selecting just last 50 entries is super quick, because it doesn't need to check the whole table. And the rest is to select top-20 with distinct code out of those 50 entries.
Obviously, queries on the set of 50 (100, 500) elements are significantly faster than on the whole table with hundreds of thousands entries.
Raw SQL "Postprocessing"
SELECT MAX(id) as id, code FROM
    (SELECT id, code
     FROM tablename
     ORDER BY id DESC
     LIMIT 50) AS nested
GROUP BY code
ORDER BY id DESC
LIMIT 20

This will give you list of id's really quick and if you want to perform additional JOINs, put this query as yet another nested query and perform all joins on it.
Backend-side "Postprocessing"
And after that you need to process the data in your programming language to include to the final set only the records with distinct code.
Some kind of Python pseudocode:
records = select_simple_top_records(50)
added_codes = set()
top_records = []
for record in records:
    # If record for this code was already found before
    # Note: this is not optimal, better to use structure allowing O(1) search and insert
    if record['code'] in added_codes:
        continue
    # Save record
    top_records.append(record)
    added_codes.add(record['code'])
    # If we found all top-20 required, finish
    if len(top_records) >= 20:
        break

Comment: Hi Godfather, I actually have the same problem. I have an order table. Some items aren't popular and not being ordered often. How to ensure that these items (ie. ItemId) are included? I like your approach and hoping to use it.

Get last distinct set of records


Converting relative paths into absolute ones not working in JSoup

Question: I'm trying to access relative links (a[href]) in a webpage and replacing them into absolute ones, and printing the modified HTML of the webpage on the console. But, when I'm looking at the links after having run the program, no changes have been made. Here's my code:
        Document doc = null;

    try {
        doc = Jsoup.connect("http://jsoup.org/cookbook/extracting-data/dom-navigation").userAgent("Mozilla").get();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    Elements imports = doc.select("a[href]");
    String s = "";
    for (Element link : imports) {
        //System.out.println("\n"+link.attr("href"));
        //System.out.println(link.attr("abs:href"));

        if(link.attr("href").equalsIgnoreCase("/")){
            //Do nothing for now
        }
        else{
            s = doc.toString().replaceAll(link.attr("href"), link.attr("abs:href"));
        }
    }
    System.out.println(s);

One very strange thing is that, in this program, I'm connecting to http://jsoup.org/cookbook/extracting-data/dom-navigation but when I connect to this link http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html I notice that the changes are being made. So what could be the problem here, something wrong with my code or with the webpage?!
Answer: Please try <your element>.absUrl("href") instead. And for testing, print your result element directly after you have changed it.
For replacing the urls you can use something like (not tested):
Elements urls = doc.select("a[href]");

for( Element urlElement : urls )
{
    urlElement.attr("href", urlElement.absUrl("href"));
    System.out.println(urlElement); // Print result directly after changes have been done
}

Comment: Hey, this works! Actually, I was just printing each element to see if the changes were made individually (and yes, they were made), but on printing the whole html doc no changes were made whatsoever, and it was the whole modified html doc that I needed. That was really strange. Anyways, the code that you've provided, specially the `urlElement.attr("href", urlElement.absUrl("href"));` line, works perfectly. Thank you.
Comment: That's strange, it seems you work on a copy and not the actual document somewhere. Just for testing, you can try *replacing* such a node instead of changing it value.


With Chrome Apps soon to be removed, is there another way to edit a local file?

Question: The Chrome Apps API has the very useful FileSystem API which allows a user to select a file for an app to edit (read and write changes to). However, with the entire Apps API soon to be removed, what other ways exists to edit a file on the local file system?
This is not an opinion-based question, I am asking for all conceivable alternatives.
Comment: Possible duplicate of http://stackoverflow.com/questions/21912056/access-local-files-using-a-google-chrome-extension
Comment: Are you certain this API is being removed? 40 minutes ago it was "a rumor" in your other question. http://stackoverflow.com/questions/43924438/is-the-chrome-filesystem-app-api-deprecated
Comment: Is it not? That was until I realized that the apps were what was being deprecated, not the fileSystem api.
Comment: You should answer your other question with that information, then, with the reputable source you found to back it up.
Comment: Done! I would dearly love for that question to not distract from this question, since this question stands on its own two feet.
Comment: The answer to that question leads you to the answer to this question, via the [migration guide](https://developers.chrome.com/apps/migration). "Q: My app uses the chrome.fileSystem API to read and write user-specified files and / or directories. Can this be done on the open web?"
Answer: Per https://developers.chrome.com/apps/migration:

Q: My app uses the chrome.fileSystem API to read and write user-specified files and / or directories. Can this be done on the open web?
A: In general, no. The open web can read single files that the user opens, but cannot retain access to those files, write to those files, or have any access to directories.
If it is critical for your app to read and write directories (e.g. it is a text editor with a folder view), you will need to either have a native helper app and extension combo, or create a native app.


Image does not display on Pyqt

Question: I am using Pyqt5, python3.9, and windows 11. I am trying to add an image to my app but it wont display anything as show below.
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(531, 316)
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(70, 30, 491, 241))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap(":/newPrefix/download.png"))
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())][1]

My Application:

This is my qrc file:
<RCC>
  <qresource prefix="newPrefix">
    <file>download.png</file>
    <file>background.gif</file>
  </qresource>
</RCC>

And both the image and the main.py are in the same directory. Any idea why this does not work?
EDIT: The code seems to work on windows 10 but not on windows 11.
Answer: you should first use pyrcc5 and convert your qrc to .py :
for example, I do this :
pyrcc5 resourse.qrc -o logo_rc.py

then you should import it :
from PyQt5 import QtCore, QtGui, QtWidgets

import logo_rc

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(550, 600)
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(0, 0, 550, 600))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap(":/images/images/photos.png"))
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

this is my out put :

Image does not display on Pyqt


How to get export shapefile from spatialite database in android

Question: I'm working on a Mobile GIS android app. I want to get export ESRI Shapefiles from my Spatialite database when the user is offline. how can i do this? Is there any library which can help me?
Answer: In spatialite.h you can find this function:
SPATIALITE_DECLARE int dump_shapefile (sqlite3 * sqlite, char *table,
                   char *column, char *shp_path,
                   char *charset, char *geom_type,
                   int verbose, int *rows,
                   char *err_msg);

which is exactly what you are looking for.
However, you have to find an Android wrapper that supports that function (it may not be available). Another method is using GDAL for Android with spatialite driver to convert data to Shapefile: see how they did it in this utility included in geotools-android.
Comment: thank u very much. but how can i use that in android with android ndk. can u explain more.
Comment: I don't know how i should use ur answer.
Comment: i'm trying to use geotools in android but this [question](https://stackoverflow.com/questions/50323013/how-to-install-geotools-by-gradle-in-android-studio-3-1-2) says it's not possible. Can u show me a document to use geotools on android? thank u
Comment: You don't need GeoTools, I was just referencing an utility that does what you want. You just need [GDAL for Android](https://trac.osgeo.org/gdal/wiki/BuildingForAndroid)
Comment: I was trying to do that but i faced problems u can see my errors.https://stackoverflow.com/questions/50155150/ndk-build-undefined-reference-errror
Comment: I have a problem to building gdal on android


Reducing artificial rings in mean curvature of mesh

Question: I have an isosurface/mesh (generated via marching cubes) of a micro-CT scan. Originally the surface looks very noisy, which becomes prevalent when the mean curvature is visualized:

To reduce the noise I've applied Gaussian smoothing to the imagedata and regenerated the mesh. This time, artificial looking rings appear:

I would like to reduce these circles/rings/terracing artifacts to obtain a more smooth distribution of the curvature values.
I was wondering if anybody would know the name of this problem since I'm struggling to find anything similar online. All help is appreciated!
Comment: Try ray marching this with a high resolution (zoom into the problematic region). If the rings disappear you know it's the discretization. If they do not disappear, then it's a feature if your surface.
Comment: It's possible that it is something specific to marching cubes. Looks like aliasing or ringing.
Comment: I was thinking that too. So I ran Dual Marching Cubes and SurfaceNets on a voxelized sphere (also with Gaussian smoothing) but these rings kept appearing (although less apparent for SurfaceNets)
Answer: This is just an educated guess, but the artifacts in your visualization of the curvature values reminded me of Moiré patterns. The images in the Wikipedia article don't show circle patterns like the ones you are observing, but I have seen similar patterns before when I tried to visualize highly oscillating functions. (Edit: The function you are visualizing, i.e. the curvature, is likely not oscillating quickly. However, the following example still illustrates that it may not only be the discretization or mesh generation algorithm that is problematic, but also the computation of the curvature.)
For example, if you try to visualize the function $f(x,y) = |\cos((x^2+y^2)^2)|$ for $x$ and $y$ ranging from $-3.3$ to $3.3$ on a grid of $256\times 256$ pixels, what you get is the following image:

The Moiré patterns appear in this image since the function $f$ is only evaluated at a single point (x,y) for every pixel, although each pixel covers not just a single point but an area. A better visualization of the function $f$ would involve integrating over the corresponding area for each pixel, which would result in a uniform gray color near the image boundaries reduces the Moiré patterns.
My guess is that there is something similar happening in your situation. As for solving your problem, this essentially means that the curvature is computed in an erroneous way if the discretization is too coarse. So you could either try to improve the algorithm that is used for the computation of the curvature or simply use a finer discretization. Unless, of course, if the rings really are a feature of your surface, in which case they will not disappear as lightxbulb pointed out.
In case you are interested, I have attached the C++ code that I used to generate the above image. Note that if you increase X and Y while keeping lX and lY constant, the discretization is refined and the Moiré patterns will disappear.
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

using namespace std;

void WriteGrayscalePPM(const std::string& file, const std::vector<unsigned char>& values, const unsigned int X) {
  const unsigned int Y = values.size ( ) / X;

  std::ofstream image(file.c_str(), ios::out | ios::binary);
  image << "P6\n" << X << ' ' << Y << "\n255\n";
  for (unsigned int i=0; i<X*Y; i++) {
    unsigned char color[3] = {values[i], values[i], values[i]};
    image.write((const char*)color, 3*sizeof(char));
  }
}

int main(int argc, char **argv) {
  const int X = 256;
  const int Y = 256;
  const double lX = 3.3;
  const double lY = 3.3;

  std::vector<unsigned char> values(X*Y, 0);

  for (int y=0; y<Y; y++) for (int x=0; x<X; x++) {
    double xd = lX / (X/2) * (x - X/2);
    double yd = lY / (Y/2) * (y - Y/2);
    double d = sqrt(xd*xd + yd*yd);

    values[x + y*X] = 255*abs(cos(d*d*d*d));
  }

  WriteGrayscalePPM("moire.ppm", values, X);

  return 0;
}


The file casper/filesystem.squashfs is corrupt

Question: I tried burning Lubuntu 12.04 to a CD-RW with Xfburn and braseo, but it keeps be corrupted. I tried to check my hashes but:
<code>Lubuntu 12.04 i386$ md5sum -c md5sum.txt | grep -v "OK$"
md5sum: ./casper/filesystem.squashfs: Input/output error
./casper/filesystem.squashfs: FAILED open or read
md5sum: WARNING: 1 listed file could not be read
</code>
My disc has enough room. Also, the iso's checksum is fine.
<code>~/Desktop$ md5sum -c MD5SUMS.txt
md5sum: lubuntu-12.04-alternate-amd64+mac.iso: No such file or directory
lubuntu-12.04-alternate-amd64+mac.iso: FAILED open or read
md5sum: lubuntu-12.04-alternate-amd64.iso: No such file or directory
lubuntu-12.04-alternate-amd64.iso: FAILED open or read
md5sum: lubuntu-12.04-alternate-i386.iso: No such file or directory
lubuntu-12.04-alternate-i386.iso: FAILED open or read
md5sum: lubuntu-12.04-alternate-powerpc.iso: No such file or directory
lubuntu-12.04-alternate-powerpc.iso: FAILED open or read
md5sum: lubuntu-12.04-desktop-amd64+mac.iso: No such file or directory
lubuntu-12.04-desktop-amd64+mac.iso: FAILED open or read
md5sum: lubuntu-12.04-desktop-amd64.iso: No such file or directory
lubuntu-12.04-desktop-amd64.iso: FAILED open or read
lubuntu-12.04-desktop-i386.iso: OK <--------------------------------This is the file
md5sum: lubuntu-12.04-desktop-powerpc.iso: No such file or directory
lubuntu-12.04-desktop-powerpc.iso: FAILED open or read
md5sum: WARNING: 7 listed files could not be read
</code>
What is going on?
Answer: Input/output error is not uncommon at the very end of a CD.
(Caused often by write type "TAO", which creates two non-data blocks
at the end of the range, which the drive advertises as readable.
Aka "Read-ahead bug". Traditionally made harmless by 300 kB of padding.
It should not happen if you have chosen write type "SAO".)
Make sure that you try to read only as many bytes from the CD
as are stored in the original .iso image file.
The size of an ISO image is supposed to be integer divisible by 2048.
E.g. if your .iso file has a size of 4,581,523,456 bytes, then it
has 2,237,072 blocks. So use
dd if=/dev/sr0 bs=2048 count=2237072 | md5sum
(assuming your CD drive has address /dev/sr0)
When the reading is done (hopefully without i/o error), then
lookup the resulting MD5 checksum in your file "md5sums.txt".
E.g. "a87d2796b7acf90fbe48dcaeb27dc7cc"
Command line example for writing CD with write type SAO:
xorriso -as cdrecord -v /dev/sr0 -sao -eject lubuntu-12.04-desktop-i386.iso
The same option will also work with programs cdrecord or wodim,
instead of "xorriso -as cdrecord".
Comment: Actually, I think it was a disc scratch. I new CD-R fixed it.


One Vita = One PSN account, what about games?

Question: I know you about the relation 1 PS Vita = 1 PSN account = 1 memory card*
*Actually, you can swap accounts after restoring the device and all that...
What I am not so sure is if I can download Vita games from a secondary account in my PS3, and then send it to my Vita. In other words:
2 PSN accounts both linked in two PS3 >> Both PS3s can send games to Vita
I know it's a bit confusing but it's also hard as hell to explain. :S
Comment: As far as my research goes it is not possible to send games across accounts. But I have not found an official source.
The best options seems to be swapping accounts as you described with two memory cards.
Comment: So in essence you want to know how to send games from 2 different PS3s with different PSN accounts to your PS Vita?
Comment: Yes, or if it is even possible. I'm afraid if a game is linked to account A, it won't transfer to Vita linked with game B. But I wanted to confirm.
Answer: No. You can not do what you are hoping to do.
Only the PSN account on the PS3 that is also the PSN account signed into the Vita can send games to it. If you want to send games from the other PSN account you will need to wipe and reset the Vita to the other account first.


Is it possible to extend a namespace class with same class but different path in spl_autoload_registry

Question: I have two namespaced classes loaded with composer with the same namespace and class. (PSR4)
<code>//directory1/Foo/Bar.php
namespace Foo;

class Bar{
    ....
}
</code>
I have a second directory with the same namespace for overrides.
<code>//directory2/Foo/Bar.php
namespace Foo;

class Bar{
    ....
}
</code>
Now if I register both directory1 and directory2 as auto loaders directory2 will take priority over directory1.
With this method I can completely override classes via alternate directories.
When calling new Foo\Bar;
I will get an instance of directory2/Foo/Bar.php
If the file does not exit in the second directory I will get an instance of:
I will get an instance of directory1/Foo/Bar.php
This is great but I have a problem though.
Although I can do full overrides it seems to be impossible to extend classes set up in this way.
Is it possible for Bar found in directory2/Foo to extend Bar found in directory1/Foo since they share a namespace and class name?
Answer: I would strongly oppose the idea to let the autoloading decide which version of a class gets loaded.
If you create the same class twice, with possible differences between the two versions, any other programmer (including yourself after some time) will be confused which class really contains the correct code that is being used in your program.
Additionally, all IDEs that do a decent amount of code indexing and parsing will also get confused and signal that there are two possible classes that might be used.
Nobody will get any benefit from having exactly two different files with the exact same class name but differences in the code.
You didn't state which problem you want to get solved with this approach, but I think you should do! Autoloading should not play any role when solving object oriented programming problems.
Comment: I am implementing a theme for cakephp 3.0. The reason I want to do this is to allow themes to override controllers and cells and helpers for plugins. The controllers in cells should be rendered from the default location if no override is specified. Copying the files to the themes override directory works perfectly but it would be awesome if I was able to extend the class instead of replacing it. Because of the nature of what I am trying to accomplish it is impossible for me to rename the override class or name the original class something different. Just wanted to know if this is possible.
Comment: You just stated the topic of the real question you have. Don't ask about a technical detail about a questionable approach to solve the problem the way you want it. Ask about the more general problem you have with creating themes for CakePHP. If you add the right tags to your question, you likely will get answers from CakePHP experts that will tell you how to do it. :)
Comment: Thanks, I have had extensive conversations with the core developers of the framework on github surrounding templating and the surrounding conventions. The context of how I want to implement this is not really important, the question was one more fundamental to the nature of php and the working of the autoloaders. I knew this was likely impossible but felt it needed to be asked since I could not find any info relating to this topic after a lot of googling.


Does the filter operator behave differently when applied to an Observable created by from operator compared to when applied to a BehaviorSubject?

Question: I have defined variables person$ and source$ with two different approaches:
Approach 1: Defining person$ by using BehaviourSubject:
interface IPerson {
  name: string;
  age: number;
}

const person$ = new BehaviorSubject<IPerson[]>([
  { name: "amir", age: 20 },
  { name: "hosein", age: 10 },
]);

Approach 2: Defining variable using from operator:
const source$ =  from([
  { name: "amir", age: 20 },
  { name: "hosein", age: 10 }
]);

For finding person with age of less than 15, At first, I've  used filter operator as follows:
const filteredPerson$ = person$.pipe(
  filter((person) => person.age < 15),
  tap((person) => console.log("person", person)),
);

const observer1 = filteredPerson$.subscribe();

Using filter operator for variable person$ does not work.
But, using second approach, it works!.
const filtered$= source$.pipe(filter(person => person.age < 15));
const observer2= filtered$.subscribe(val => console.log(`${val.name}`));

Comment: Does this answer your question? [Angular filter Observable array](https://stackoverflow.com/questions/43430715/angular-filter-observable-array)
Comment: Thanks for paying attention. I have added more details about my question.
Answer: Behaviour subject, will emit an array( [ { name: "amir", age: 20 }, { name: "hosein", age: 10 }, ]) ), since an array is not an object, the filter condition will fail hence the entire result is filtered out!
while from takes an array and converts it into a stream of observables ( first { name: "amir", age: 20 }, then { name: "hosein", age: 10 } ) , emited one by one, so in this scenario, filter will receive a object and filter will work fine, since a single person will evalulated based on the condition

RxJs filter is used to filter out a observable stream not the data, the correct property to do this will be map since it will transform the response before reaching the subscribe! We use the javascript array filter operator to filter out the array values!
const filteredPerson$ = person$.pipe(
  map((persons) => persons.filter((person: any) => person.age < 5)),
  tap((person) => console.log("person", person)),
);

const observe1 = filteredPerson$.subscribe();

Comment: Thanks for your response. I've modified my question and provide further details.


TCL use "eq" or "==" when the argument can be a list or a string

Question: I have the following if loop:
if { expr { $Node_3 eq "BadAngle" } } {
  return "BadAngle"
}

Node_3 can be a list containing coordinates, or the simple string "BadAngle"
I use TCLPro 1.4 for debugging and TCL 8.6. I get:
*syntax error in expression " expr { $Node_3 eq "BadAngle" } "*
I then also tried:
if { [ expr { $Node_3 eq "BadAngle" ] == 1 } } {
   return "BadAngle"
}

But i get the same error.
Also: What is the better alternative in this case: To use "==" or "eq", I think "eq" because a list is a kind of a string..or?
Answer: You seem to be getting in a bit of a pickle there. Firstly, you probably don't want to use expr inside the if condition, so this will be enough:
if { $Node_3 eq "BadAngle" } {
    return "BadAngle"
}

Since one of the things you are comparing against is definitely non-numeric, you'll be fine using the eq operator though the == operator is equivalent. The only time there is a difference is when both operands look like numbers, when == will compare them as numbers (parsing them into numbers if necessary). This means that "1" == "0x01" despite them being rather different strings; the eq operator always compares as strings.
How to choose which is best? It's actually pretty easy: do you think you are working with numbers at this point on both sides of the comparison? If yes, use ==, and otherwise use eq.

The one time you want to use expr inside if is when you're dynamically selecting the operator. This is not really recommended, but you'd do it like this:
set op "=="
if { [expr {$Node_3} $op {"BadAngle"} ]} {
    return "BadAngle"
}

It's pretty ugly. (Notice that I put everything else inside its own braces to prevent double evaluation, and I'm careful with balancing all the brackets correctly, which is what was tripping you up in the code in your question.) Don't do it unless you really really need to.
Comment: Also, `Inf` and `NaN` are numeric (though the latter is probably going to be a checked error very soon afterwards; NaNs are weird stuff) according to both Tcl and IEEE floating point arithmetic.
Comment: Why would you use `if { [expr {$Node_3} $op {"BadAngle"} ]}` wouldn't `if "\$Node_3 $op {BadAngle}"` be slightly less ugly? Or is there a reason to stick to the curly braces around the condition at all cost?
Answer: You have two distinct problems in your attempts:

In the first example you're trying to call expr in a wrong way: if (and other commands which support conditions, such as while) use the same machinery to evaluate their condition the expr command does — to cite the manual:

The if command evaluates expr1 as an expression (in the same way that expr evaluates its argument).

Now that machinery sees a bare word "expr" and has no idea what to do with it.
There are two ways to fix the code:

Wrong way — properly call expr:
 if {[expr {$Node_3 eq "BadAngle"}]} { ... }

This is wrong because the nested call to expr is purely superficial.
Correct way — just drop unneeded expr:
 if {$Node_3 eq "BadAngle"} { ... }

In the second example you decided to make the situaton more complicated by introducing another boolean test (not needed as the eq and == operators already return a value of type boolean).  But in this case you forgot to put the closing curly brace, }, which performs grouping, for the code should have been
if { [ expr { $Node_3 eq "BadAngle" } ] == 1 } } { ... }

In any case the correct solution is to simply use
if {$Node_3 eq "BadAngle"} { ... }


Hide content dynamically with React

Question: I want to dynamically hide items when they are irrelevant.
This should only apply for tags with a "taglevel" above 1.
For example, if I click "books" it should only show "adventure" and "classic". It will hide the tag "blockbuster" as no "books" belong to "blockbuster".
This screenshot should make it clearer:

I thought I could do this by mapping booleans. Instead of passing a level and all of the categories you'll just pass a list of categories to display, then give that list in PhotoGallery for each level
I am open to any way of doing this.
I've put the code in this codepen:
http://codepen.io/yarnball/pen/GjwxQq
Here's a sample of where I take the tag level:
var PhotoGalleryLevel = React.createClass({
  render: function () {
    var getCategoriesForLevel = this.props.displayedCategories.some(function (tag) {
      return tag.taglevel === this.props.level;
    }.bind(this));

    /* Write method here that takes the level as an argument and returns the filtered list?*/
    /*displayedCategories={this.state.getCategoriesForLevel(1)}
    displayedCategories={this.getCategoriesForLevel(1)}
    */

    var filteredTags = this.props.tags.filter(function (tag) {
      return tag.taglevel === this.props.level;
    }.bind(this));
    var disabled = this.props.displayedCategories.some(function (tag) {
      return tag.taglevel === this.props.level;
    }.bind(this));
    return (

        {filteredTags.map(function (tag, index){
          return <PhotoGalleryButton key={index} tag={tag} selectTag={this.props.selectTag} disabled={disabled} />;
        }.bind(this))}

    );
  }
});

EG of JSON data:
   "title": "Into the Wild",
    "tag": [
        {
            "name": "Movie",
            "taglevel": 1,
            "id": 1
        },
        {
            "name": "Adventure",
            "taglevel": 2,
            "id": 30
        },
        {
            "name": "Classic",
            "taglevel": 1,
            "id": 2
        }
    ],
    "info": []
}

Answer: schneider here: http://codepen.io/anon/pen/EgOqwj?editors=0010
the idea is to generate new uniqueCategories every time you click on a tag:
this.setState({
      uniqueCategories: this.getUniqueCategories(PHOTODATA, newCategories),
      displayedCategories: newCategories,
    });

now you have getUniqueCategories function and I've added this:
(!display.length || !displayFiltered.length ||
  displayFiltered
    .some(function(t) {
        return arr.filter(function(tc) {
          return tc.taglevel === t.taglevel;
        })
        .some(function(tc) {
          return t.id === tc.id;
        });
    }))

its not clean but i've followed your pattern using filter and some functions
Comment: Thank you! Just a small change- for my actual code (I made changes for the codepen), My getInitialState would be handled differently. I'm using setState for my fetch of the API. Here's my example: http://dpaste.com/217R03B

Hide content dynamically with React


Django - HTTP Uploading of Multiple Images

Question: I looked at this question:
Uploading multiple files with Django
but it did not seem to help as I have issues regarding it:

I don't want to deal with flash sessions using SWF Upload and Uploadify because I need to do uploads that only authenticated users can do.
newforms are for older versions of django, I am using 1.3

Using Django, how can I have this HTML form structure:
<form enctype="multipart/form-data" action="." method="post">
 Image 1
 <input type="file" name="image[]" id="id_image_1" />

 Image 2
 <input type="file" name="image[]" id="id_image_2" />
</form>

and handle it using a view?
Answer: If you have a fixed number of filefields, you could simply define a form with enough filefields, or add filefields programatically in a form's constructor. See the Django docs on File Uploads.
If you want some sort of dynamic functionality (a la gmail's "add another file"), then you could define a formset using a form with a single filefield.  Display a single form initially and when you want to add another, use a little javascript to produce the new form and update the formset's management form.  There are a number of snippets floating around to help you do this, though they may need some tweaking.  See the Django docs on File Uploads and Formsets.
Another option may be to use a custom widget and field, though I have not reviewed or tried this.
On the off-chance you aren't aware, the name="image[]" scheme is PHP specific and has no special meaning in other languages, unless you reimplement it.
Answer: newforms is what the current forms were called before 1.0. Furthermore, if you got your form validated, http://docs.djangoproject.com/en/dev/topics/http/file-uploads/, you'll have your files as a list (tuple, probably, but sequence anyway) in request.FILES['image'], so just do:
if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
       for f in request.FILES['image']:
           handle_uploaded_file(f)

You'll have to write handle_uploaded_file yourself, the URL explains how


Is there a recognised record for Minesweeper on a Cell phone?

Question: Is there a current record for an expert game played on a touch screen cell phone and/or tablet?
I put up a 98 second expert game on my phone and I'm curious how good that is compared to the 'best'
Comment: @Schism - 'It doesn't exist' is actually a [valid answer](http://gaming.meta.stackexchange.com/a/8484/28182) - (while this meta is specific to Plot/Lore, the same reasoning applies here): *"If there is no answer at the moment, we can either leave it open to be potentially answered later or we can offer that as an answer and update if more information is later revealed."*
Comment: Seems like most of the world records are for PCs.  I don't know that anyone is tracking for tablet/phone devices - http://www.minesweeper.info/worldrecords/
Comment: I'm VTC but for a different reason. There is (afaik) no canonical competitive Minesweeper implementation for mobile--unlike desktop, which uses Minesweeper X--so even if such a stat was tracked, it would hardly be meaningful.
Answer: Unfortunately no, there doesn't appear to be any competitive listing of Minesweeper times as played on a mobile device. While many versions & clones of Minesweeper exist for many platforms, the competitive players appear to stick to desktop-PC versions.
In terms of world rankings, Authoritative Minesweeper is the most recognised source (in Western culture at least).

The ranking started in April 2000 and in October 2012 was accepted by Guinness World Records - Minesweeper Wiki: World Ranking History

You can check out some of the best times posted here.

So which versions of the game are used competitively? According to the Minesweeper Wiki, competitive Minesweeper is usually played on competitively-sanctioned clones of the original Minesweeper:

Programs
Most tournaments used official clones of minesweeper. Budapest 08 used Windows Vista because it was sponsored by Microsoft. Vienna 06/07/08, Budapest 07, Munich 10, UK 11 and Zurich 11 used Viennasweeper, which was not an official world ranking clone until 2008 but was given permission by the IMC to be used. Budapest 05/06 and Vienna 05 used Clone 0.96. Shanghai 07 used Clone 0.97, while all other tournaments used Clone 2007.

Whilst one of the tournaments listed above used the version of Minesweeper that came with Windows Vista, do note that Microsoft versions aren't allowed anymore:

Microsoft minesweeper is no longer allowed on the rankings except in special cases. There are many reasons. First, it uses a small number of boards that repeat. Players began using board cycles to play the same board multiple times. This is an example of Unfair Prior Knowledge. UPK is also a problem of Vista minesweeper, because you are allowed to play a game many times until you win.


Automatic tests of click events

Question: Clicks on certain DOM elements sents click events to Google Analytics, as URL requests like https://stats.g.doubleclick.net/r/collect?v=1&aip=1&t=dc&_r=3&tid=UA-1234567-2&cid=297722160.1523959944&jid=2028321276&_gid=1320758195.1530624077&gjid=12698493&_v=j68&z=1135539045
What tools/methods/workarounds are usual to automatically test click events - mainly their status code and content?
Answer: I am not 100% sure that I understand your question.  First think you should understand is that hits sent to google analytics are not validated they are send and forget.  Google analytics returns a gif thats it there is no way to know if the request was a success or a fail.
There is one way of debugging hits being sent to Google analytics in test before you actually release to production and thats the debug endpoint

https://www.google-analytics.com/debug/collect?v=1&aip=1&t=dc&_r=3&tid=UA-1234567-2&cid=297722160.1523959944&jid=2028321276&_gid=1320758195.1530624077&gjid=12698493&_v=j68&z=1135539045

sending your hit to the debug endpoint results in
{
  "hitParsingResult": [ {
    "valid": true,
    "parserMessage": [ {
      "messageType": "INFO",
      "description": "IP Address from this hit was anonymized to 126.96.36.199.",
      "messageCode": "VALUE_MODIFIED"
    } ],
    "hit": "/debug/collect?v=1\u0026aip=1\u0026t=dc\u0026_r=3\u0026tid=UA-1234567-2\u0026cid=297722160.1523959944\u0026jid=2028321276\u0026_gid=1320758195.1530624077\u0026gjid=12698493\u0026_v=j68\u0026z=1135539045"
  } ],
  "parserMessage": [ {
    "messageType": "INFO",
    "description": "Found 1 hit in the request."
  } ]
}

This hit was not actually sent to google analytics it was just test sent.  If you want to set up some kind of unit testing or atuomation testing of your hits your going to have to do that yourself using the debug endpoint
More info can be found here validating-hits
Comment: Could you explain, what kind of debug response what i get on using analytics_debug.js?
Comment: Its the same https://developers.google.com/analytics/devguides/collection/analyticsjs/debugging

Automatic tests of click events


No window-decorations when running Compiz without Sudo

Question: I am running a barebones install of Ubuntu Server 13.04, that I want to boot into a Kiosk like application. For testing, I am launching into X running just XTerm.
When I boot up, if I do sudo compiz& in my .xsession, everything comes up fine (my XTerm window has decorations). If I run just compiz&, I don't get any decorations (although compiz is listed as a running process).
Answer: As for the "sudo" issue there should never be any need to run compiz as root, since you already own the xterm... you are logged in right... lol.
But in some certain circumstances we need to break the rules, like running a gui app as super-user, in these cases sometimes our config files get written to as root, and then whist trying to run that as a normal user we get a borked screen, or bad output from our program. So first off I would check the file perms on you configs for compiz, and the like to be certain that they aren't owned by root now.
Just be advised that gui apps as super-user can be very dangerous, and could potentially bork your entire installation, if not handled with care!!!
As for decorations, try running compiz like this compiz ccp&
Comment: File permissions was the correct issue (`~/.config/compiz-1` was set to root). Thanks!


Not able to login through Multi Attribute when Email is enabled as username in wso2 Identity server

Question: I'm using Identity server version 6.1, Here if we enable email as username in wso2 identity server and enable multiattribute login, I'm not able to login through Mobile Number even after adding the mobile claim in Allowed Attribute Claim List under multi attribute login of Identity provider. Any help is highly appreciated.
Answer: The issue you have faced has been already reported in https://github.com/wso2/product-is/issues/14930
With the introduction of the MultiAttribute Login feature in the product, a user gets the flexibility over controlling username and configure any attribute as his preferred login identifier.
This feature cleared up the actual requirement of email as a username feature in previous IS versions where email is considered as an immutable attribute.
So without enabling email as username feature, as a workaround, you can configure email and mobile as login identifiers. You have to mark both claims as unique claims as well.
If you want to keep the user's username also as an email, change the regex pattern of username claim