need a special image slider with views

Question: Is there any module that works with views and slide images like the following image?

so far I've found about 13 image slider in Drupal but non of them does such thing.
Comment: This question appears to be off-topic because it is about implementing a functionality, or a layout seen in a site, for which only a screenshot is provided. See [Help Center](http://drupal.stackexchange.com/help/on-topic).
Comment: @Drupalist Don't forget, this is a **Q+A** site. It's not a support forum/suggestion engine. We specifically don't want this type of question here _because_ it's the PSD of your specific site. You're narrowing the scope so much that the question can only be useful to you, and not to future visitors, which goes against what the site is for. Please see the help center, where this type of question is specifically disallowed: _Implementing a functionality, or a layout seen in a site, for which only a screenshot or a site URL is provided_
Comment: No @Mołot this is the PSD of my a site I'm going to implement, that is why I'm looking for a module for it.
Comment: Ok @Clive got it.
Answer: you can achieve that by jCarousel module

This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
Comment: its Other releases download link background is yellow, are you sure there is no problem with it ?
Comment: I think so, I've used it one of my project and works well. Just see reported installs under project information.

need a special image slider with views


joomla component with jquery and ajax error response

Question: Without AJAX I would output errors to the user like so (usually in the controller):
JError::raiseWarning( 100, JText::_('COM_EXAMPLE_EXCEED_LIMIT') ); // or: jexit(JText::_('COM_EXAMPLE_EXCEED_LIMIT'));
//then redirect them back to component
JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_example'));

With AJAX you can't do this as it will just fail to parse whatever data your sending back (in my case json)
jQuery.ajax({
    url: "index.php?option=com_example&task=add",
    dataType: 'json',
    data: dataString,
    success: function(data){
    //do stuff
    }
});

Ideally I'd like to use JError::raiseWarning because it is nice and pretty. But not sure that is possible since that is server side and the response is coming client side? Any ideas?
Answer: You should be able to fill the element with the id system-message-container with your error message using Javascript. However it may fail depending on the template if it uses an override.
If you really need a message like from JError, you need to reload the page and generate it on serverside. But the point of AJAX is that you don't reload the page :-)
Also note that JError is depreceated. Use $app->enqueueMessage('message', 'type') instead.
Comment: Thanks for the tip. `system-message-container` is very good to know! I've decided to go with a JSON error message on success. Not the prettiest, but I don't think there really is an elegant way.


What is the big $O_p$ of the product between a $O_p(a_n)$ term and a uniformly bounded function?

Question: Suppose $\frac{1}{n}\sum_{i=1}^n \hat{\theta}_i^2 = O_p(a_n)$ and $||f(X)||_{\infty}$ is bounded.
What is the big $O_p$ of $\frac{1}{n}\sum_{i=1}^n (\hat{\theta}_i f(X_i))^2$?
The way I understand this is because $||f(X)||_{\infty}$ is bounded (i.e., uniformly bounded), then the square of $f(X)$ is bounded too. Therefore, $\frac{1}{n}\sum_{i=1}^n (\hat{\theta}_i f(X_i))^2$ should still be bounded in probability. But I'm not sure what exactly the $O_p$ is.
Answer: Let $F:=\|f(X)\|_\infty$, you have that
$$\left\vert\frac{1}{n}\sum_{i=1}^n (\hat{\theta}_i f(X_i))^2\right\vert \le F^2 \left\vert\frac{1}{n}\sum_{i=1}^n (\hat{\theta}_i)^2\right\vert $$
Hence, for any real number $M$ such that $\left(\frac{1}{n}\sum_{i=1}^n (\hat{\theta}_i)^2\right)/a_n $ is smaller than $M$ with probability greater than $1-\varepsilon$, it follows that $\left(\frac{1}{n}\sum_{i=1}^n (\hat{\theta}_if(X_i))^2\right)/a_n $ is smaller than $MF^2$ with probability greater than $1-\varepsilon$ as well.
In other terms, it follows from the definition that $\frac{1}{n}\sum_{i=1}^n (\hat{\theta}_if(X_i))^2$ is $O_p(a_n)$ as well.


How to add IPV4 range to unmanaged server

Question: I am really inexperienced with Linux and networking.
I bought an unmanaged dedicated server running ubuntu 16.04. I am having problems with binding the ipv4/24 range with my dedicated server. How would I bind/add my IP range to my dedicated server?
Comment: Hate to say - by paying someone who HAS read all the docs. This quesiton will not solve a lot of followup questions magically. We only deal where with people that read the basic docs AND know how to provide all relevant information - for normal users, superuser.com is more likely to be the right palce. As per site rules. Note that you may be over your head with an unmanaged server, and the results of that are generally a hacked server.
Answer:
TomTom point has a lot of merit. Do consider seriously educating yourself on network management, or pay someone to do that for you. That being said, I'm all for people working through their problems towards proficiency, and using Server Fault to help with that, and messing with an unmanaged server is a great way to do that - just take into account that you will get into a lot of trouble.
Ubuntu 16.04 is pretty old is will go out of support next year. It is a Long Term Support release, but LTS in Ubuntu means 5 years. It would have been much better to start with a new 20.04 LTS installation, or even an 18.04 (giving you 3 years to figure it out before you have to upgrade). The fact that you got a new server with 16.04 is troubling - I would suggest you consider switching providers.
Make sure your provider is routing IPv4 range your bought to your server - this is out of your control and often where the line breaks. If you think you configured everything correctly and it still doesn't work - give your provider's support a call.
To set up the network interface, you'd want to add an entry to /etc/network/interfaces or create a new file with the entry in /etc/network/interfaces.d. See man interfaces for the full documentation or this article for a simple example.

You start by figure out your interface name - this should be easy by running ip a and find the correct interface, probably by looking for the other IP addresses that are supposed to already be attached to the correct interface. It should look like ens<number>.
As you are adding an additional IP address in addition to the existing one, you'd need to add an "alias interface" - think of it like a virtual interface card - it is bound to the same hardware but has additional configuration.
Then create the interface alias file (or edit the interfaces file) like in this example - I'm assuming the interface is named ens5 and it will take the IP address 192.168.1.1, and it will be the first alias:
iface ens5:1 inet static
  address 192.168.1.1
  netmask 255.255.255.0
  gateway 192.168.1.254

If you want to add more IP addresses to the same interface, you'd need to increment the alias ID - the part after the : in the interface name - for each new address.
Comment: Thank you for your reply! But I have a problem I searched up online and I did edit `etc/network/interfaces` and added another interface called enp1s0f0:0 then I inputted my IP address on there but it still didn't work. Do you have a clue on what I might be doing wrong?
Comment: After editing the file you need to get it to load. The easiest way would be to restart the server. Did you do that?
Comment: Yes I did but it still didn't work


How can I dismiss a UIPopoverController without knowing the reference of it?

Question: As what I said above. I encountered a problem that I have to dismiss the popover on screen while I don't know where it come from.
What I want to do is : when the app become inactive, I want to dismiss the popover. But I don't know where the popover is presented, and which controller is responds to it?
Is there a notification which I could listen to when the UIPopover is presented?
Or can I find the Popover on the screen?
Thank you guys.
Comment: This SO Question might answer: http://stackoverflow.com/a/2687793/111823
Comment: You can check this SO question: http://stackoverflow.com/questions/6693837/how-to-dismiss-uiactionsheets-and-uipopovercontrollers-without-knowing-who-prese
Answer: Just subclass your own implementation of UIPopoverController and overridepresentPopoverFromRect:inView:permittedArrowDirections:animated and presentPopoverFromBarButtonItem:permittedArrowDirections:animated and keep track of popover references in a global array. Since Apple's HIG says only one popover is allowed at a time on screen, you only need to track the last one.
Comment: Thank you for your answer, that will be a good solution for my problem , and when you mentioned "keep track of popover references", did you mean post a notification ? btw, if I need to subclass UIPopoverController, I have to change all class and have to tell others to use my subclass instead of the official class.


Is it out if the batsman loses his bat on reaching crease and a run-out is effected at the same moment?

Question: There are two scenarios in question here:

Batsman extends and drags his bat to inside the crease. But just as he dragged in, he lost the bat from his hands and his whole body is still outside the crease. Fielder seizes the moment and tries to effect a run out.
Batsman extends and drags his bat to inside the crease. He now wants to go for the next run, and just as he is about to leave the crease to do that, he loses the bat from his hands and his whole body is still outside the crease. Fielder seizes the moment and tries to effect a run out.

Is it OUT/NOT OUT in either/both the cases?
One thing I know here for sure is that the new 'bouncing bat rule' is not applicable here, because there is no contact with the bat and hands here.
Answer: The batsman is Out, run out in both cases.
In the first they have not made their ground as the bat is dropped before they have made their ground. In the second they have deliberately left it in order to continue running.
This can be determined using the conditions laid out in Law 30, Batsman out of his/her ground, and the remainder of Law 38, Run out.
Comment: Thanks. Can you give the reference to the relevant rule here? Also, in the first scenario, please note that the batsman had made his ground for a brief time, which is the cause of my confusion.
Comment: The first scenario describes a batsman losing the bat as they are entering the crease, which suggests they have not made their ground first before dropping it. If they have made their ground and then dropped it, this is a different scenario. Please clarify the question.


Probability: What is the best strategy for multiple choice game scenario?

Question: Here is the scenario:

Each day you get to chose 1 box out of 3 total boxes.
1 out of those 3 boxes has a rare item, the other 2 boxes have a common item.
You get to choose 1 box per day (give the constraints above) for 7 days.
Note that each day the position of the rare item is randomized.
Total items in boxes: 21 (7 rare, 14 common).
You get a total of 7 items (rarity determined by random selection)

What is the best strategy to obtain a rare item from this game?
(if possible, show the "math" for it)
I think it is best to pick the same box every day, but I'm not sure how to explain why I think that.
Thanks for your help.
Comment: In the scenario that you are describing, it is impossible to come up with a strategy that is better than any other strategy.
Comment: Could you explain why? It seems to me that if you pick the same box each day you would have a better opportunity. Like with the Money Hall problem there is a strategy... http://en.wikipedia.org/wiki/Monty_Hall_problem
Comment: The Monty Hall problem is a very specific problem, which is why the strategy applies. The way your problem is defined, the strategy 1231231 has exactly the same chance for successes as the strategy 1111111.
Comment: example: if you pick the same box every day (say box 1), then you get 1 in 3 odds each day, but 7 in 21 over all, whereas if you pick a different box each day, you still get 1 in 3 odds each day, but 7 in 63 overall. I'm sure I'm figuring that wrong, but perhaps you could help me understand why I'm wrong? Is it really just 1 in 3 odds period?
Comment: Another thought that to me is similar is with multiple choice tests. I was once told (not that I believe everything I'm told) that if you must guess on a large number of questions on a multiple choice test (say your an out of time on an ACT section, where you are rewarded for correct answers, but not punished for incorrect answers) that it is best to select the same answer (say C) for each... Maybe that's where I'm getting the idea that picking the same box (in the OP scenario)?
Answer: If you pick the same box every day, your chance of success all seven times is $\frac{1}{3^7}$. You have the same chance if you pick a difference box each day, as the results are independent.
To simplify this, take the base case: 2 days, 2 boxes. Your possible configurations are:
<code>RC, RC
RC, CR
CR, RC
CR, CR
</code>
On any given day, the probability of you getting a rare from this configuration is 1/2 for any given box. Therefore, the probability of getting at least one rare in two days is 3/4 regardless of which box you choose.
Comment: Thank you for your help on this. I appreciate it.
Answer: I agree with everything @mason and @Jonathan are saying.
To address your idea about choosing the same box (or same question in a multiple choice).

Suppose that you decide to choose the 1st box every time. Now I think we can agree that the chances of a RARE item is $\frac{1}{3}$.
Now on day two you stick with your strategy and decide to pick box 1. Now according to your description of the problem, the RARE item is randomized each day, so the probability of there being a rare item in box one is still $\frac{1}{3}$. Now if your chances are worse by picking box two or three, then their probabilites $\underline{must\:be\: less\;than\: \frac{1}{3}}$. For simplicity suppose the chances of a RARE in boxes two and three is $\frac{1}{4}$ But then the probability of getting a rare item if I opened all three boxes would be less than 1 $(\frac{1}{3} + \frac{1}{4} + \frac{1}{4} = \frac{10}{12} \ne 1)$! This would violate some of the laws of probability (as well as the condition that each day there is a RARE item among the three boxes).
Hence either the probability is 1/3 for each box each day, or some rule in the problem you described has been broken!
Comment: Thank you. That makes sense as well. I see that the chances are 1/3 no matter what... I think that I must have been swept away with the "law of averages" (yeah, I know it's bad and especially with a small sample size)... you know, thinking that if I picked the same box every time that it would somehow work out in my favor since if the odds are 1/3 it would have to hit at least 2 - 3 times...
Answer: The main question has been ably dealt with by (at this time) Jonathan Rich and FAS.
OP, in the comments, brought up the question of strategy in a multiple choice test, if one is essentially out of time and has to guess. For concreteness let us assume there are $30$ questions, with $3$ choices on each question, a), b), and c), only $1$ of which is correct.
Imagine that the teacher made sure that a) was always the correct answer, and then used a good randomizing device to scramble the labels of each choice. Then we are back at the "rare item" question of the OP, and conclude that there is no strategy available to the student.
But possibly the teacher wanted all correct answers to appear exactly $10$ times.
Then if we guess a) each time, we will get exactly $10$ right.
If we randomize our guesses, using a fair die each time to make the decision, then on any question our probability of being right is $1/3$. It turns out that the mean number of correct answers will be $10$, precisely the same as if we guess a) each time. But the variance will be much greater. If the passing mark is $15$, then ticking a) each time leads to a sure fail. A randomized strategy, by contrast, gives a reasonable shot at passing, at the cost of a significant probability of getting a very low mark.
People making up tests get nervous about having consecutive correct choices be the same. Perhaps one could exploit that nervousness and devise improved guessing strategies. One would need data.
Comment: @mason81: I once met a teacher who told me she had been bubbling all day. It took a while for my overheated imagination to understand the prosaic reality.
Comment: Very interesting. I appreciate your answer and this information.
Comment: You are welcome. I thought it might be fun to think about multiple choice test strategies, where a lot more is going on than in the game scenario you described.
Comment: yeah, no doubt. the human element makes for quite an interesting factor. talking about this almost makes me miss those old scantron answer sheets from high school... almost... :)


Could a good sound be had from small output amps?

Question: I'm wondering if it is OK to instead of having your guitar go through a high wattage amp that fills the arena up by itself rather have a small tube amp set to full blast and then maybe set it up and send it through a PA system or other cabs?
Could you still have a decent sound if you do this or will it sound weak?
Comment: 1970, build a bigger amp. 1995 onwards, use whatever you like & mic it up.
Comment: You can only rely on the sound guy/gal if you brought them with you. A small wattage amp cranked does  not sound like a 50 or 100 watt amp. The transformers aren't as big. Plus you will have no true clean sound. The loudness of an amp has more to do with speaker SPL than wattage.
Comment: Neil Young has for years used a (~15W) tweed Fender Deluxe, and I doubt anyone would accuse him of a weak sound!
Comment: ...and… the sound guy will love you if he's in charge of your mix level, not you ;)
Comment: But will it still sound good? As I understand it tube amps become tremendous when cranked fully.
Comment: It will generally sound better over the PA than it would if you tried to just crank the level from the backline with a bigger amp. Pick your amp, choose your sound, leave the rest to the engineer.
Answer: Absolutely - use a smaller amp and mic it up. Check out pretty much any rock band these days. Sure, some will use the classic Wall of Marshalls (with one or 2 mic'ed up) at big venues, but the majority now use relatively small amps - often between 50 and 150 watts, and have these mic'ed into the PA desk.
This makes it very easy to define your on-stage sound, and gives the sound engineer the flexibility he needs to take that good sound and project it out through the PA.
If you use massive amps, it can be very difficult to tailor your sound to work in different venues, whereas a 50 Watt Marshall can be set to your liking for breakup and overdrive in even small venues.
Comment: Actually, chances are, the "Wall of Marshalls" is actually a "Wall of empty Marshall cabinets with a single cabinet behind the stage micd up".
Comment: As a sound engineer, I can definitely attest to the "the smaller the amp, the bigger the sound" mantra.


Scalar curvature of metric?

Question: The metric components in a two-dimensional spacetime are given in terms of the coordinates $(t, x)$ by$$ds^2 = f(x)\,dt^2 + dx^2.$$What is the scalar curvature, $R$, of this metric?
Comment: I know what a metric is, but I'm unclear what "metric components" are.  Is this a term used by theoretical physicists?
Answer: Define the orthonormal basis
$$ e^0 = f \, dt, \quad e^1 = dx. $$
Then
$$ de^0 = \frac{f'}{f} e^1 \wedge e^0, \quad de^1 = 0. $$
Cartan's first structural equation,
$$ de^i = -\omega^i{}_j \wedge e^j, $$
implies that
$$ \omega^0{}_1 = \frac{f'}{f} e^0, $$
which by antisymmetry is effectively the only nonzero curvature form in two dimensions.
The second structural equation is
$$ \Theta^i{}_j = \frac{1}{2} R^i{}_{jkl} e^i \wedge e^j = d\omega^i{}_j + \omega^i{}_k \wedge \omega^k{}_j, $$
and the second term on the right-hand side vanishes in two dimensions because there aren't enough dimensions for the indices $i,j,k$ to be distinct.
Then,
$$ \Theta^0{}_1 = d\left( f' dt \right) = f'' dx \wedge dt = \frac{f''}{f} e^1 \wedge e^0, $$
so
$$ R^0{}_{110} = \frac{f''}{f}, $$
or
$$ R^1{}_{010}=-\frac{f''}{f} $$
in the more useful form, and the Ricci tensor is thus
$$ R_{11}=R_{22}=-\frac{f''}{f}, $$
and summing gives
$$ R=\frac{2f''}{f}. $$
This is by far the quickest way I know to calculate curvatures, especially in two dimensions when the extra wedge term is not present.
Comment: Is there a factor of $f$ or $\sqrt{f}$ missing?  It does not seem clear to me that $e^0$ is unit in this way.

Scalar curvature of metric?


Could anyone suggest a Drupal database versionning tool?

Question:
Possible Duplicate:
How do I manage collaborative development on a Drupal site?

Is there any Drupal database version like GIT for versionning files ? with drush or any thing else ?
I've already used features module but it doesn't cover all needs in database versionning to get back to one saved version of the project.
The real point is to get drupal usable by many "site builders" and can manage conflict. on some features
Thanks. :)
Answer: I think the Backup and Migrate module will help you. Here is a quote about it (from the module's project page):

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.
Comment: I've edited the question, does "backup and migrate" covers conflict management ?
Answer: What exactly are you missing?
Features combined with Strongarm will do a pretty good job.
Comment: If I dive in to this solution, is there an important amount of job to do to get this work?
Comment: yes. you would have to define in your features which site specific database variables you would like to version and add those to your feature like you would have added any other component.


How to place overlay over image using JQuery?

Question: Desired Effect: An image (and only the image) should darken when a user hovers over it.
Plan: Use .mouseenter with JQuery to implement the desired effect.
Problem: When a user hovers over image, the overlay applies to something else (#Bars), despite using the same selector for both .mouseenter and also for appending the overlay. So the overlay works properly, but it isn't applying to the image. I tested the overlay by appending it to the body, and this does work (that is, when I hover over the image, the entire body of the webpage darkens). I even tested it on the nav bar, and once again, it works (when I hover over the image, the nav bar darkens). Unfortunately, the one thing that I want to append it to, the image, doesn't work.
Attempted Solutions: I've added IDs to ul, li, a, and the img, and I have tried selecting several combinations of these, but nothing has worked. I've also tried adding a high z-index in the CSS to #overlay, just in case it was lower than the picture. This didn't work.
Question: Which selector should I use to achieve the desired effect?
html.erb

<%= link_to(image_tag("bar1.jpg", id: "bar1image"), bar1_path, id: "bar1") %>

<%= link_to(image_tag("bar2.jpg", id: "bar2image"), bar2_path, id: "bar2") %>

JQuery
$(document).ready(function(){
    var $overlay = $('

');
    $("li#bar1photo a")
        .mouseenter(function(){

            $("li#bar1photo a").append($overlay.show());

        })
        .mouseleave(function(){
            $overlay.hide();
        });
});

CSS
#overlay {
    background: rgba(0,0,0, 0.75);
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    display: none;
}

Comment: Is there any reason you cannot add the overlay element to the HTML directly instead of using jQuery? You could do something like this and skip the jQuery: http://jsfiddle.net/pu0k2bf9/.
Answer: The parent need a relative position.
.barphoto {
 position: relative;
}

Demo here.
Answer: i whould do somthing like that:
$("li#bar1photo a").on('mouseover',function(){
  $(this).parent("li").addClass('overlay');
});

and the css somthing like that:
.overlay {
     position: absolute;
     top: 0;
     right: 0;
     width: 100%;
     height: 100%;
     background-color: rgba(0,0,0, 0.75);
}

Comment: Your jQuery adds a class to the `li` element which already has a class `.barphoto` the OP could hook into. The code you have supplied adds styles to the `li`which will not provide the overlay effect.
Comment: what's OP mean?... there is no problem to add more then one class to element... i figured from the question that the li holding the image as background-image isn't it?
Comment: OP = `Original Poster` = the person who asked the question. Of course you can have more than one class on an element. Creating a utility class can be useful as I believe that was part of what you were suggesting in your answer but the OP wants an overlay that will effectively darken the image when it is hovered. Changing the background of the `li` will not darken the image when hovered.


using Xcode 10 for python, gets a launch error

Question: I want to use Xcode to create python applications and I am testing it and every time I want to run the project I get the following error:

There is a problem launching using posix_spawn (error code: 8).

And Xcode also said build succeeded.
what can I do to resolve this problem?
Comment: If you want an answer, you need to update your question with more detailed information on how you set up the project. What type of Xcode project did you create? What files did you add to the project? How do you set up the project to use the Python interpreter? What is your code that calls posix_spawn? How do you run the project? Keep in mind that Xcode is not a good IDE for developing Python programs. You would be better off using a text editor like Visual Studio Code, BBEdit, or TextMate to write your Python programs.
Comment: Ok thx,Actually I just wanted to post that I fixed it by reseting some Xcode features.
Comment: Add an answer with what you did to fix the error to help someone who has this problem in the future.
Answer: try change executable interpreter to /usr/bin/pythonw


Exibir zero a esquerda usando o método ToString

Question: Tenho mais ou menos o seguinte código implementado em c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Teste
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(0134.ToString());
        }
    }
}

Mas ele não exibe o int 0134 todo:

O 0 a esquerda não está aparecendo.
Comment: Ja tentou "0134".ToString()?
Comment: Funciona mas queria converter int
Answer: 0134.ToString("D4");
Dessa forma de algum modo deve passar quantos elementos existem no integer, se por exemplo sua integer for 00134, não apareceria o primeiro elemento, seria necessário alterar D4 para D5
Comment: Obrigado funcionou.
Comment: Pode ver uma lista completa de parâmetros [aqui](https://msdn.microsoft.com/pt-br/library/dwhawy9k(v=vs.110).aspx)
Answer: Forma Abreviada (Padrão)
Formato: .ToString("D[n]") ou .ToString("d[n]")
O n é opcional e quer dizer o tamanho da string, e caso o número não atinja o tamanho definido a string é completada com 0 a esquerda.
Ex:
  123.ToString("D");  //-> Saída: "123"
  123.ToString("D1"); //-> Saída: "123"
  123.ToString("D2"); //-> Saída: "123"
  123.ToString("D3"); //-> Saída: "123"
  123.ToString("D4"); //-> Saída: "0123"
  123.ToString("D5"); //-> Saída: "00123"

Fonte | MSDN

Forma Explícita (Personalizada)
Há também a forma explícita, que é mais flexível e que dá para fazer a mesma coisa do que a forma abreviada.
Ex:
123.ToString("00000"); //-> Saída: "00123"
123.ToString("000");   //-> Saída: "123"
123.ToString("0-0-0"); //-> Saída: "1-2-3";
123.ToString("0-0");   //-> Saída: "12-0";

Fonte | MSDN


Settle a bet: Errors in prediction / regression

Question: In my work, I am comparing "predicted" values to "theoretically true" values. To calculate one predicted value, I take some $N_{R_i}$ samples from an area in space, $R_i$ (i.e. the samples are from different locations in a region). I do some calculations on the samples to calculate a predicted value for each sample. Then I average the predictions to calculate an average predicted value for the region. There are around 10 regions in total, so 10 predicted values.
The theoretically true values are back-calculated using a very different methodology. Theoretically true values are only available many years after the original samples are taken (that's why we bother to make predictions). There can only be one theoretically true value per region $R_i$. That's why I averaged samples from within each region to compare to the single theoretically true value per region.
I hope you are with me so far.
So, what I have is a small data set of about 10 predicted and "true" values. The correlation between them is strong.
Now, what if we expand into a new region? I can take some new samples and make a prediction for that region.
I want to know how to calculate the uncertainty in my prediction.
I think I am after "Uncertainty in the mean" since my prediction is an average of $n$ samples.
$$
SE_x=\frac{s}{\sqrt{n}}
$$
So, I think I can say that if I calculate a predicted value, $x$, there is a 68% chance for the "true value" to be within 1 $SE_x$ of $x$. Is this correct?
My colleague thinks we should be interested in the standard error for a predicted value:
$$
s_{y_p}=s^2_e\bigg(1+\frac{1}{n}+\frac{(x-\overline{x})^2}{\sum(x-\overline{x})^2}\bigg)
$$
(she found that equation here: http://courses.ncssm.edu/math/Talks/PDFS/Standard%20Errors%20for%20Regression%20Equations.pdf)
Who is right? Or maybe a better question is: what will the 2nd formula give me that the first will not?
Comment: The second formula takes into account that a difference between the sample slope and the population slope will have its biggest impact on predictions based on X values very far from the mean of X.
Answer: Let's start with:

So, I think I can say that if I calculate a predicted value, x, there is a 68% chance for the "true value" to be within 1 $SE_x$ of x. Is this correct?

No, that is not correct unless you were using Bayesian analysis.  There is either a zero percent or a one hundred percent chance the true value is in the region.  There is no way to tell.  Confidence intervals are not measures of the precision of your work.  They do not measure uncertainty regarding the parameter.  It is tied to the role chance plays in the sampling distribution.
What they do tell you is that if you were to perform the experiment an infinite number of times, then at least 68% of those experiments would contain the true value of the parameter within $\pm{1}SE.$  They provide no probability that the data is inside an interval.  There are an infinite number of intervals for any given $\alpha$ level of confidence.  There isn't just the one you gave.  There are other ways that are also standard to construct error bars, such as nonparametric ones.
Your colleague is correct if the conditions of linearity, independent errors, normal errors, and homoscedasticity are met along with the requirement that the prediction is inside the valid set allowed in the scientific model.  If not, then it is the wrong form for the predictive interval.
Obviously, the predictive interval is far wider than the confidence interval.  It contains both the impact of chance on your parameter estimate plus the effect of chance in nature itself.  Nature doesn't know you made a prediction.
There is a chapter in Decision Theory: Principles and Approaches by Giovanni Parmigiani on scoring rules for predictions.  It is generic rather than applied though.  If you were looking for "give me the formula to plug in," then this is the wrong book.  The lecture you attached provides a discussion of predictions.
As to your question, "I want to know how to calculate the uncertainty in my prediction," then you need to use a Bayesian method.  Bayesian methods are built around uncertainty, Frequentist methods are built around chance.  They are subtly different things.  In Pearson-Neyman methods, the null hypothesis and the sample space drive the math.  In Bayesian methods, information and a model of nature drive the math.
Rather than just switch to Bayesian analysis, however,  I recommend you learn a bit about both and ask yourself what you really want to know.  They provide different things using the same data.  They are not two different ways to solve a problem, they solve two different problems.
There is a good discussion, here on Stack Exchange, on the difference between Bayesian and Frequentist intervals.  It is at What's the difference between a confidence interval and a credible interval?
It may provide you with some clarity with what you really want to ask and know, and the limits of what either method can provide.
Comment: +1. [Here](http://jakevdp.github.io/blog/2014/06/06/frequentism-and-bayesianism-2-when-results-differ/) is an article by Jake VanderPlas that has examples of the frequentist and Bayesian approaches to solving different kinds of statistical problems, including regression.
Answer: As Dave Harris pointed out, you're wrong to think that there's a 68% chance the true value lies in the interval. Aside from that, I think you're interested in the standard error of the mean for your problem. The difference in the two equations, put basically, is that the standard error of the mean is an estimate of the variability in the distribution of the sample mean. So you collect a sample and record the mean, but you could have collected any number of different samples with different recorded means. What's the variability in those means?
In contrast, the standard error for a predicted value would be an estimate of the variability in trying to predict a particular element in the population. Put another way, you've recorded your mean from your sample. How much uncertainty is there in predicting a new value with that mean.
Mathematically, it's the difference between VAR($\hat{\mu}$) and VAR($y* - \hat{\mu}$). The former only includes the variability of of the sample mean. The latter includes that and the variability in y.


.NET Core parâmetro JSON

Question: Eu estou começando a aprender C#, usando .NET CORE, e estou tentando criar uma API que realiza buscas em um banco MongoDB.
Já procurei em alguns tópicos aqui, vi algumas coisas, mas nenhuma das soluções que encontrei funcionou.
Eu criei uma classe chamada SearchParameter para poder receber os parâmetros de busca, porém quando tento realizar a mesma no Insominia ele retorna o seguinte:

Não consigo entender o que está havendo. Seguem as classes.
SearchParametrs:
public class SearchParameters
{
    // Propriedes

    [Required(ErrorMessage = "É necessário informar um parâmetro de busca.")]
    [JsonProperty("ticketField")]
    public string ticketField { get; set; } // representa o campo do ticket que será utilizado para busca.

    [Required(ErrorMessage = "É necessário informar um parâmetro de comparação.")]
    [JsonProperty("comparationParameter")]
    public string comparationParameter { get; set; } // representa o parâmetro de comparação, se o valor a ser buscado é IGUAL ou DIFERENTE do ticketField.

    [JsonProperty("initialDate")]
    public DateTime initialDate { get; set; } // representa a data incial de um período a ser pequisado.

    [JsonProperty("finalDate")]
    public DateTime finalDate { get; set; } // representa a data final de um período a ser pesquisado.
}

Inicio do CONTROLLER, que define a rota:
[ApiController]
[Route("v1/archivedTickets")]
public class ArchivedTicketsController : ControllerBase
{...}

Método GET do CONTROLLER:
[HttpGet]
    [Route("getByChannelName/{searchParameters}")]
    public IActionResult getByChannelName(SearchParameters searchParameters)
    {
        try
        {
            return Ok(_repository.GetByChannelName(searchParameters));
        }
        catch (Exception exc)
        {
            return null;
        }
    }

Método que realiza a busca no REPOSITÓRIO:
public List<ArchivedTicketsModel> GetByChannelName(SearchParameters searchParameters)
    {
        return _collection.Find(archivedTicket => archivedTicket.ChannelName == searchParameters.ticketField && archivedTicket.DateCreation >= searchParameters.initialDate && archivedTicket.DateCreation <= searchParameters.finalDate).ToList();

    }

Eu coloquei um breakpoint na classe do CONTROLLER para debugar, mas o Insominia retorna essa mensagem sem nem ao menos entrar no método GET.
Estou testando em um localhost, que é a minha base_url. Já tem receber os parâmetros de forma separada, e deu certo, mas o objeto JSON não vai, e eu quero receber esse objeto como parâmetro.
Answer: Quando você define a sua rota dessa forma
[Route("getByChannelName/{searchParameters}")]

O seu método está esperando receber um parâmetro único.
Você definiu o seu método como HTTP/GET, por padrão ele não verifica o que está no corpo da requisição para preencher sua classe de parâmetro.
O que você pode fazer é informa-lo que você está esperando um objeto que está no body.
public IActionResult getByChannelName([Microsoft.AspNetCore.Mvc.FromBody]SearchParameters searchParameters)

Dessa forma, não é necessário passar na rota, ficando apenas
[Route("getByChannelName")]

Comment: Deu certinho! Muito obrigado pela ajuda!!

.NET Core parâmetro JSON


What is the best way to use a 2-class classifier for a multi-category case?

Question: I have a 3 class sample labeled data set, which I have divided into 2 parts. I am using the first part to train the two-class perceptron classifier.
One approach is to train $\binom{3}{2}$ two-class classifiers on training data for two classes at a time, and then use voting to classify the test samples for a multi-category case.
The obvious problem with the above approach is the presence of ambiguous regions like the ones shown in the image below:

Pattern classification by Duda, Hart, Stork suggests training $c$ different linear discriminant functions, where $c$ is the number of unique classes, such that
$$g_{i}(x) = W_{i}^tX + w_{i0} \quad \quad \quad  i = 1,..., c$$
and assigning $X$ to $\omega_{i}$ if $g_{i}(X) > g_{j}(X)$. The resulting classifier is called in the text book as a linear machine.
Following is an illustration from the book showing decision boundary produced by a linear machine for 3-class problem.

My doubt is how is the training process of the $c$ linear discriminant functions $g_{i}(X)$ different from training of $\binom{c}{2}$ 2-class classifiers?
UPDATE: The one vs rest approach mentioned in DavidDLewis's answer is not the one I am referring to. With the one vs rest approach, there are infact even more ambiguous regions. I am referring to linear machine classifier using which there are no ambiguous regions.
See illustration of 1 vs rest approach below:
Comment: imagine $k$ 1-v-rest classifiers as each describing regions where the $i$th class dominates the rest, _i.e._  $\left\{x|g_i(x) \le c_i\right\}$. This can result in the ambiguous region in your bottom figure. The linear machine approach _trains_ the classifiers in the same way, but then defines the region where the $i$th class dominates as $\left\{x|g_i(x) \le g_j(x),\,\forall j\right\}$.
Comment: I believe the 'linear machine' is a 'one vs. rest' approach, but the resultant classifiers are used differently than in your diagram.
Comment: It would be really helpful, if you could please elaborate on the usage differences you mentioned in your comment.
Answer: Training c linear discriminant functions is a example of a "1-vs-all" or "1-against-the-rest" approach to building a multiclass classifier given a binary classifier learning algorithm.  Training C(c,2) 2-class classifiers is an example of the "1-vs-1" approach.  As c gets larger, the "1-vs-1" approach builds a lot more classifiers (but each from a smaller training set).
This paper compares these two approaches, among others, using SVMs as the binary classifier learner:
C.-W. Hsu and C.-J. Lin. A comparison of methods for multi-class support vector machines , IEEE Transactions on Neural Networks, 13(2002), 415-425.
Hsu and Lin found 1-vs-1 worked best with SVMs, but this would not necessarily hold with all binary classifier learners, or all data sets.
Personally, I prefer polytomous logistic regression.
Comment: I am not referring to "1 vs rest" approach. Please see the update on my question post for clarification on the question. Thanks!


Cocoa/Objective-C NSButton event handling?

Question: I'm wondering how to handle an event on NSButton click, I've searched all over the internet and found lots of things like RightMouse button event handling, event handling on mouseup, event handling in c++, etc. but nothing that's just normal event handling, seems like everyone knows it already so I can't find any information about it? And I'm doing it all without .nib files or any kind of builder, it's pure text, so how do I handle button click event, I already have window and button created?
Answer: Did you try this ?
<code>NSButton *myButton = [[NSButton alloc] initWithFrame:myFrame];
[myButton setTarget:self];
[myButton setAction:@selector(myMethodToCallOnClick:)];
</code>
Comment: As soon as possible, giving me error that you can't mark answer correct within 4 minutes... I'll mark it when I can
Comment: Oh, thanks that's what I was looking for, knew it was something easy as heck but just couldn't find out what
Comment: Ok. Happy it helped. I guess you can validate the answer ;)


Animation On Local Position

Question: I am trying to make this:
The chracter walks up to a large crate, the player presses the e key and an animation starts playing, such that the character climbs up on to the crate. (all in first person view).
So far I tried this with normal "First Person Controller" Prefab in Unity.
My code so far:
<code>function OnTriggerStay(other : Collider){
    if(other.tag == "GrabZone"){
        if(Input.GetKeyDown("e")){
            animation.Play("JumpToLedge");
        }
    }
}
</code>
However when I use this on the FPC, it will always play from the position the animation is created on. I also tried to create an empty game object, placing the FPC in there. Gives same effect.
Most recently, I tried just animating the graphics of the FPC alone. This seems to work, but since the Character Controller itself is not animated, that stays on the ground. So the whole FPC won't work anymore.
Is there anyway I could let this animation play on the local position the player is on at that time? Or can you think of any other logical solution for a grab and climb?
Answer: You should always animate from the 0,0 position. This way you can always easilyl determine what to do and where to go with your model.

Animation On Local Position


How can I calculate the mean and variance of a linearly transformed random variable?

Question: Say I have a random variable $x$, with mean $\mu_x=35$ and standard deviation $\sigma_x=10$. I want to linearly transform $x$ to $y$ according to the formula $y=a+bx$ so that $\mu_y=100$ and $\sigma_y=15$, choosing values of $a$ and $b$ that satisfy these properties.
I know the formulas to calculate mean and standard deviation of a single random variable, but I can't figure out how to adapt them to a linear transformation of a random variable, particularly for situations where I only have a mean and variance for a distribution and not the underlying data.
Comment: Begin with [linearity of expectation](https://stats.stackexchange.com/search?q=linearity+expectation).  If that doesn't completely resolve the question, then please indicate where you are stuck in the derivation.
Comment: I could do that for a specific example, but I would like to have a general rule for various linear transformations, particularly for situations where I only have a mean and variance for a distribution and not the underlying data.
Comment: Then say so, for clarity, and maybe someone will answer.
Comment: And....why would you? Isn't it just simpler to transform your variables and then find the mean and standard deviation of the transformed variables?
Answer: Since y = a + b*x, we have following.
E[y] = E[a + bx] = a + bE(x). Thus, y's mean = a + b * (x's mean).
E[y^2] = E[(a + bx)^2] = a^2 + 2abE[x] + b^2*E[x^2].
(E[y])^2 = (a + bE(x))^2 = a^2 + 2abE[x] + b^2*(E[x])^2.
var(y) = E[y^2] - (E[y])^2 = b^2*(E[x^2] - (E[x])^2) = b^2*Var(x).
Conclusions:
(1) y's mean = a + b * (x's mean).
(2) y's variance = b^2 * (x's variance).
Comment: Very helpful and clear, thanks!


Realizar busca dentro de objeto javascript e retornar valor

Question: eu preciso fazer uma busca dentro de um objeto javascript que me traga o sku de acordo com o tamanho e cor, vcs pode me dar uma luz?
Exemplo: Preciso inserir em uma variável o sku do produto que tenha a cor "Azul" e tamanho "Queen". Nesse caso seria o SKU 132
var produtos = {
skus:[{
    especificacao: {
        cor: "Azul",
        tamanho: "Queen"
    },
    sku: 132
}, {
    especificacao: {
        cor: "Branco",
        tamanho: "Queen"
    },
    sku: 133
}]
};

Comment: Você pode utilizar a function filter dentro de outra function que recebe a cor e o tamanho. https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/filtro
Comment: ⚠ As duas respostas são boas, mas a outra não marcada com ✔ é compatível também com o Internet Explorer (a que foi marcada não é).
Comment: obrigado pela informação. Como as duas funcionaram pra mim, vou aceitar sua sugestão.
Answer: Ok, mas primeiro vamos criar um objeto válido, porque o declarado na pergunta não é.
var produtos = {
    skus:[{
        especificacao: {
            cor: "Azul",
            tamanho: "Queen"
        },
        sku: 132
    }, {
        especificacao: {
            cor: "Branco",
            tamanho: "Queen"
        },
        sku: 133
    }]
};

Para pesquisar um objeto num array, você pode utilizar o método find. O método find recebe uma callback, e invoca essa callback passando por parâmetro cada objeto do seu array, basta então retornar true para quando o objeto atender seu critério.
var skuEncontrado = produtos.skus.find(sku => sku.especificacao.cor === 'Azul' && sku.especificacao.tamanho === 'Queen');

Answer: Pode utilizar o filter, seria algo do género:
var produtos = {
    skus: [
        {
            especificacao: {
                cor: "Azul",
                tamanho: "Queen"
            },
            sku: 132
        },{
            especificacao: {
                cor: "Branco",
                tamanho: "Queen"
            },
            sku: 133
        }
    ]
};

var list = produtos.skus.filter(function(item){
    return (item.especificacao.cor == 'Azul' && item.especificacao.tamanho == 'Queen');
});

console.log('Lista de Produtos: ', list);


value of $a+b$ of the following function

Question: $f(x)=x^3-3x^2+5x\;$ and
$\;f(a)=1,f(b)=5.\;$ Find $a+b$.
I know only one real root exist for each equation as derivative of the function is always positive .I do not intend to use the formula of roots of cubic equation. How should i go about this problem ????
Comment: Solving approximately with a graph, we can see that $a+b=2$. That may help reverse engineer it...
Comment: $a,b \in \Bbb R$?
Comment: Yup it is real , nice solution indrayudh
Answer: I assume that $a$ and $b$ are real numbers (this can be guaranteed since $f(a)=1$ and $f(b)=5$ have real solutions.
As you said that $f^\prime$ is always positive that means $f$ is a strictly increasing function. Since $f(0)=0$ then $0<a<b$.
Note that we have
$$f(\frac{a+b}2)-\frac{f(a)}2-\frac{f(b)}2=-\frac38(b-a)^2(a+b-2).$$
So, If $a+b\leq 2$ then $$f(\frac{a+b}2)-\frac{f(a)}2-\frac{f(b)}2\ge0\iff f(\frac{a+b}2)\ge 3\iff\frac{a+b}2\ge 1\iff a+b\ge 2 $$
which gives $a+b=2$.
If $a+b>2$, then have $$f(\frac{a+b}2)-\frac{f(a)}2-\frac{f(b)}2<0\iff f(\frac{a+b}2)< 3\iff\frac{a+b}2< 1\iff a+b< 2 $$ that leads to contradiction.
In conclusion, we must have $a+b=2$.
Comment: Fist I considered that $x=1$ is the point in which $f$ change for concav to convex. And since $a<1<b$ then $f(\frac{a+b}2)$ must lie around $\frac{f(a)+f(b)}2$. Then I proved analytically like above.
Comment: How did you know to solve it like this? Is there a broader technique you are pulling from?
Answer: Since the function $f(x)=x^{3}-3x^{2}+5x$ is increasing and $f(0)=0, f(1)=3$ and $f(2)=6$, we must have $0 \lt a \lt 1 \lt b \lt 2$. And also, we have, $$a^{3}-3a^{2}+5a=1 \space \space \space \space \space ...(1)$$ and $$b^{3}-3b^{2}+5b=5 \space \space \space \space \space ...(2)$$ Adding $(1)$ and $(2)$ and denoting $a+b$ and $ab$ by $t$ and $x$ respectively, we have, $$t^{3} -3t^{2}+5t -3xt+6x-6=0$$ $$\iff (t-2)(t^{2}-t+3-3x)=0.$$
Now, we have $t^{2} \geq 4x$ and hence we have $t^{2}-t+3-3x \geq x-t+3$. But $x-t+3 = (a-1)(b-1)+2 > -1 +2 =1 >0.$ This is because we have $-1 \lt -(b-1) \lt (a-1)(b-1)$. Hence we must have $$t=a+b=2.$$


Doing something wrong with simple integration

Question:
So far my problem is finding E(X). After all my attempts I have E(X) = a/(a+1), and even wolfram alpha backs me up on this, even though the answer my prof got was a/(a-1). Sorry it's a picture again, but my rough work

I believe my set up and integration was right, but somewhere in evaluating the limit I went wrong. It's such a simple mistake but it's so irritating.
Comment: Sorry, late night and near exams. Brain is scrambled looking at it 20 mins. I'll avoid in the future.
Answer: Your mistake is as you integrate
$$\int_1^\infty x^{-\alpha} \, dx = \left.\frac{x^{-\alpha+1}}{\color{red}-\alpha+1}\right|_1^\infty$$
Comment: Dang it. So everything else is correct?
Comment: It seems that with that correction, you should be able to get the same answer as your prof.


Gauss circle problem and pole of zeta function

Question: I know some approach of the Gauss circle problem and its generalizations by Poisson formula. However, I read that the number of points of the lattice $\mathbb{Z}^n$ (or integer points $\mathcal{O}$ of a number field $F$) in a ball of radius $X$ is asymptotically dominated by $X^n$... and that this is a consequence of the fact that the Dedekind zeta function of $F$ has a simple pole at 1.
Where does it come from?
Answer: The number of points on $\Bbb{Z}^n$ with magnitude $\le r$ is asymptotic to the volume of the $r$-ball and it is immediate from drawing a cube centered around each lattice point of magnitude  $\le r$ giving a volume comprised between $Vol(B_{r-1/2}(0))$ and $Vol(B_{r+1/2}(0))$. This implies that the zeta function of this lattice has a simple pole at $1$ of residue the volume of the unit ball. The converse follows from a Tauberian theorem similar to the one needed to prove the PNT, where the analytic continuation of $\zeta_{\Bbb{Z}^n}(s)$ follows from the functional equation which follows from the Poisson summation formula.


Script SQL, para Inserir e-mails em uma tabela, e depois altera-los

Question: Eu tenho um script, que faz inserções randômicas de e-mails em uma tabela, após essas inserções, preciso encontrar uma maneira de verificar novamente esses e-mails inseridos, e alterá-los
Essa é uma parte do Script, eu passo para ele uma quantidade de e-mails (por exemplo 5), e ele vai criar 5 e-mail (email@example.com....email@example.com), o que eu não estou conseguindo é após essas inserções, substituir esses e-mails em um UPDATE. Preciso substituir esses mesmos e-mails inseridos, por outros e-mail, como (email@example.com....email@example.com)
FOR i IN 1..V_QTD_EMAILS LOOP
INSERT INTO G_CADASTRO.PX_EMAIL
  (
  ID,
  CD_DADOS_XXX_XXX_XXX,
  EMAIL,
  DT_INCLUSAO,
  CD_USUARIO
  )
VALUES
  (
    (SELECT MAX(ID) + 1
    FROM G_CADASTRO.PPX_EMAIL),
    V_CD_DADOS_PX_ESTAB,
    'KAUE' || i || '@EMAIL.COM.BR',
    SYSDATE,

    4993
  );
END LOOP;

COMMIT;

Eu tentei incluir esse bloco, mas não funcionou:
FOR i IN 5..V_QTD_EMAILS loop
  UPDATE G_CADASTRO.PX_EMAIL
     SET EMAIL = 'MATHEUS_' || i || '@EMAIL.COM.BR'
    WHERE CD_DADOS_PX_ESTAB = V_CD_DADOS_PX_ESTAB
END LOOP;

Poderiam me ajudar?
Comment: Faça o mesmo loop do insert, e user o seu EMAIL  no `where  EMAIL   =  'KAUE' || i || '@EMAIL.COM.BR' and CD_USUARIO = 4993`  e no seu set use  `SET EMAIL = 'MATHEUS_' || i + 5 || '@EMAIL.COM.BR'`
Comment: mas o update vai acontecer quando ? você chama o script novamente depois, passando 10 por exemplo ? ou só chama o script 1x e ele dá o insert e em seguida já dá o update ?
Comment: Rovann Linhalis, exatamente isso, o script roda uma única vez, então o insert e o update ocorrem no mesmo script, então o teste é finalizado. Na verdade o fluxo ocorre assim: Verifica a Tabela Pai >> Se já existe e-mail, apaga tudo, e insere novos dados, Então depois esses dados deve sofrer um UPDATE, que altera os e-mails
Comment: Por que você não insere os emails corretamente no primeiro loop?
Answer: Pessoa, resolvi com o seguinte SCRIPT:
FOR i IN 1..V_QTD_EMAILS loop
  UPDATE G_CADASTRO.PX_EMAIL
      SET EMAIL = 'TSTALTERACAO_' || i || '@EMAIL.COM.BR'
      WHERE EMAIL = 'KAUE' || i || '@EMAIL.COM.BR'
      AND CD_USUARIO = 4993;
END LOOP;

Obrigado pela ajuda de todos
Comment: Para marcar minha própria resposta, preciso esperar dois dias :\
Comment: marca a resposta como aceita ;)


how do I add up the whole column in excel?

Question: how do I add up the whole column in excel if there are N/A values?
I cant seem to find a solution to enable me to omit the N/A values as it keeps returning an error
Answer: Use AGGREGATE which will ignore the errors:
=AGGREGATE(9,3,A:A)

Comment: Thanks Scott,it worked. never used aggregate before
Comment: Or, if you are using O365, then place this formula in Define Named Manager as  `=LAMBDA(x,AGGREGATE(9,3,x))` and named it as `MYSUM` , so you can use it in your spreadsheet as `MYSUM(x)` where `x=A:A`


Installing PIP on debain - Unknown command pip

Question: I'm having a bit of a hard time installing PIP on a debian linux machine. This is the code I am using in a shell script:
# Install setuptools
python -c 'import setuptools' > /dev/null 2>&1
if [[ $? != 0 ]] ; then
    wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | sudo python
    if [[ $? != 0 ]] ; then
        echo "Unable to install setuptools" >> /dev/stderr
#       exit 1
    fi
fi

# Install PIP
wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
python get-pip.py

# Install packages
pip install supervisor --pre
pip install uwsgi
pip install virtualenv

However in my log I get the following messages showing that PIP didnt install correctly:
/root/StackScript: line 42: pip: command not found
/root/StackScript: line 43: pip: command not found
/root/StackScript: line 44: pip: command not found

Could anyone help me understand where I have gone wrong please?
Comment: Have you looked at this?  http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python?rq=1
Answer: Just install package python-pip from repository:
apt-get install python-pip
If you really need most recent version, then to use it from command line you should add it's executable directory to $PATH
Comment: The trouble is with this is it will install an outdated version of PIP which had security issues.


Android dim screen down problem

Question: This code dims the screen down, and it works for android 2.2 units. But when i tried it on my emulator(2.3) and on my friend's phone(2.3), i went to lock screen.
Any ideas why, And how i should do to get it work with 2.3?
<code> WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.screenBrightness = 0;
    getWindow().setAttributes(lp);
</code>
Answer: Kind of an old question at this point, but the emulator does not support screen dimming, and that behavior is just a glitch, mine does the same thing on 2.1, 2.2 etc on the emulator.
As to 2.3, I have not seen that. Have you tried to set the 0 to something like 0.01 instead, I have read (though never seen) that on some devices setting it to zero does this, and actually on the emulator if you use 0.01 it will not go to lock screen, though it still does nothing of course (unsupported behavior)
You can also try and logically or in the  following
<code>lp.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
</code>
Though counter intuitive I have read this keeps the screen touch enabled on devices that go to black when set to 0, and stops the problem your friends phone is exhibiting as well.
Quite honestly with all of the different results reported on different OS versions and platforms I am staying away from the screenBrightness setting since it seems pretty unreliable.

Android dim screen down problem


What does "not relying on any parametric functional form to be postulated" mean?

Question: I am reading the introduction section to a ml-book where I came across this sentence which I do not quite understand.
The Gaussian process is a non-parametric and probabilistic model for nonlinear functions. Non-parametric means that it does not rely on any parametric functional form to be postulated.
The second part I'd like a simpler explanation if possible.
Answer: While the answer to your question can be found online (e.g., Wikipedia's article on nonparametric statistics - see https://en.wikipedia.org/wiki/Nonparametric_statistics), I will go into some detail here.
Essentially. "nonparametric" means that no assumptions are made on the underlying data-generating process model. Here, a model consists of a number of parameters and variables combined together in some meaningful way. For instance, the Gaussian (normal) distribution
$$\frac{1}{\sqrt{2\pi\sigma^2}}e^\frac{-(x-\mu)^2}{2\sigma^2}$$
is one such parametric model having parameters $\mu$ (the population mean) and $\sigma^2$ (the population variance), and (random) variable $x$. Note some sources instead write the above expression in terms of the population standard deviation $\sigma$. in that case, the $\sigma^2$ under the square root is moved in front of it, becoming $\sigma$.
In most cases, population parameters are unknown a priori and therefore must be estimated (using a variety of techniques, such as the method of moments or maximum likelihood estimation).
I like to think of nonparametric as being equivalent to "data-driven", where we let the data do all of the talking. If you listen hard enough, your data will speak to you!


A puzzle on random variables that must have the same sum

Question: $X_1,\dots,X_n$ and $Y_1,\dots,Y_n$ are random variables that take values in $\{0,1\}$. Their distribution is unknown, each variable may have a different distribution and they might be dependent. The only known facts are:

$\sum_{i=1}^n X_i = \sum_{i=1}^n Y_i$
For all $i$, $\Pr[X_i=0] \geq \alpha$
For all $i$, $\Pr[Y_i=1] \geq \alpha$

I would like to prove (or disprove) that $\alpha \leq 1/2$.
The claim is obviously true for $n=1$, since in this case there are only two options:
A. $X_1 = Y_1 = 0$
B. $X_1 = Y_1 = 1$
Each of these options must happen with probability at least $\alpha$, but the total probability of these options is at most 1, so $\alpha$ must be at most $1/2$.
Is the claim also true for $n>1$?
Comment: Just take expectation on both sides of equality to get $n\alpha\le n(1-\alpha)$
Answer: Since expectation is linear you can write $$\mathbb{E}\left(\sum_{i=1}^{n}X_{i}\right) = \sum_{i=1}^{n}\mathbb{P}(X_{i}=1) \leq n(1-\alpha)\ .$$ Similarly, $$\mathbb{E}\left(\sum_{i=1}^{n}Y_{i}\right) = \sum_{i=1}^{n}\mathbb{P}(Y_{i}=1) \geq n\alpha\ .$$
Since the two expectations are equal you have the following inequality, valid for any integer $n>0\ .$
$$n\alpha \leq n(1-\alpha) \quad \Rightarrow \quad \alpha \leq \frac{1}{2}\ .$$
Answer: Thanks to linearity of expectation, this is indeed true. Taking the expectation of both sides yields:
$$\mathbb{E}\left(\sum_{i = 1}^{n}X_i\right) = \mathbb{E}\left(\sum_{i = 1}^{n}Y_i\right)$$
$$\sum_{i = 1}^{n}\mathbb{E}(X_i) = \sum_{i = 1}^{n}\mathbb{E}(Y_i)$$
$$\sum_{i = 1}^{n}\left(1-\Pr[X_i = 0]\right) = \sum_{i = 1}^{n}\Pr[Y_i = 1]$$
Then, since $\Pr[X_i = 0] \ge \alpha$ and $\Pr[Y_i = 1] \ge \alpha$, we have: $$n-n\alpha \ge \sum_{i = 1}^{n}\left(1-\Pr[X_i = 0]\right) = \sum_{i = 1}^{n}\Pr[Y_i = 1] \ge n\alpha$$
Since $n-n\alpha \ge n\alpha$, we get $\alpha \le \dfrac{1}{2}$, as desired.


Show different objects by double clicking listbox with same name

Question: Currently I'm working on a school project where I have this class members.
The listbox shows the propeties names as in Members.Name.
The problem I have is members with the same name shows the same information in the output textbox. I kinda need a different solution let me paste in my.
public void OutputMember()
    {
        searchResult = MemberSearch.ByName(Program.memberList, lbmembers.Text);
        foreach (Members member in searchResult)
        {
            tboutput.Text = string.Format("Medlemsnr {0}" +
            "Namn: {1}\r\n" +
            "Eftername: {2}\r\n" +
            "Personnummer: {3}\r\n" +
            "Adress: {4}\r\n" +
            "Email: {5}\r\n" +
            "Tele:{6}\r\n\r\n\r\n",member.MemberNr, member.Name, member.SurName, member.BirthYear.outStringWithId(),
             member.Adress, member.Email, member.Tele);

So I understand that the problem of this is the parameters.
I just send a list of members and just the name in text.
public static List<Members> ByName(List<Members> memberList, string member)
{

    List<Members> searchList = new List<Members>();

    for (int i = 0; i < memberList.Count; i++)
    {
        if (memberList[i].Name.Equals(member))
        {
            searchList.Add(memberList[i]);
        }
    }

    return searchList;

so the questions remains how do I view the "right" object in the output textbox by double clicking one of three equal names in the list.
Comment: if i use tboutput.Text += gives me all the members with the same name,
but that is not what im looking for,
Answer: You have not coded what you expect the program to do.
You expect the program to display the related Member based on its position in the list.
But you have coded a search method that returns the Member based on a name match, of which there are possible duplicates.
You are also returning multiple items from the list when you only need 1, and are needlessly looping through all results only to return the last one.
You just need:
public void OutputMember()
{
        member = Program.memberList[lbmembers.SelectedIndex]);
        tboutput.Text = string.Format("Medlemsnr {0}" +
        "Namn: {1}\r\n" +
        "Eftername: {2}\r\n" +
        "Personnummer: {3}\r\n" +
        "Adress: {4}\r\n" +
        "Email: {5}\r\n" +
        "Tele:{6}\r\n\r\n\r\n",member.MemberNr, member.Name, member.SurName, member.BirthYear.outStringWithId(),
        member.Adress, member.Email, member.Tele);
}

Comment: If you're doing this in VS2015+, you can replace the string.Format with an interpolated string like tboutput.Text = $"Name: {member.Name} ...";
Comment: Thanks! worked great!
the thing with my search method was i had a Search textbox aswell and if i for example typed "asd" i wanted  the output to show all members named "asd", that's why i had  the search method adding multiple objects.  And for less coding sake i tried to add the same search method for both the searchbox and listbox :P but apparently i only needed the index from listbox:)
Comment: If you want to implement search by text & search by index via one function you could accomplish this by function overloading. Just rename your ByName method to something like Search, and write another version that takes an int as the second parameter. The text version can return a List and the int version can return a Members. Incidentally, you might want to look at your naming convention, should the class be named Members or Member?
Comment: yeah a overload would be great makes it less code in ViewMember class. Well the name of the member class is going to be only Member. I have 2 member classes ATM cause i added an old one. So i'm trying the old one right now and it is named with an "s"


Boundary of a bounded set is compact

Question: I was wondering if my proof is not wrong. I'd appreciate if it could be reviewed.
Prove: the boundary of a bounded set is compact.

Proof:
Suppose $U$ is a bounded set. We know that $\overline{U}=U^{\circ} \cup \partial U$, that is, the closure of $U$ is the union of the interior of $U$ and the boundary of $U$. Moreover, $\overline{U}$ is compact by Heine-Borel. Thus there exists open cover of $\overline{U}$, which is $\{X_{\alpha}\}_{\alpha\in A}$. There also exists a finite subcover of $\overline{U}$, which is $\{X_{\alpha}\}_{\alpha\in A_0}$, where $A_0 \subset A$. But $\partial U \subset \overline{U}$, so $\{X_{\alpha}\}_{\alpha\in A_0}$ is also an open cover for $\partial U$, and so $\{X_{\alpha}\}_{\alpha\in A_0}$ is a finite subcover of $\partial U$. Hence, $\partial U$ is compact.
Comment: Same mistake as in the other thread. You start with an open cover of a set which is not the one you want to prove being compact. In addition, since you know Heine-Borel already, you can use it. But, of course, you can also deal with open coverings. It's your choice.
Comment: Nit pick.  Is your metric space complete?
Comment: you can't invoke Heine--Borel unless your space is $R^n$ which you haven't said. Your result is not tree without some restrictions on the space such as being $R^n.$
Answer: Your proof isn't quite right at the moment, because you have to consider any open cover of $\partial U$, which may or may not be an open cover of $\overline{U}$.
However, there's an easy way to fix this: given an open cover $\{V_i\}_{i\in I}$ of $\partial U$, add $U^o$ to the cover to obtain an open cover of $\overline{U}$, then argue as in your original proof.
Comment: So I said that if $K$ is a set, there's an open cover $\{U_{\alpha}\}_{\alpha\in A}$ of $\partial K$. Since $\partial K$ is bounded, there exists a finite subcover $\{U_{\alpha}\}_{\alpha\in A_0}$ of $\partial K$. Now consider $\bigcup_{\alpha\in A_0} U_\alpha\cup K^\circ$, which is a finite subcover of $\overline{K}$. Thus $\overline{K}$ is compact. But $\partial K \subset \overline{K}$, thus $\partial K$ is compact.
Comment: Why would it be needed to obtain an open cover of $\overline{U}$ if what has to be proved is that $\partial U$ is compact, not $\overline U$?
Comment: Well, the idea is to use the compactness of $\overline{U}$ to show that the open cover has a finite subcover. By the way, as the comments pointed out, if we're in $\mathbb{R}^n$ then it would be faster to just invoke the Heine-Borel theorem.
Comment: I don't understand why can't we just say that since $\partial U$ is bounded, it has an open cover, and thus it has a finite subcover? Why do we need to bother about $\overline{U}$? We're in a general topological space. @carmichael561
Comment: I think you're mixing up the quantifiers in the definition of compactness. You must show that every open cover has a finite subcover.
Comment: If we know that $\partial U$ is a closed and bounded set (since $U$ is finite), then the topological space of which $U$ is a subset can be an open cover of $\partial U$. But any open cover has a finite subcover, correct? I think I'm completely lost.

Boundary of a bounded set is compact


Error while converting tuples to Pandas DataFrame

Question: When i try to convert tuples to pandas dataframe i get the following error:

DataFrame constructor not properly called!

I am using the following code
columnlist=["Timestamp","Price","Month","Day","DayofWeek","tDaysleftMonth","tDayinMonth","tDayinWeek"]
tickerData=pd.DataFrame(tickerDataRaw,columns=columnlist)

The data was loaded to tuples from a MySQL database ,
Please find a screenshot of the data. Data I am trying to convert
Comment: I am using the following code
columnlist=["Timestamp","Price","Month","Day","DayofWeek","tDaysleftMonth","tDayinMonth","tDayinWeek"]
tickerData=pd.DataFrame(tickerDataRaw,columns=columnlist)
Answer: I think you can use DataFrame.from_records with converting tuples to list:
import pandas as pd

tuples = ((1,2,3),(4,6,7),(7,3,6),(8,2,7),(4,6,3),(7,3,6))

columnlist = ['a','b','c']
df = pd.DataFrame.from_records(list(tuples), columns=columnlist)
print (df)
   a  b  c
0  1  2  3
1  4  6  7
2  7  3  6
3  8  2  7
4  4  6  3
5  7  3  6

Another solution with DataFrame constructor only:
import pandas as pd

tuples = ((1,2,3),(4,6,7),(7,3,6),(8,2,7),(4,6,3),(7,3,6))

columnlist = ['a','b','c']
df = pd.DataFrame(list(tuples), columns=columnlist)
print (df)
   a  b  c
0  1  2  3
1  4  6  7
2  7  3  6
3  8  2  7
4  4  6  3
5  7  3  6

EDIT:
If check DataFrame and parameter data:

data : numpy ndarray (structured or homogeneous), dict, or DataFrame
Dict can contain Series, arrays, constants, or list-like objects
Answer: According to the Dataframe documentation page, data is required to be

numpy ndarray (structured or homogeneous), dict, or DataFrame

The easiest way to resolve your problem is simplty load your data in a numpy array and it should work fine.
>>> tuples = ((1,2,3),(1,2,3),(1,2,3))
>>> columns = ["A", "B", "C"]
>>> pd.DataFrame(tuples, columns=columns)
PandasError: DataFrame constructor not properly called!

>>> pd.DataFrame(np.array(tuples), columns=columns)
   A  B  C
0  1  2  3
1  1  2  3
2  1  2  3


I wante to find some $v>0$ verifying this property

Question: Let us consider a function $f: (0,+∞)→(0,+∞)$. Assuming that $f$ is continuous differentiable and strictly increasing for all $t>0$.
I want to find some $v>0$ verifying this property:
$$f(a)<f(v)≤c$$
where $a>0$  and $c>0$ are given real numbrers. I have no idea how to start.
Comment: Take $f(x)=x$ for $x\leq 0$ and $f(x)=x+2$ for $x>0$. Take $a=0$ and $c=1$. Then $f(a)=f(0)=0 < 1 = c$. But $f(a)0$, in which case $f(v)>2>c$.
Comment: @arts: But $f$ is continuous.
Comment: It wasn't when I wrote it. You added it later as can be seen in the edit history.
Comment: @arts: Yes, Thank you very much.
Answer: Let $a, c > 0$ such that $f(a) < c$ (otherwise it obviously doesn't hold). Then, because $f$ is continuous at $a$, there exists $\delta > 0$ such that $|v - a| < \delta \implies |f(v) - f(a)| \le c - f(a)$.
For any $v \in \langle a, a + \delta\rangle$ we have $f(a) < f(v)$ so:
$$0 < f(v) - f(a) = |f(v) - f(a)| \le c - f(a)$$
Which implies $f(a) < f(v) \le c$.


regex to match s3 urls in nginx location directive & proxy to amazon s3

Question: In nginx location directive, how do I match s3 urls.
for example, the wrong url is:
http://example.com/https://s3.amazonaws.com/mybucket/logo.jpg?1404251306

from Logs, I can see nginx can that it able to service the request from this url & returns a 404.
xx.xx.xx.xx - - [15/Aug/2014:12:38:04 +0000] "GET /https://s3.amazonaws.com/mybucket/logo.jpg HTTP/1.1" 404 151 "-" "Mo

with this, I want to match this url, proxy the request to s3 & return logo.jpg. I have come up with something like this:
location ~* ^/https/(.*) {
  set $s3_host 's3.amazonaws.com';
  set $s3_bucket 'mybucket';

  proxy_set_header       Host $s3_host;
  proxy_set_header       Authorization '';
  proxy_hide_header      x-amz-id-2;
  proxy_hide_header      x-amz-request-id;
  proxy_hide_header      Set-Cookie;
  proxy_ignore_headers   "Set-Cookie";
  proxy_buffering        off;
  proxy_intercept_errors on;

  resolver               18.104.22.168 valid=300s;
  resolver_timeout       10s;

  proxy_pass http://$1;
}

Questions:

What regex should I use in location directive so it matches amazon
s3 urls ONLY.
Currently, it handles any bucket. How do I restrict
    the bucket as well?

[Update]
I get the following error:
==> /var/log/nginx/error.log <==
2014/08/15 13:53:08 [error] 1579#0: *1 invalid port in upstream ":/s3.amazonaws.com/mybucket/logo.jpg", client: xx.xx.xx.xx, server: localhost, request: "GET /https://s3.amazonaws.com//mybucket/logo.jpg HTTP/1.1", host: "18.104.22.168"

Comment: You should fix your links instead of trying to mitigate the symptoms of the problem.
Comment: already done. but there are few older clients(desktop app users who haven't upgraded to latest version) who are still using the older URLs. this is done to give them a migration path.
Answer: Edit: (1) Sorry, some typo here (2) I adjust regex so it matches one or more slash before string mybucket like your log above.
Well, maybe you mean something like this
location ~* ^/https://s3\.amazonaws\.com/+mybucket(.*) {
  ...
  proxy_pass http://s3.amazonaws.com/mybucket$1;
}

Comment: I recently tested above configuration and it's working as expected. No 404 error or other nginx error messages. Probably you should reorder the location. In my case, the location direction was right below `location / {`. If reordering location doesn't help, please add the full version of your nginx config in the question.
Comment: with this, I get `invalid port in upstream` error.
Comment: @CuriousMind, check the updated answer
Comment: This doesn't match the location, I get `404`
Answer: I hit this error and it was because I was setting the Host header wrong.
Here's the config that ended up working:
set $s3_bucket        's3-us-west-1.amazonaws.com';
...
proxy_set_header       Host $s3_bucket;

Note that the host header does not include http/https. That should be included in the proxy_pass line
      proxy_pass             http://$s3_bucket/whatever


How to deal with scaling and transparency of a bitmap as android:windowBackground

Question: I am trying to set a global background image for my android application. The image is a PNG file with transparency. I set it in the following way:

And drawable/background_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<bitmap
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/background_main_bitmap"
        android:gravity="bottom|center_horizontal" />

My PNG file should sit at the bottom of the screen always, being scaled to match the screen size always. With the above code, however, I am facing two problems.

The transparent background of the PNG file is black while I want it to be white.
The PNG file is larger than the screen width and hence, I can only see a portion of it. It is not scaled to match the width of the screen.

How can I accomplish these two things, possibly without havin to write Java code? (Although it would be better than nothing...)
Answer: Problem #1 can be solved with a layer-list in drawable/background_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff"/>
        </shape>
    </item>
    <item>
        <bitmap
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:src="@drawable/background_main_bitmap"
            android:gravity="bottom|center_horizontal|fill_horizontal" />
    </item>
</layer-list>

Problem #2 remains though...
Comment: I don't have answer to #2, but the layered drawable may be written much easier: ``
Answer: just change the property of android:gravity like following:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/flush"
        android:gravity="fill_horizontal|fill_vertical"/>

Answer: Actually, using layer-list may give you expected scaling:

All drawable items are scaled to fit the size of the containing View, by default. Thus, placing your images in a layer list at different positions might increase the size of the View and some images scale as appropriate. To avoid scaling items in the list, use a <bitmap> element inside the <item> element to specify the drawable and define the gravity to something that does not scale, such as "center"

Thus, the following drawable will suit your request:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@android:color/white" />
  <item android:drawable="@drawable/background_main_bitmap" />
</layer-list>

Comment: That doesnt work, since window background is not a view. Just a drawable.


Zend Expressive / Laminas Mezzio - Route expects at least parameter values

Question: I want to use two parameters within  a fast route in zend expressive / laminas mezzio.
routes.php
$app->get('/api/users/{userId:\d+}/pages/[{id:\d+}]', [App\Page\PageHandler::class], 'api.pages');

ConfigProvider.php
 [
        '__class__' => RouteBasedResourceMetadata::class,
        'resource_class' => Page\PageEntity::class,
        'route' => 'api.page',
        'extractor' => ObjectPropertyHydrator::class,
  ],
  [
         '__class__' => RouteBasedCollectionMetadata::class,
         'collection_class' => Page\PageCollection::class,
         'collection_relation' => 'pages',
         'route' => 'api.pages',
  ],

This error occurs:
Route `api.page` expects at least parameter values for [userId,id], but received [id]

There is a problem with the mapping...
How can I add a second paramtere in de Metadata Mapping? I thought there would be an auto-mapping...
Answer: I guess the path configuration in the routes.php is faulty. Try this:
$app->get('/api/pages/{id:\d+}/users/{userId:\d+}', App\Page\PageHandler::class, 'api.pages');

In the handle function you can easily access userId and id via getAttributes function of the $request object:
public function handle(ServerRequestInterface $request) : ResponseInterface
{
    $userId = (int)$request->getAttribute('userId');
    $id = (int)$request->getAttribute('id');
}

The configuration in the ConfigProvider is not necessary for this.
If you want that getAttribute returns directly the corresponding entity objects and not the IDs, I would recommend you to use a middleware for it, which uses userId and id in order to loads the desired objects from the database or any other data source.
The following example uses Doctrine:
<?php
namespace App\Middleware;

class GetEntitiesFromQueryParamsMiddleware implements MiddlewareInterface
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager
    {
        $this->entityManager = $entityManager;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $pageId = (int)$request->getAttribute('id');
        $page = $this->entityManager
                ->getRepository(PageEntity::class)
                ->find($pageId);
        $userId = (int)$request->getAttribute('userId');
        $user = $this->entityManager
                ->getRepository(User::class)
                ->find($id);
        return $handler->handle($request
                ->withAttribute(PageEntity::class, $page)
                ->withAttribute(User::class, $user));
    }
}

Create a Factory for the middleware and register it in the ConfigProvider.
Also register this middleware in pipeline.php after RouteMiddleware:
...
$app->pipe(RouteMiddleware::class);
$app->pipe('/api/pages', GetEntitiesFromQueryParamsMiddleware::class);
...

Now you can access the objects in the handler method:
class PageHandler
{

    public function handle(ServerRequestInterface $request) : ResponseInterface
    {
        $page = $request->getAttribute(PageEntity::class);
        $user = $request->getAttribute(User::class);
    }
}


Exibir posts do wordpress com SQL

Question: Estou fazendo um site estático, onde todos os arquivos são em PHP, no entanto esse site tem um blog que deve ser gerenciável pelo Wordpress, aí vocês me perguntam e pro que não fazer tudo pelo Wordpress? pois é rsrsr ordem são ordens né.
Então tive a ideia de criar uma pasta chamada "noticias" onde irei instalar o Wordpress, então vai ficar dominio/noticias.
Só que eu preciso exibir as duas ultimas noticias na página inicial, ou seja fora do Wordpress, eu sei que vou ter que criar um arquivo para se conectar ao banco de dados e fazer o include na index.php e escrever uma sentença em SQL, mas sou muito leigo nisso, poderiam me da uma luz?
Answer:
eu sei que vou ter que criar um arquivo para se conectar ao banco de
  dados e fazer o include na index.php e escrever uma sentença em SQL

Você não precisa de nada disso. A partir da versão 4.7 você pode usar a REST API do WordPress pra puxar os dados. A única exigência é que esteja usando pretty-permalinks (qualquer coisa que não seja seusite.com?p=342 por exemplo).
$posts = file_get_contents( 'http://seuwordpress.com/wp-json/wp/v2/posts' );

$posts agora é um objeto JSON contendo os últimos posts do site. Equivalente ao que seria a página inicial.
Comment: pretty-permalinks é o mesmo que url amigável né? então quer dizer que com isso eu posso usar as funções sql nativas do Wordpress em qualquer página fora do Wordpress? vou já testar como isso funciona
Comment: isso, url amigável. Você não vai conseguir usar as funções nativas do WordPress. O que você pode fazer é requisições para os `endpoints` da API, que vão te retornar partes do conteúdo - como essa que eu mostrei. No link tem todos os `endpoints` disponíveis e exemplos de como fazer as consultas.
Comment: Na verdade é simplesmente como se vc estivesse consumindo um webservice externo, vc faz requisições e recebe respostas.
Comment: Consegui :D eu abrir o retorno dele com aquele programa Postman que organiza todo o código json e ele não mostra a image de destaque do post, saberia me dizer?
Comment: Ele não vai mostrar a imagem, vai trazer somente o ID e vc precisa fazer outro request pra buscar essa imagem pelo ID. Abra outra pergunta com essa dúvida se precisar.

Exibir posts do wordpress com SQL


Identificar a coluna de referência de uma coluna virtual do Oracle

Question: Tenho um índice no Oracle em que uma das colunas é DESC. Crio ele da seguinte forma:
CREATE INDEX XFT25TB ON FT25T (FT07CODEMP, FI16MODELO, FT07CODIGO, FT25ORDIMP, DESC)

Porém, ao utilizar as views de dicionário de dados do Oracle, o índice referencia uma coluna virtual no lugar de referenciar a coluna FT25ORDIMP, conforme abaixo:
SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = 'FT25T' AND INDEX_NAME = 'XFT25TB';

INDEX_NAME                     TABLE_NAME                     COLUMN_NAME                                                                      COLUMN_POSITION COLUMN_LENGTH CHAR_LENGTH DESCEND
------------------------------ ------------------------------ -------------------------------------------------------------------------------- --------------- ------------- ----------- -------
XFT25TB                        FT25T                          FT07CODEMP                                                                                1            22           0 ASC
XFT25TB                        FT25T                          FI16MODELO                                                                                2             2           2 ASC
XFT25TB                        FT25T                          FT07CODIGO                                                                                3            22           0 ASC
XFT25TB                        FT25T                          SYS_NC00006$                                                                                4            34           0 DESC

Gostaria de saber se existe alguma forma de obter o nome da coluna FT25ORDIMP a partir da coluna virtual SYS_NC00006$. Não encontrei nenhuma maneira de fazer essa referência diretamente.
Comment: https://decipherinfosys.wordpress.com/2009/02/12/check-for-column-expression-of-function-based-index-in-the-schema/ sem acesso ao Oracle para testar todavia
Comment: Não sabia que virtuais poderiam ser indexedas !
Comment: @Motta, no caso o que é indexado é uma coluna física mesmo, o próprio Oracle que cria a coluna virtual e insere no índice...
Comment: Outra questão também é que eu consigo ver, através da view `USER_IND_EXPRESSIONS`, a coluna física daquele item, no campo `COLUMN_EXPRESSION`, porém não consigo utilizar esse resultado em nenhum WHERE, obter como uma string nem nada, apenas visualizar...
Answer: Consegui resolver criando uma função no banco, deixo aqui a quem puder interessar.
CREATE OR replace FUNCTION COLUNAS_RAW_INDICES(p_tname IN VARCHAR2, p_cname IN VARCHAR2)
RETURN VARCHAR2
AS
  l_cursor   INTEGER DEFAULT DBMS_SQL.open_cursor;
  l_n        NUMBER;
  l_long_val VARCHAR2(4000);
  l_long_len NUMBER;
  l_buflen   NUMBER := 4000;
  l_curpos   NUMBER := 0;
BEGIN
    DBMS_SQL.PARSE(l_cursor, 'SELECT DATA_DEFAULT FROM USER_TAB_COLS WHERE '
                             || 'TABLE_NAME = :TableName '
                             || 'AND COLUMN_NAME = :ColumnName', DBMS_SQL.NATIVE);
    DBMS_SQL.DEFINE_COLUMN_LONG(l_cursor, 1);
    DBMS_SQL.BIND_VARIABLE( l_cursor, ':TableName', p_tname);
    DBMS_SQL.BIND_VARIABLE( l_cursor, ':ColumnName', p_cname);
    l_n := DBMS_SQL.EXECUTE(l_cursor);
    IF (DBMS_SQL.FETCH_ROWS(l_cursor) > 0) THEN
      DBMS_SQL.COLUMN_VALUE_LONG(l_cursor, 1, l_buflen, l_curpos, l_long_val, l_long_len);
    END IF;
    DBMS_SQL.CLOSE_CURSOR(l_cursor);
    RETURN RTRIM(LTRIM(REPLACE(l_long_val, '"', '')));
END COLUNAS_RAW_INDICES;
Dessa forma, executando o comando SELECT COLUNAS_RAW_INDICES('FT25T', 'SYS_NC00006$') FROM DUAL consigo obter como um VARCHAR2 a coluna que eu preciso.


Two Way DataBinding with WPF User Control in Windows Forms

Question: I have a user control with a WPF Data Grid. I used this user control in a Windows form using Element Host.
I can bind the data to the user control using ListCollectionView but when i make updates to the datagrid the changes are not reflected back.
I set the Mode = TwoWay but no use.
Any ideas ?
Here is a sample of my code:
UserControl.xaml
<my:DataGrid ItemsSource="{Binding}"
             HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended"
             CanUserAddRows="False" CanUserDeleteRows="False"
             CanUserResizeRows="False" CanUserSortColumns="False"
             AutoGenerateColumns="False"
             RowHeaderWidth="20" RowHeight="25" Width="Auto" Height="Auto"
             RowStyle="{StaticResource RowSelected1}"
             CellStyle="{StaticResource RowSelected}"
             GridLinesVisibility="Horizontal" >
  <my:DataGrid.GroupStyle>
    <GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle1}">
      <GroupStyle.Panel>
        <ItemsPanelTemplate>
          <my:DataGridRowsPresenter/>
        </ItemsPanelTemplate>
      </GroupStyle.Panel>
    </GroupStyle>
  </my:DataGrid.GroupStyle>
  <my:DataGrid.Columns>
    <Controls:LabelTextBoxColumn   Header="Tread BarCode" Width="2*"
    HorizontalAlignment="Left" VerticalAlignment="Center"
    ElementStyle="{StaticResource BaseLabelCellStyle}"
    EditingElementStyle="{StaticResource BaseTextBoxCellStyle}"
    Binding="{Binding Name,Mode=TwoWay}"/>

The code in my Windows form frm1 is :
this.sdaTrueName.Fill(this.dstrueSrch1.dtTrue);
view = new ListCollectionView(this.dstrueSrch1.dtTrue.ToList());
view.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
UserControlABC.DataContext = view;

I have to save the data back into my database.I am using Dataset and DataTables.
Please help me with any ideas ?

I tried to debug my program and i was getting an error in the output window.
System.Windows.Data Warning: 52 : Created BindingExpression (hash=19378226) for Binding (hash=19699911)
System.Windows.Data Warning: 54 :   Path: 'IsEnabled'
System.Windows.Data Warning: 56 : BindingExpression (hash=19378226): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=19378226): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=19378226): Attach to System.Windows.Controls.TextBox.IsEnabled (hash=56309765)
System.Windows.Data Warning: 63 : BindingExpression (hash=19378226): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=19378226): Found data context element: TextBox (hash=56309765) (OK)
System.Windows.Data Warning: 67 : BindingExpression (hash=19378226): DataContext is null
System.Windows.Data Warning: 61 : BindingExpression (hash=19378226): Resolve source deferred
System.Windows.Data Warning: 63 : BindingExpression (hash=19378226): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=19378226): Found data context element: TextBox (hash=56309765) (OK)
System.Windows.Data Warning: 74 : BindingExpression (hash=19378226): Activate with root item dataTableExtrRow (hash=24854661)
System.Windows.Data Warning: 104 : BindingExpression (hash=19378226):   At level 0 - for dataTableExtrRow.IsEnabled found accessor <null>
System.Windows.Data Error: 39 : BindingExpression path error: 'IsEnabled' property not found on 'object' ''dataTableExtrRow' (HashCode=24854661)'.
BindingExpression:Path=IsEnabled; DataItem='dtextruderWindupRow' (HashCode=24854661); target element is 'TextBox' (Name=''); target property is 'IsEnabled' (type 'Boolean')
System.Windows.Data Warning: 76 : BindingExpression (hash=19378226): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 84 : BindingExpression (hash=19378226): TransferValue - using fallback/default value 'True'
System.Windows.Data Warning: 85 : BindingExpression (hash=19378226): TransferValue - using final value 'True'"

Here is the XAML code in my Resources window in my User Control:

Here is my Code in my WPF DataGrid:
<Controls:LabelTextBoxColumn
      Header="Tread BarCode" Width="2*"
          HorizontalAlignment="Left" VerticalAlignment="Center"
          ElementStyle="{StaticResource BaseLabelCellStyle}"
          EditingElementStyle="{StaticResource BaseTextBoxCellStyle}"
      Binding="{Binding rollCallID,Mode=TwoWay}"/>

I can't understand this error.
Comment: spend a little time formatting your question to be readable and save time for N SO readers who want to help you. Everyone values their own time => doesn't want to spend time trying to decipher a poorly formatted question. Maximises your chances of getting an answer...
Answer: Does your Data source implement INotifyCollectionChanged? Otherwise WPF doesn't know that something is different.
Answer: Could be due to multiple reasons... not enough info here.

Do you see any data binding errors in the output window, when you're running the app with debugger attached ?
Shouldn't you be using ObservableCollection instead of ListCollectionView for the backing data source ? Link I don't see ListCollectionView implementing INotifyPropertyChanged.
Answer: Try adding "UpdateSourceTrigger=LostFocus" to the Binding of the LabelTextBoxColumn.
Also, try not to fill the Dataset from the Code-Behind. I had a similar issue when binding my Dataset to a Listbox. I would change the value in the Listbox and the change would never reflect back from the source. I found that i kept on filling the Dataset with old values.
And what i also forgot to do is to update the database explicitly. I your Code-Behind, after making changes, call the DatasetTableAdapter.Update() method.
I did not need to implement INotifyPropertyChanged.


Conditional probability question involving balls w/o replacement

Question: A box contains 12 balls numbered 1 through 12.  If 5 balls are selected one at a time from the box, without replacement, what is the probability that the largest number selected will be 9?
I want to just say $$\frac{9\times8\times7\times6\times5}{\binom{12}{5}}$$ but that is wrong and I don't know why.
Comment: This is not what I would normally expect to be called a _conditional_ probability question.
Answer: You need to do the problem in two parts.  First what is the probability that none of the ball chosen are numbered 10 through 12.  This has probability $P=\frac{9\times 8\times 7\times 6 \times 5}{12 \times 11\times 10\times 9\times 8}$.  Second the probability (under this condition) that a 9 has been chosen.  To get this calculate the probability that a 9 was not chosen.  This is  $Q=\frac{8\times 7\times 6\times 5\times 4}{9\times 8\times 7\times 6\times 5}$.  The final answer is $P(1-Q)$
Comment: At first I doubted this method—"Surely the events are not independent"—but then I realized that $Q$ is a conditional probability. And indeed the answer agrees with other correct answers.
Answer: The event in which the largest number is 9 is if:
a) You pick 9
b) You pick 4 other numbers that are less than 9
The number of ways you can do that is simply picking 4 items out of 8. You should be able to finish from here.
Answer: The event "the largest draw is $9$" can be seen as the intersection of two events:

$E_1$: all draws are at most $9$.
$E_2$: (at least) one draw is $9$.

So you can compute your probability as $P(E_1)\cdot P(E_2|E_1)$.
$P(E_1)={9\choose 5} / {12 \choose 5} = \frac{7}{44}$, i.e. the number of ways you can take your $5$ draws from the $[1...9]$ interval, over the number of ways you can take them from the $[1...12]$ interval.
$P(E_2|E_1)=1-\frac{8}{9}\frac{7}{8}\frac{6}{7}\frac{5}{6}\frac{4}{5}=\frac{5}{9}$, i.e. $1$ minus the probability of avoiding a $9$ with your first, second, third, fourth and fifth draw given that all your draws are in the $[1...9]$ interval.
Then the probability that your highest draw is a $9$ is $\frac{7}{44}\frac{5}{9}=\frac{35}{396}$. There are other, slightly quicker ways to compute the solution, but I think that this one through conditional probabilities is the most "obvious".

The original question also asks: why is the probability not $\frac{9\cdot 8\cdot 7\cdot 6\cdot 5}{12 \choose 5}$? The denominator is the number of ways one can choose $5$ balls out of $12$. The numerator is the number of ways one can choose $5$ "distinguishable" balls out of $9$. This has two problems: first, it counts the balls as "distinguishable" (in other words, it takes $9\cdot 8\cdot 7\cdot 6\cdot 5$ instead of $9\choose 5$). Second, it considers every case in which the highest draw is at most $9$, rather than exactly $9$ (so it forgets to multiply by the probability that of the $5$ draws in the $[1-9]$ range, one is indeed $9$, i.e. $1-\frac{8}{9}\frac{7}{8}\frac{6}{7}\frac{5}{6}\frac{4}{5}=\frac{5}{9}$). Addressing these two issues takes us to the formula above.
Answer: There are $8$ choices (i.e.: 1,2,3,4,5,6,7,8) which are less than $9$, $1$ choice which equals $9$ and $3$ choices (i.e.: 10,11,12) which exceed $9$. So, appplying the hypergeometric distribution formula, we readily get:
$$
\frac{\binom{8}{4}\binom{1}{1}\binom{3}{0}}{\binom{12}{5}}=\frac{\binom{8}{4}}{\binom{12}{5}}=\frac{\frac{5\cdot 6\cdot 7\cdot 8}{2\cdot 3\cdot 4}}{\frac{8\cdot 9\cdot 10\cdot 11\cdot 12}{2\cdot 3\cdot 4\cdot 5}}=\frac{5\cdot 6\cdot 7\cdot 8}{8\cdot 9\cdot 2\cdot 11\cdot 12}=\frac{5\cdot 7}{3\cdot 11\cdot 12}=\frac{35}{396}
$$
Answer:
A box contains 12 balls numbered 1 through 12.  If 5 balls are selected one at a time from the box, without replacement, what is the probability that the largest number selected will be 9?

The probability for selecting 9 and four numbers less than 9, when selected any five of the twelve without replacement, is: ${^8\mathrm C_4}\,/\,{^{12}\mathrm C_5}$ or $5\cdot{^8\mathrm P_4}\,/\,{^{12}\mathrm P_5}$
Since you seem more familiar with using $^n\mathrm P_r$ then that second is derved as follows:  Count the ways to permute the maximum (9) and four places.   Count the ways to fill those places with a permutation of 4 balls from the 8 lesser balls.   Count the ways to fill all five places with a permutation of any 5 balls from 12.   Multiply and divide the counts, as appropriate.

i want just say $\frac{9*8*7*6*5}{12P5}$ but that is wrong and dont know why.

${^9\mathrm C_5}/{^{12}\mathrm C_5}$, or ${^9\mathrm P_5}/{^{12}\mathrm P_5}$, is the probability for selecting five numbers that are 9 or less, when selected any five of the twelve without replacement.   (The maximum of those five ballsis not restricted to being 9; just to not exceeding it.)
Answer: EDIT: Misread initial question at first.
Probability that largest number is nine would be (8 choose 4)/(12 choose 5). 8 choose 4 represents all the ways of choosing the remaining 4 numbers below 4 without replacement. Then divide by the total number of combinations
Comment: I think this answer is computing the probability that the greatest number selected is equal to _or less than_ nine.
Comment: It's a mistake to multiply by 5 -- after all, we're counting combinations and not permutations. Note that (8 choose 4)/(12 choose 5) = 35/396, matching the top answer.
Comment: that would seem to suggest the answer in my book is wrong.
Comment: Edited, I initially read that less than or equal to, not exactly nine. Fixed.


Example of a ring $R$ and ideals $A$ and $B$ of $R$ such that $AB\neq A\cap B$.

Question: Give an example ofa ring $R$ and ideals $A$ and $B$ of $R$ such that $AB\neq A\cap B$. I know that $AB\subset A\cap B$. But I can't find an example such that $AB\neq A\cap B$.
Comment: Take $A=B$. In most of reasonable situation, $AB=A^2\ne A$ (find an example with  $R=\mathbb Z$).
Answer: Take $R=\mathbb Z$, $A=(6)$, $B=(10)$. Then $AB=(60)$ but $A\cap B=(30)$.
In general, if $A=(m)$ and $B=(n)$ then $AB=(mn)$ and $A\cap B=(lcm(m,n))$ and so they are equal iff $\gcd(m,n)=1$.


WIX and preconditions (DLLs/OCXs in System32, ...)

Question: What i have:
I have an installations routine written in WIX 3.6 (with heat, candle, light)

What's the problem:
it only installs the app-folder-files (registering activex-components, registering and starting a service, making regentries, ...) and not DLLs/OCXs in the System32-folder. also the avalabiliy of ADO (ActiveX Data Objects) isn't checked.

Which is the best way to deal this?
Answer:
If there are files you created that need installed to
System32, then you need to manually edit your .wxs file(s) to include
those files.
If you have third party prerequisites that need installed, generally speaking you would install them using the distribution method (installer) provided by the vendor. You can then create a WiX bundle that installs your prerequisites before installing your package.