Equal number of training instances of each classification label?

Question: I am using Naive Bayes to perform binary classification. In my training set, the two class labels occur with probability Pr(label A) = 0.95 and Pr(label B) = 0.05.
Should I prune the training set so that there is an equal number of training instances of each label? Does the answer apply to any classifier, not just Naive Bayes?
Answer: It really depends on what your ultimate goal is. If you just care about overall accuracy and the  class priors you observe in your training set are a good estimate of what you are likely to see in the world, then you should not do anything to your data. It is worth noting that you will likely end up with a classifier which overwhelmingly predicts $A$, but this is what you would expect and makes sense from a decision theory point of view.
On the other hand, if you care about things like precision and recall for both classes, or you think the observed class priors are not truly that biased, you will need to do something to deal with the class imbalance. Rather than repeat here, I'll point you to this answer I previously posted regarding methods to deal with class imbalance.
As to the last part of your question, the answer is yes, this answer applies to classifiers in general and not just Naive Bayes.
Comment: Thanks for the answer. This 'class imbalance' problem seemed to me to be most obvious with Naive Bayes since the Bayes' Theorem equation contains a specific term for the class prior. From what you wrote about class imbalance being a general problem, am I correct in assuming that other ML classifiers like C4.5 Decision Trees and SVM also implicitly or explicitly use class prior probabilities?


How do I fetch the user ID from the shipping profile?

Question: I'm trying to get the User ID from Shipping Profile in Drupal Commerce using the following code, but eventually, $entity->getOwnerId() is returning me NULL in any case, if it's an authenticated user or admin it's giving me 0 as the UID.
function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'profile') {
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($entity->getOwnerId());
    }
}

Answer: Shipping and billing profiles don't have a user ID, they are always anonymous because they belong to the parent entity (order/shipment), not the user.
Only address book profiles have user IDs.
Answer: Thanks for the heads-up @bojanz. Considering your response, I've found 2 possible solutions:
function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'profile') {
        $entity->setData('copy_to_address_book', TRUE);
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($entity->getOwnerId());
    }
}

More reasonable one:
function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'commerce_order') {
        $uid = $entity->get('uid')->target_id;
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($uid);
    }
}


prove a theorem about an upper bound of entropy of a random vector

Question: There is a theorem that:
if Z is any zero-mean, complex random vector with covariance $E[ZZ^H]=R_z$, then $H(Z)\leq \log|{\pi eR_z}|$, with equality holding if and only if Z has a circularly symmetric Gaussian distribution and $H(Z)$ is the entropy of Z.
I do not know what the name of this theorem to seek its proof in books or articles. I will be thankful if someone tell its name to me, or offers a proof for this theorem.
Answer: This theorem has not a specific name, but a proof for this has been offered in the following article on page 4:
http://lthiwww.epfl.ch/~leveque/Projects/telatar.pdf


nodejs function in class returns undefined

Question: So, I have a function in my class that should return an object, but instead it returns undefined, which I dont know why it is happening, here's the code:
method.getQuests = function(){
    var id = this._data[0].id;
    var lvl = this._data[0].level;
    var structure = [];

    connection.query("SELECT * FROM quest WHERE player_id = ?", [id], function(errors, rowss, fieldss) {

        for(var i = 0; i < rowss.length; i++){
            var rewards = {
                "coins":rowss[i].gold,
                "xp":rowss[i].experience,
                "honor":rowss[i].honor,
                "premium":rowss[i].donut,
                "statPoints":0,
                "item":0
            };

            structure.push({
                "id": rowss[i].id,
                "character_id": id,
                "identifier": rowss[i].name,
                "type": 1,
                "stage": rowss[i].stage,
                "level": lvl,
                "status": 1,
                "duration_type": 1,
                "duration_raw": (rowss[i].duration * 60) * 4,
                "duration": rowss[i].duration * 60,
                "ts_complete": 0,
                "energy_cost": rowss[i].duration,
                "fight_difficulty": 0,
                "fight_npc_identifier": "",
                "fight_battle_id": 0,
                "used_resources": 0,
                "rewards": JSON.stringify(rewards)
            });
        }

        return structure;

    });

}

What is also happening is that after I call some mysql query my user data stored in this._data doesn't exist anymore, so Im totally lost at this point.
Comment: Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)
Answer: connection.query is async, so when you return structure; it will return undefined because the async function connection.query()  hasn't completed yet. Try using a callback. When you define your function, define it like this:
method.getQuests = function(callback){

And instead of return structure; try
callback(structure);

Then, when you call it and want to use it, use it like this:
method.getQuests(function(structure){
console.log(structure);
});

Comment: Thanks for this solution!


Consulta com um filtro diferente para cada linha

Question: Estou fazendo uma query onde, eu tenho 3 colunas relacionadas por um filtro de texto Where '.' Like %xxx%', onde cada linha da coluna tem um filtro diferente (um Like %xxx% diferente).
Tentei montar em cases mas não consegui, segue abaixo como pensei:
Select `Estruturada_Duplicata`.`duplicata_comment`, `Estruturada_Duplicata`.`duplicata_value`
from(
Select `Estruturada_Duplicata`.`duplicata_comment`, `Estruturada_Duplicata`.`duplicata_value`
Case when (duplicata_comment = '%restri%') then count(`Estruturada_Duplicata`.`duplicata_comment`), sum(`Estruturada_Duplicata`.`duplicata_value`) end restricao,
Case when (duplicata_comment = '%protesto%') then count(`Estruturada_Duplicata`.`duplicata_comment`), sum(`Estruturada_Duplicata`.`duplicata_value`) end protesto
from(`dataform`.`estruturada_duplicata`)
  )
LIMIT 1;

Também tentei com subqueries, mas não consegui estruturar porque só é possível trazer uma coluna por sub. Caso não tenha ficado claro no código: uma coluna da consulta só vai trazer os textos duplicata_comment, outra contar quantos comments existem com filtro indicado, e outra  somar o valor das duplicatas com o filtro indicado.
Answer: Se é que eu entendi, tente:
SELECT  COUNT(CASE WHEN (duplicata_comment = '%restri%') THEN 1 ELSE 0 END) cont_restricao,
            SUM(CASE WHEN (duplicata_comment = '%restri%') THEN `Estruturada_Duplicata`.`duplicata_value` ELSE 0 END) val_restricao,
            COUNT(CASE WHEN (duplicata_comment = '%protesto%') THEN 1 ELSE 0 END) cont_protesto,
            SUM(CASE WHEN (duplicata_comment = '%protesto%') THEN `Estruturada_Duplicata`.`duplicata_value` ELSE 0 END) val_restricao
FROM `dataform`.`estruturada_duplicata`;

Comment: Andei testando essa solução de algumas formas, mas continua dando errado. Os counts das duplicatas sempre dão o mesmo valor, independente da condição. E a soma dos valores sempre dá zero.


Testing for Partial Structural Break in R

Question: I want to test for a partial unknown structural break in a time series.  By this I mean that I want to test $H_0: \beta_{1} = \beta_{2}$ such that $Y_t = \beta_{0}^{'}X_t + \beta_{1}^{'}Z_t(t<T) + \beta_{2}^{'}Z_t(t>T) + e_t)$.  Intuitively, this is accomplished by rolling a Wald Statistic over the data.  However, in R I can not find a way to do this.  Both strucchange::Fstats and gap::chowtest appear to only test the case of a full structural break (i.e. $Y_t = \beta_{1}^{'}Z_t(t<T) + \beta_{2}^{'}Z_t(t>T) + e_t$.  Is there a way to test a partial structural break in R?
I think my best solution will be to roll aod::wald.test over the sample and obtain the critical values from Andrew (1993).
Comment: Did you search `install.packages("sos", dep = TRUE); findFn("partial structural break")`?
Comment: @Pascal, first off thanks for introducing me to the `sos` package.  Unfortunately, I did not find a useful package.
Answer: It is correct that strucchange::Fstats() does not support testing of partial structural changes. However, instead of the supF (or supWald) test you can also compute the supLM test via strucchange::gefp() and this also allows to assess partial structural change hypotheses.
Example with artificial data and partial change in z but not x:
set.seed(0)
d <- data.frame(x = runif(200), z = runif(200), err = rnorm(200))
d$y <- 0 + 0 * d$x + rep(c(0, 1), each = 100) * d$z + d$err

Then you can compute the generalized empirical fluctuation process for the model under the null hypothesis of no change. Either for all three parameters or only for the slope of the regressor z:
efp_all <- gefp(y ~ x + z, data = d)
efp_z <- gefp(y ~ x + z, data = d, parm = "z")

The latter, however, is essentially only the third component of the full fluctuation process. plot(efp_all, aggregate = FALSE, ylim = c(-2, 2)) yields:

This shows that there is somewhat increased fluctuation in the process related to z (but not with respect to x) which is not significant at the 5% level when using a double maximum test:
sctest(efp_all, functional = maxBB)
##         M-fluctuation test
##
## data:  efp_all
## f(efp) = 1.3601, p-value = 0.1412

Similarly a supLM test would not be significant:
sctest(efp_all, functional = supLM(0.15))
##         M-fluctuation test
##
## data:  efp_all
## f(efp) = 11.037, p-value = 0.1476

yielding a similar p-value. However, when focusing on the z coefficient only, the p-values clearly decrease:
sctest(efp_z, functional = maxBB)
##         M-fluctuation test
##
## data:  efp_z
## f(efp) = 1.3601, p-value = 0.04947
sctest(efp_z, functional = supLM(0.15))
##         M-fluctuation test
##
## data:  efp_z
## f(efp) = 7.3998, p-value = 0.08646

However, whether your power really increases a lot by this is a different question. In my experience, I often find that the differences between the partial and full tests are smaller than the power of the different kind of test statistics (supF, double maximum, Cramer-von Mises, MOSUM, etc.). And which of these is really most powerful depends on the kind of alternative which you rarely know well enough in advance... For example in this data set (which I have tweaked somewhat, of course), the full sample supWald or Cramer-von Mises tests are both significant:
sctest(Fstats(y ~ x + z, data = d))
##         supF test
##
## data:  Fstats(y ~ x + z, data = d)
## sup.F = 15.077, p-value = 0.03075
sctest(efp_all, functional = meanL2BB)
##         M-fluctuation test
##
## data:  efp_all
## f(efp) = 1.0978, p-value = 0.03209

For more details on the gefp() framework, see Achim Zeileis (2006). "Implementing a Class of Structural Change Tests: An Econometric Computing Approach." Computational Statistics & Data Analysis, 50, 2987-3008. doi:10.1016/j.csda.2005.07.001
If you want to use your own partial supWald test, I would just use stats::anova() (rather than the aod package) and get the p-values from strucchange::pvalue.Fstats().


Render wordpress shortcodes without using the_content() in loop

Question: I have the following code in my index.php page that fetches all the pages and alter them. The problem is that i haven't used the_content() to show the content rather i used echo $page->post_content(). I have to now embed a contact form 7 in my page but as i read on different questions here that shortcodes won't work if there is no the_content().
My question is how can i show the contact form with any trick here.
$pages = get_pages($args);
foreach ($pages as $page){
    // Override Homepage
    if($page->ID == 5){
        $page->post_content = file_get_contents(get_template_directory_uri().'/includes/homepage-override.php');
    }
    // Check if it is menu page
    if($page->post_parent == 169){
        $page->post_content = file_get_contents(get_template_directory_uri().'/includes/location-menu-page.php?location='.$page->post_title);
    }
    // Calling Gallery Images
    if($page->ID == 23){
        $page->post_content = file_get_contents(get_template_directory_uri().'/includes/gallery-page.php');
    }

    // Calling about page
    //if($page->ID == 7 || $page->ID == 17 || $page->ID == 29){
    if(has_post_thumbnail($page->ID)):
        $image = wp_get_attachment_image_src( get_post_thumbnail_id($page->ID), 'single-post-thumbnail' );
        $dom = new DOMDocument();
        @$dom->loadHTML($page->post_content);
        $imgs = $dom->getElementsByTagName("img");
        foreach($imgs as $img){
            $img->setAttribute( 'src' , $image[0] );
            break;
        //}
    }
    $page->post_content = $dom->saveHTML();
    endif;
    echo $page->post_content;
    //the_content(); This is not working
}

Answer: You can apply the_content filters to post_content:
<?php echo apply_filters('the_content', $page->post_content); ?>

It also may be possible to do_shortcode():
<?php echo do_shortcode($page->post_content); ?>

Comment: same on index.php file or functions ?
Comment: You can put this wherever you currently `echo` the `$page->post_content`.


Correct handling of type-dependent logic (highly polymorphic objects) inside of abstract logic using OOP

Question: What is the best way from point of OOP to handle mapping from Game object to GameDto object, taking into account that Game has property Scoreboard that has a lot of derived objects (more than 15) as FootballScoreboard, Formula1Scoreboard, BaseballScoreboard, etc?
There is ability to know what exact type of Scoreboard inside of game only in runtime (it can be for whatever sport).
ScoreboardDto has corresponding FootballScoreboardDto, Formula1ScoreboardDto, BaseballScoreboardDto, etc classes.
The simplified scheme:
public class Game
{
    public Scoreboard Scoreboard { get; }
}

public class GameDto
{
    public ScoreboardDto Scoreboard { get; }
}

public class DtoParser
{
    public GameDto Parse(Game game)
    {
        var gameDto = new GameDto();
        //How to implement parsing of game.Scoreboard in the best way here????
    }
}

The main goal is to avoid if-else chains and switch-cases, since it's bad practice in OOP.
The possible solution what I see:
use some kind of ScoreboardParserFactory that returns necessary scoreboard parser depending on the scoreboard type.
Like:
var parser = _scoreboardParserFactory.Create(game.Scoreboard);
gameDto.Scoreboard = parser.Parse(game.Scoreboard);

But there are still the disadvantages:
1) It still doesn't look like I'll be able to make any implementation using only IoC and without long if-else/switch-case like:
if (scoreboard.GetType() == typeof(FootballScoreboard)) return new FootballScoreboardParser()
else if (scoreboard.GetType() == typeof(Formula1Scoreboard)) return new Formula1ScoreboardParser()
else ...

2) I'll still have to make explicit type conversion inside of parser's Parse method, like:
public class FootballScoreboardParser
{
    public ScoreboardDto Parse(Scoreboard scoreboard)
    {
        var footballScoreboard = (FootballScoreboard) scoreboard;
        return new FootballScoreboardDto() {/*...*/};
    }
}

Is any better way to implement the conversion from terms of high quality OOP code (without explicit type conversions and long if-else/switch-case)? Maybe there is any standard way of handling such cases? Any help from IoC in this?
Comment: This is exactly what IoC addresses. Use a container and register the parser for each type, then request from the container. No need for `if` statements.
Comment: @JuanRomero, thank you for the comment.Agree regarding IoC, but what about implementation of parsers (for ex. FootballScoreboardParser), we still will have to use explict type conversion, no any other ways, right? Isn't there any more beautiful approaches for implementation of this, without explicit type conversion (which is often recognized as smell code)?
Comment: You can achieve what you want using generics. Is the game the same or does it also vary?
Comment: @Juan Romer, game is the same (no derived supposed)
Answer: You could do it using generic interfaces:
public class DtoParserFactory
{
    private Dictionary<Type, IDtoParser> _parsers = new Dictionary<Type, IDtoParser>();

    public void Register(Type type, IDtoParser parser)
    {
        _parsers.Add(type, parser);
    }

    public IDtoParser GetParser(IScoreBoard scoreBoard)
    {
        var type = scoreBoard.GetType();
        var parser = _parsers[type];
        return parser;
    }
}

public class SomeScoreboardParser : BaseScoreBoardParser<SomeScoreboard, ScoreboardDto>
{
    public override ScoreboardDto Parse(SomeScoreboard scoreBoard)
    {
        return new ScoreboardDto();
    }
}

public abstract class BaseScoreBoardParser<TScoreBoard, TDto> : IDtoParser<TScoreBoard, TDto> where TScoreBoard : IScoreBoard where TDto: IDto
{
    public abstract TDto Parse(TScoreBoard scoreBoard);
    public IDto Parse(IScoreBoard scoreBoard)
    {
        return Parse((TScoreBoard)scoreBoard);
    }
}

public interface IDtoParser<TScoreBoard, TDto> : IDtoParser
    where TScoreBoard : IScoreBoard
    where TDto : IDto
{
    TDto Parse(TScoreBoard scoreBoard);
}

public interface IDtoParser
{
    IDto Parse(IScoreBoard scoreBoard);
}

public class ScoreboardDto : IDto
{

}

public interface IDto
{

}

Then consume it:
var game = new Game();
DtoParserFactory factory = new DtoParserFactory();
factory.Register(typeof(SomeScoreboard), new SomeScoreboardParser());
var parser = factory.GetParser(game.Scoreboard);
var dto = parser.Parse(game.Scoreboard);

You just need to register your types in the factory and it will resolve them for you. This is the line that does that in the code sample:
factory.Register(typeof(SomeScoreboard), new SomeScoreboardParser());

This is [obviously] an oversimplified example I wrote on the fly. There are a few things that can be improved. This is just meant to illustrate the point.
Comment: thank you for the comment again. Your example actually is a bit different from my case - as I told in the description there is an ability to know what time of the scoreboard only in runtime, so I cannot write things like:

DoGame();
Let's say I have a list of games that I need to parse, and every game may have its own type of scoreboard.
Comment: I suspect that in my case there is no way to avoid explicit type conversion in parsers ?..
Comment: @TOL: OK. I modified the example to work the way you want it.
Comment: Juan, thank you for the answer. It's the most beautiful and safe usage of explicit type conversion, but it's still explicit type conversion (here I mean: return Parse((TScoreBoard)scoreBoard);). Do you think it's fine to use such kind of things (as explicit type conversion) in well OOP designed application? Is it the best implementation what possible to do in such case?


What advantages does Features offer in deploying changes

Question: What advantages does using features to manage deploying changes (versus keeping code updated and data fresh)?
The Features way (near as I can discern):
Features takes configuration (which is 'content') re-envisions it as code and builds a module for it, and then pushes it up where it continues to live as an object that has to be maintained as code forever.
The next time the developers update their code, (where the best would include updating their dev database to a fresher copy of production), they get these configuration changes that they too have to manage in perpetuity.
The not really doing anything special way
The original developer updates the configuration on production, (after ironing out these changes in development), then we are done worrying about that configuration change, forever.
The next time the developers update their code, (where the best would include updating their dev database), the configuration changes are included.  No one ever has to worry about overrides and reverting ever.
Obvious Caveat:
If the original developer changes 103 individual settings, remembering and setting them all would be nightmarish.  In this case I would understand using a configuration packager, which is more or less how Features is used, to set the production system to match. But then what?  I don't understand keeping that project alive after you have updated the settings on prod to match what you did in development.  Features as a fire and forget config missile, I get... as code... I don't get maintaining it after the fact.
===================================
I started out this post open to Features, after it was regaled by some incredibly trustworthy Drupal gurus.  I had a bad feeling about it, but hoped it would wane.  After writing this, again find myself frustratingly opposed to something everyone else seems to think is the best thing since sliced servers.
The features ideals I can't wrap my brain around:
I have always approached Drupal with a philosophy less eloquently described by one aforementioned gurus as: "Content comes down, code goes up."
In Drupal 7, configurations for the system and modules is stored in the database.  The dotted line I've drawn in my perception demarcates content from code is right on that line; code is stored in files managed in Git, content is entered into the UI and stored in the DB.
Using Features for Structure:
On my gut feeling about exports and features, another Guru said: "It's going to end up in a file one way or another".
I didn't argue at the time because I wasn't seeing his perspective and wasn't comfortable calling him on it (guru vs. marginally experienced flounder).
I've never thought about it because I wasn't using the paradigm he was thinking about (developer).  I had always just imported the structure, because my brain is always in a different paradigm (site builder) when I'm working with structure.
I haven't ever done it the way he described.  It is actually clever, and I can see using that method in certain cases.  I realized later when my brain was back in developer mode that I have done something similar this, in a different sort of way; I use Form Builder to build rough forms quickly, then drop them into my code, I don't export them, because Form Builder gives you access to the code for their construction as you build them out.
This makes me hesitant to say "Features is teh Ahhsumz"
So what am I missing?
Comment: In reference to my concern that you end up with moldy features that exist just to get in the way of other features at some point: [autopoetic][2] via [Adam Balsam][3] points [in this answer](https://drupal.stackexchange.com/questions/59876/remove-features-without-lose-functionality) out that those can be cleaned up with the [Features Tools Module][4]. [2]: http://drupal.org/user/271093
[3]: https://drupal.stackexchange.com/users/11462/adam-balsam
[4]: http://drupal.org/project/ftools
Answer: You seem to have mentioned the use-case of Features only as a configuration packer, probably with strongarm, or with structure - where you would not use the code once it is run and has made its changes in the database.
But one of the important uses of Features is ctools exportables, such as Views, rules, etc... Here, the settings are much more complex than '103 configuration options' and if you are dealing with multiple developers, a staging site and then production, you can't imagine doing all of this manually on all different servers and instances.
Comment: Problematic? Yes, definitely... but that's just because it is not built into Drupal. Of course, that changes when Drupal 8 gets out (even for fields and some configuration). But I see your point. I still feel that you will see the benefit sometime, and I don't think tutorials will help you here. This would be something you would decide if it works for you, and so far it seems like you don't need it, and that's good.
Comment: Forgive me for being obtuse... trust me this is worse for me than it is for you, and it isn't intentional.

That's just it... For Views for instance: I would just export my view when I had it how I wanted... and then import it into production, and instruct the team to grab the latest copy of the DB when it was propagated...
I'm not seeing why Features is superior, but I'm seeing why it might be problematic...
Guess I'll have to watch a few video tutorials on the subject. God I hate video tutorials.
Answer: As a Drupal developer, I find that there is a virtual ocean of tricks and tips out there that don't make much sense at first, but then grow on you as you use them.  Features is one of them.  Here are a few points to keep in mind (you probably know most of this):

Using Development and Test servers are an absolute must.
Drupal updates are often complicated and require plenty of trial and error (and advice.)
Manual Live updates are bad.  You won't get it exactly right the first time every time.
Sometimes manual Live updates are unavoidable, be sure to practice a few times on test.
Otherwise, have an established method for moving updates from production to test to live.
Almost all of your (back-end) site updates will change the database in some way.
Content does indeed move down and changes move up.
If you don't separate database updates from content, content will (eventually) be lost.
To minimize loss, take the site off-line and be as quick as possible or...
If you can separate updates from content, you will not need to download/manage content.
Features automatically separates database updates from content.
automatic processes are faster, more accurate and more reliable in the long run.
It is still important to move content to test to insure that your changes won't break things.
Features improves to process of adding, storing, sharing and reverting updates.
If there happens to be a problem with your update, reverting a feature is FAST.
There are cases were you can publish your update to additional sites using features.
features is a form of encapsulation and encapsulation is good.


Nameservers on CPanel/WHM, with No IP?

Question: I added two nameserver with the same IP on initial setup and now in Main >> DNS Functions >> Nameservers IPs I see my Nameservers with No IPs
How Can I fix this?
Thanks
Comment: This question appears to be off-topic because it is about [`working with a service provider's management interface, such as cPanel`](http://serverfault.com/help/on-topic).
Answer: I think I found why this happens, because cPanel can't resolve nameservers it display "No IPs" even if it's setup correctly.
Some times this issue can be fixed by editing <code>/etc/nameserverips</code>

Nameservers on CPanel/WHM, with No IP?


mapbox expression to filter feature property of layer (feature id) by array of ids

Question: I'm using Mapbox GL JS 1.12.
I'm trying to selectively extrude buildings by feature id. I have successfully filtered data from the 'building-extrusion' layer in Mapbox Studio to achieve this effect. However, I'm keen to know the code way so that i don't have to manually enter a long list of ids into the input form on the UI.
Here's a way I felt is intuitive and correct to me based on what i gather from the documentation and other code snippets online.
     let filter=[
       "any",
       ["in", [123456, 245085, 435086], ["to-number", ["get", "id"]]],
       ['==', 'extrude', 'true']
     ]
     map.setFilter('some-buildings-3d',filter)

Errors:

Error: layers.some-buildings-3d.filter[1][1]: string expected, array
found
Error: layers.fire-stations-3d.filter[1][2]: string, number, or
boolean expected, array found

I'm using the defualt 'composite' source to add layer;
map.addLayer(
  {
    'id': 'some-buildings-3d',
    'source': 'composite',
    'source-layer': 'building',
    'type': 'fill-extrusion',
    'paint': {
        'fill-extrusion-color': '#aaa',
        'fill-extrusion-opacity': 0.6
    }
  },labelLayerId
);

Rather than continuing to mindlessly trial-and-error, does anyone at StackO has experience with Mapbox expressions to filter data and know of the right approach?
Comment: Could you please create a minimal setup, to see where you are getting those error's?
Answer: the syntax of in is:
["in",
    keyword: InputType (boolean, string, or number),
    input: InputType (array or string)
]: boolean

i think you need any.
[
  "any",
  ["in", 123456, ["to-number", ["get", "id"]]],
  ["in", 245085, ["to-number", ["get", "id"]]],
  ["in", 435086, ["to-number", ["get", "id"]]],
]


Counting number of partial flags

Question: For a tuple ${m_{1},...,m_{s}}$, $\sum _{i}m_{i}=n$,
call a collection of subspaces $V_{1}\subset ... \subset V_{s}=n$,
such that the dimension of $V_{i}/V_{i-1}=m_{i}$ a partial flag of the type ${m_{1},...,m_{s}}$
Denote it by $V_{\bullet }$. The set of such flags is denoted by $Fl({m_{1},...,m_{s}})$.
Find the number of elements in the set $Fl({m_{1},...,m_{s}})$.
We are discussing nilpotent elements and jordan normal form theorem
Comment: You need to provide more details. Is $V$ a complex vector space? or is it defined over a finite field? In the former case, the set is infinite.
Comment: Sorry forgot to add, V is defined over a finite filed of p element.
Comment: Hint: Start with an easier case, the set $Fl(m)$, in other words the set of $m$-dimensional subspaces of $V$. (This is also called the Grassmannian.) Do you know the number of elements in $Fl(m)$? Once you have worked that out, you can proceed by induction.
Comment: Sorry for asking for more clarification, I did calculate Fl(m), but I would like to know on what and how should I apply the induction
Comment: I am not sure if it is the sum or the product, or any other mathematical relation
Answer: This can be calculated inductively as follows:

Count the number of $m_1$ dimensional subspaces of $V$.
Having chosen an $m_1$-dimensional subspace $V_1$, the number of partial flags in $V$ containing $V_1$ is the same as the number of flags in the $(n-m_1)$-dimensional vector space $V/V_1$ of type $m_2,\ldots,m_s$.

Putting (1) and (2) together, you deduce that the number of flags of type $m_1,\ldots,m_s$ is equal to the number of $m_1$-dimensional subspaces of $V$ multiplied by the number of flags of type $m_2,\ldots,m_s$:
$$Fl(m_1,\ldots,m_s)=Fl(m_1)Fl(m_2,\ldots,m_s).$$
So, the key is to obtain the count in (1). Can you finish?

Counting number of partial flags


Is it possible to have multiple websites, with different domain names, on the same Rails application?

Question: I have a few different small websites, and for each one I have a hobby-level hosting plan that supplies way more bandwidth/storage than any of them individually need. Furthermore, every time I make a change to the stack I use, for example when I start using a newer version of a gem, I have to update each of them separately, and I have to run separate tests for each of them. There are also identical tables that each one has, for example Admin and Error.
So I've started to think about whether it would be possible to combine them into one single app, maybe with separate Controller folders that are treated as root by different domain names. Anyone have any experience hosting different websites from the same code base? Is this even possible?
Update:
To add some more context, I want to host the whole thing on one server, possibly with one database, but with multiple controller folders that each represent a different website and a different domain. For example, I currently have smallapp.com and lilsite.com, and I'm paying for the same hosting plan for both (that is in excess for both their needs), and they both have an identical Error model, and I update both whenever I start using a new gem version. They're also using the same gems and libraries. Ideally, I would have an app called superapp, hosted with only one instance of the same hosting plan, sharing one SSL cert, that would have two controller folders called smallapp and lilsite. The route "www.smallapp.com" would somehow point to the /smallapp/home.html path, and vice versa. Users on both smallapp.com and lilsite.com could create errors in the same database, but they could never view files in the other's controller.
Comment: If the models / controllers are more or less the same, you could have a look at `Apartment` gem to split your site into multiple separate sites. But as soon as there are some differences in the code, you are probably still better off to keep them as separate applications. It will become very cumbersome to manage individual changes.. you could consider to move parts of the application into microservices though, that each of your separate apps can leverage. For instance for managing comments, or logins.
Answer: Without knowing the full context yes it's hard to provide the best solution, but its possible.
Yes @bo-oz is correct you could use Apartment gem for this. We currently use this where I work.
You could also just have 2 servers that deploy off the same repo/code base.
Specifically, you could have 2 Heroku servers that deploy off the same github repo. Then have 2 separate domains. When you deploy you will just deploy both servers off your master branch.
Comment: Interesting. Do you know if it's possible to have 2 separate domains, but on the same server?
Answer: It is possible.

All the domains have to point to the same IP address which is the address of your server. For that you need to change the domains DNS settings.
The web server (such as Nginx) has to direct all the requests (from all domains) to the same Rails application.
In the Rails application the routes have to point to different controllers based on a domain. request.domain is available in the 'routes.rb' file. See this question for more information Rails routing to handle multiple domains on single application

Keep in mind that requests from different domains will not share the same session. That's possibly not what you want.
Comment: 1. is not necessary true : a same server can have multiple IPs assigned, and Nginx using them in multiple server blocks


Embed form (has many) with activeadmin

Question: I am making a blog using rails and activeadmin. I associate tags to each post. I want to know how to configure activeadmin to add tags on posts.
I want to be able to create tags from a new Post form. How can i do that?
Thank you
Answer: if Posts has_many Tags then something like this could work.
form do |f|
  f.inputs do
    f.input :title
    f.input :content
    f.has_many :tags do |fu|
      fu.input :name
      fu.input :_destroy, :as=>:boolean, :required => false, :label => 'Delete Tag' unless fu.object.new_record?
    end
  end
end

ActiveAdmin expects that the Post model accepts_nested_attributes_for :tags
like..
class Post
  #....
  accepts_nested_attributes_for :tags
end

Embed form (has many) with activeadmin


Want to prove that some $\mathbb R[x]$-Module has no basis

Question: So here is my question,
Consider the $\mathbb R[X]$-module $\mathbb R[X,X^{-1}]$ i.e the $\mathbb R[x]$-module of all Laurent-Polynomials. I want to show that is module is not free i.e it has no basis.
I already feel I see the problem, since if one multiplies an element $p(x)\in\mathbb R[X^{-1}]$ with some element of the ring $\mathbb R[X]$ it is only possible to increase the degree of $p(x)$ but it is not possible to decrease it.
Moreover, I think if we I assume for contradiction that there exists a basis 0f $\mathbb R[X,X^{-1}]$ than it contains at least some reel constant $c$ as basis of $\mathbb R[X]\subset\mathbb R[X,X^{-1}]$. Then every basis has to be of the form $\{c,p_1,p_2,...\}$ where $p_i\in\mathbb R[X,X^{-1}]$ - $\mathbb R[X$] i.e is some polynomial of degree strictly less the zero. And this polynomials can not be linear independent since one can always increase the degree until it becomes again positv...?
Answer: Let $K$ be any field (nothing special about the real numbers here). Suppose $K[X,X^{-1}]$ were a free $K[X]$-module on some basis with cardinality $\gamma$ (finite or infinite). You already argued that $\gamma=1$ is not possible.
Now this would imply $K[X,X^{-1}]\otimes_{K[X]}K(X)$ is a $K(X)$-vector space of dimension$~\gamma$. But is is actually a $K(X)$-vector space of dimension$~1$, since any two elements of $K[X,X^{-1}]$ are obviously linearly dependent over$~K(X)$. Contradiction.
Comment: Nice use of scalar extension!
Comment: So, while it isn't free, it does have rank $1$.
Answer: Suppose $\mathcal{B}$ is a set of generators for $\mathbb{R}[X, X^{-1}]$ as an $\mathbb{R}[X]$-module. There must be terms of arbitrarily low lowest term, since - as you've correctly noted - multiplying elements of $\mathbb{R}[X, X^{-1}]$ by elements of $\mathbb{R}[X]$ can only increase the degree of the lowest term. So in particular, $|\mathcal{B}| = \infty$
But $1$ can be written as a finite $\mathbb{R}[X]$-linear sum of elements of $\mathcal{B}$, say $1 = f_1b_1 + ... + f_rb_r$. Let $b \in \mathcal{B}$ be such that $b \neq b_i$ for all $i$, and assume the lowest term of $b$ is degree $r < 0$. Then $bX^r \in \mathbb{R}[X]$ (and $bX^r \neq 0$).
But now $(f_1bX^r)b_1 + ... + (f_rbX^r) - bX^r$ is a non-trivial $\mathbb{R}[X]$-linear relation between elements of $\mathcal{B}$, so $\mathcal{B}$ cannot be a basis.
Comment: Thank you! This answer really helped me!
Answer: Observation: Any two nonzero $\Bbb R[x]$ submodules of $\Bbb R[x,x^{-1}]$ intersect. If $M$ and $N$ are two such submodules and $a\in M$, $b\in N$ are nonzero elements. You can find powers of $x$ such that $x^ia\in \Bbb R[x]$ and $x^kb\in \Bbb R[x]$, and then you can find their gcd in $\Bbb R[x]$. That is, there exist $p,q$ such that $px^ia=qx^kb\in M\cap N$, showing the intersection is nonzero.
Using that observation, if $\Bbb R[x,x^{-1}]$ were free, it could not have more than one copy of $\Bbb R[x]$ in its decomposition. That would mean $\Bbb R[x,x^{-1}]$ is a cyclic $\Bbb R[x]$ module. But as you observed, no single element would suffice to generate all of $\Bbb R[x,x^{-1}]$, since the set of things a single element can generate has a definite lower bound on its degree.
Answer: Here is a base-free argumentation. Let us assume that $\mathbb{R}[X^{\pm 1}]$ is a free $\mathbb{R}[X]$-module then it is also projective. Let $g : \mathbb{R}[X,Y] \to \mathbb{R}[X^{\pm 1}]$ be the surjective $\mathbb{R}[X]$-algebra-homomorphism mapping $Y \mapsto X^{-1}$. Now by projectivity there is a $\mathbb{R}[X]$-module-homomorphism $f : \mathbb{R}[X^{\pm 1}] \to \mathbb{R}[X,Y]$ such that $g \circ f = id$. This leads easily to a contradiction: because of $X^n \cdot f(X^{-n}) = f(1) \in \mathbb{R}[X,Y]$ we see that $X^n$ divides $f(1)$ for all positive integers $n$ which forces $f(1)=0$. But then $X = gf(X) = X \cdot gf(1) = 0$.
Of course this argument still works if we replace $\mathbb{R}$ by any other (nonzero) commutative ring.


Subset Relation is What Kind of Relation?

Question: I have to determine whether the $\subseteq$ relation is reflexive, symmetric, transitive and serial.
I'm slightly confused as to how to begin
I know that $A\subseteq B$  iff $\forall x (x\in A \rightarrow x\in B).$
And I have quantified definitions of reflexivity, symmetry, seriality, transitivity:
R is reflexive iff $\forall x Rxx$.
R is symmetrical iff $\forall x,y  (Rxy \rightarrow Ryx)$.
R is transitive iff $\forall x,y,z (Rxy \land Ryz \rightarrow Rxz)$.
R is serial iff $\forall x \exists y Rxy.$
I understand these in the abstract. But I'm confused about how knowing the definitions of the relevant kinds of relations and the definition of $
\subseteq$ can help me determine whether $\subseteq$ is reflexive, symmetrical, transitive and/or serial.
Does anyone have any advice about how to proceed? (I've read through a similar question posted from 3 years ago but it does not help me understand how to go about doing this problem).
Comment: Apply the def... $A \subseteq A$ iff $\forall x (x \in A \to x \in A)$.
Comment: This sound good... thus: $\forall x (A \subseteq A)$ and the $\subseteq$ rel is reflexive.
Comment: And so on......
Comment: You have to consider that the expression $x \subseteq y$ has the same "form" of $xRy$. It is a binary relation between sets.
Comment: Symmtery: in general no. If $A \subseteq B$, not necessarily we have also $B \subseteq A$ (otherwise $A=B$).
Answer: Reflexive: Is it true for all sets $A$ that $A\subseteq A$?
Symmetric: Is it always true that if $A\subseteq B$, then $B\subseteq A$?
Transitive:  Is it always true that if $A\subseteq B$ and $B\subseteq C$, then $A\subseteq C$?
Answer: Instantiating your definitions, you have:

$\subseteq$ is reflexive if $\forall A,\ A \subseteq A$
$\subseteq$ is symmetric if $\forall A,B,\ A \subseteq B \Rightarrow B \subseteq A$
$\subseteq$ is transitive if $\forall A,B,C,\ (A \subseteq B \wedge B \subseteq C) \Rightarrow A \subseteq C$
$\subseteq$ is serial if $\forall A,\, \exists B,\, B \subseteq A$

You should use the given definition of $\subseteq$ to check which of these conditions hold and which do not.
I'll get you started with a proof that $\subseteq$ is reflexive. Let $A$ be a set. We need to prove $A \subseteq A$. For all $x$, the statement $x \in A \Rightarrow x \in A$ is certainly true, and hence $A \subseteq A$ is true. So $\subseteq$ is reflexive.


Expanding a mySQL table using only mySQL

Question: Let's say I have a mySQL table whose structure is like this:
mysql> select * from things_with_stuff;
+----+---------+----------+
| id | counter | quantity |
+----+---------+----------+
|  1 |     101 |        1 |
|  2 |     102 |        2 |
|  3 |     103 |        3 |
+----+---------+----------+

My goal is to "expand" the table so I end up with something like:
mysql> select * from stuff;
+----+---------+
| id | counter |
+----+---------+
|  1 |     101 |
|  2 |     102 |
|  3 |     102 |
|  4 |     103 |
|  5 |     103 |
|  6 |     103 |
+----+---------+

And I want to do this "expansion" using only mysql.  Note that I end up with a row per quantity and per counter. Any suggestions?  A stored procedure is not an option here (I know they offer while loops).
Thanks!
Comment: I wanted to comment on [marcos'](http://stackoverflow.com/users/925801/marcos) answer above, but I am on a karma diet. Your large table doesn't have to be as big as the sum of all quantity, it only has to be as big as the largest single quantity - viz. 3 in this example (as opposed to 6 if it had to be the full sum). I still think it would be valuable to have a way to generate that table (or the rows) on the fly. OP: why are stored procedures not an option?
Answer: The following will do the trick as long as some_large_table has a length greater than or equal to the largest quantity in things_with_stuff. For example, let some_large_table be a big fact table in a data warehouse.
SELECT @kn:=@kn+1 AS id, counter
FROM (SELECT @kn:=0) k, things_with_stuff ts
INNER JOIN (
    SELECT @rn:=@rn+1 AS num
    FROM (SELECT @rn:=0) t, some_large_table
    ) nums ON num <= ts.quantity;

Comment: Btw, wrap the query in a CREATE TABLE stuff ( ... ); statement as needed
Answer: Assuming there is a maximum value for quantity, you could do:
INSERT INTO things SELECT counter FROM things_with_stuff WHERE quantity > 0;
INSERT INTO things SELECT counter FROM things_with_stuff WHERE quantity > 1;
INSERT INTO things SELECT counter FROM things_with_stuff WHERE quantity > 2;
--... and so on until the max.

It's a bit of a hack but it should do the job.
If the ordering is important you could do a clean up afterwards.
Answer: I have sometimes in databases a table named num (number) with a single column i, filled with all integers from 1 to 1000000. It's not hard to make such a table and populate it.
Then you could use this if stuff.id is auto incremented:
INSERT INTO stuff
( counter )
    SELECT ts.counter
    FROM things_with_stuff AS ts
      JOIN num
        ON num.i <= ts.quantity

Comment: Wait, what? You can do `JOIN ON a <= b`? Is this normal SQL or just some MySQL-special thing?
Comment: @Alexandr: I think all decent RDBMS allow that. Besides (not so decent) MySQL.
Comment: That's awesome. I think my mind just exploded with stuff I could do with this. Then it hit he, by the time I have use for any of it, I've forgotten xD.
Comment: See ***`(theta) θ-join`***: http://en.wikipedia.org/wiki/Relational_algebra#.CE.B8-join_and_equijoin
Comment: If we can come up with sql to generate that list of integers to use as an inner select rather than needing to precompute num, I think this might just work!


Parameters of LDA

Question: I was learning from  Elements of statistics p.109  under the topic LINEAR DISCRIMINANT ANALYSIS
and I saw the function below for linear discriminant function
$\delta_k = X^T\sum^{-1}\mu_k -\frac{1}{2}\mu_k^T\mu_k+ \log\pi_k$
where
$\pi_k = N_k/N$ where $N_k$ is the number of class-k observations;
$\mu_k$ = $\sum_{g_i = k} x_i/N_k$
$\sum = \sum_{k=1}^k\sum_{g_i = k}(x_i - \mu_k)(x_i - \mu_k)^T/(N - K)$
Please I want know the parameters for this function (I am thinking is $\mu_k$ ) and how come it has (K-1) x (p + 1) parameters
Answer: Below is the answer quoted from Xiaozhou's note.

For LDA, (p+1) parameters are needed to construct the discriminant function in (2). For a problem with K classes, we would only need (K-1) such discriminant functions by arbitrarily choosing one class to be the base class (subtracting the base class likelihood from all other classes). Hence, the total number of estimated parameters for LDA is (K-1)(p+1).

Mean: p
Class prior: 1

function (2):
$$
\delta_k(\mathbf{x})=\mathbf{x}^T \boldsymbol{\Sigma}^{-1} \mu_k-\frac{1}{2} \mu_k^T \boldsymbol{\Sigma}^{-1} \mu_k+\log \pi_k
$$

Parameters of LDA


Adding a function to keyword values

Question: i have a map structure like this...
    {"email@example.com"{:email "firstname.lastname@example.com", :password "pass"},
    "email@example.com"{:email "firstname.lastname@example.com", :password "pass2"},
    "firstname.lastname@example.com"{:email "firstname.lastname@example.com", :password "pass3"},
    "firstname.lastname@example.com"{:email "email@example.com", :password "pass4"}}

how can i add a function to all values in refering to :password keyword?my function has a parameter that accepts only strings...this is what i tried but couldn't got around it...
(update-in mymap [:password] (myfunction "here were suppose to be values from :password keyword"))
Answer: You should update each line separately and accumulate, so iterate with reduce over the list, then for each element update-in the password key and assoc the resulting row to the result.
(reduce (fn[result row]
          (assoc result
                 (first row) ;;email
                 (update-in (second row)
                            [:password]
                            (fn[pass] ..do something..))))
        {}
        mymap)

Answer: (reduce-kv (fn [result k cfg-map]
             (assoc result
               k (update-in cfg-map [:password] your-fn)))
           {} your-ds)

or
(into {} (mapv #(update-in % [1 :password] your-fn) your-ds))

Adding a function to keyword values


Specialization of templated method in a templated class

Question: I have a simple template class with a template method in it:
#include <iostream>
#include <optional>

template <typename T>
class Test
{
public:
    template <typename U>
    std::optional test() { return std::nullopt; }

    std::optional<double> test() { return std::make_optional<double>(3.0); }
};

int main()
{
    Test<int> t;
    std::cout << t.test<int>().value_or(100) << " " << t.test<double>().value_or(100) << std::endl;
}

I'd like the program to print 100 3.0 or 100 3 rather than 100 100. How do I specialize the test method within Test such that it returns a non-empty optional with value 3.0?
In addition to the above, I've tried to add template<> above the specialization. This results in a compiler error (running gcc -std=c++17 test.cpp with GCC 9.4.0):
test.cpp:11:14: error: explicit specialization in non-namespace scope 'class Test<T>'
   11 |     template<>
      |

Comment: What you have above is not a specialization but an overload. You cannot specialize a member template without also specializing its enclosing class.
Comment: @user12002570 It is not that bug. Try moving the specialization out of the class scope.
Comment: This is a well known [gcc bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85282). Dupe: [Explicit specialization in non-namespace scope does not compile in GCC](https://stackoverflow.com/questions/49707184/explicit-specialization-in-non-namespace-scope-does-not-compile-in-gcc)
Answer: You can specialize test for double in the following way:
#include <iostream>
#include <optional>

template <typename T>
class Test
{
public:
    template <typename U>
    std::optional test() { return std::nullopt; }

    // Specialization for double:
    template <>
    std::optional<double> test() { return std::make_optional<double>(3.0); }
};

int main()
{
    Test<int> t;
    std::cout << t.test<int>().value_or(100) << " " << t.test<double>().value_or(100) << std::endl;
}

Output:
100 3

Update:
This solution works for MSVC, but not for GCC. See more info here, and here.
A possible workaround for GCC is to use if constexpr instead of a specialization:
template <typename T>
class Test
{
public:
    template <typename U>
    std::optional test()
    {
        if constexpr (std::is_same_v)
        {
            return std::make_optional<double>(3.0);
        }
        return std::nullopt;
    }
};

Comment: @n.m.couldbeanAI I see. I guess the `if constexpr` workaround is better then, in terms of complying with the standard.
Comment: What compiler command and version are you using?
Comment: VisualStudio 2022 (MSVC)
Comment: I now see [this](https://stackoverflow.com/questions/3052579/explicit-specialization-in-non-namespace-scope), which means MSVC is non-standard in this case ...
Comment: @wohlstad The standard has been fixed (but GCC was not). Explicit specialization is allowed at any scope a primary template definition is allowed. However an explicit specialization of a member of an unspecialized template doesn't seem to be legal (the standard is not very clear about this).


Application is not launching in the ZAP Chrome/Firefox Broswer

Question: I am using ZAP 2.12.0 Cross Platform Package. I have installed openjdk version "17.0.2".
When I try to manually explore any web application, It opens the browser(Chrome or Firefox) but the application is not loading. I get the error message "Failed to read "http://xyx.com within 60 seconds, check to see if the site is available and if so consider adjusting ZAP's read timeout in the connection options panel.

Am I missing anything here?
Answer: This is usually not a ZAP problem.
Is your web application actually running?
Can you connect to it using the IP address rather than the FQDN or hostname?
Can you connect to your application from the same machine using another tool like curl?
Do you need to configure an upstream proxy in order to connect to the web app?
Comment: I have tried in normal Chrome & Firefox browsers. The applications worked fine. This is happening only in the browser opened through ZAP. I tried for 3 to 4 different web applications.
Comment: Have those browsers been configured to use an upstream proxy? That might have been done automatically for you - check their configs. Also try curl from the command line.
Comment: I asked many people in our workplace, almost all have same issue. Cross Platform Package doesn't work properly in Open JDK 17. Earlier we were using ZAP in Oracle JDK. It worked fine without any issue in both Chrome & Firefox browsers.
Comment: How to update the ZAP Chrome driver compatible with the browser installed ?
Comment: Update the ZAP add-ons - we update the webdriver add-ons whenever new webdrivers are released. If for some reason you have to use an older browser then you will need to find the correct webdriver and install that yourself. The Selenium Options screen allows you to select your own webdriver file.


What's a proof that a set of disjoint cycles is a bijection?

Question: Consider a function $f : D \to D$ (where $D$ is a finite set) so that for every $d \in D$, there is an integer $n$ so that $f(f(...(n\text{ times})...f(d)...) = d$.

Prove that $f$ is a bijection.
Prove that if $f : D \to D$ (where $D$ is a finite set) is a bijection, then for every $d \in D$, there is an integer $n$ so that $f(f(...(n\text{ times})...f(d)...) = d$.

I know this proposition is true (because a bijection over a finite set is just a permutation which is always representable using cycles), I'm just having a hard time formulating a proof for it that a first-year algebra student could understand.
Comment: $f$ has finite order, so it has an inverse.
Answer: If you want to use a minimum of machinery, I don't think that you can get too much simpler than these:
(2) Fix $d\in D$ and consider the sequence $\langle d,f(d),f^2(d),f^3(d),\dots\rangle$; $D$ is finite, so there must be distinct $i,k\in\Bbb N$ such that $i<k$ and $f^i(d)=f^k(d)$. Since $f$ is a bijection, it has an inverse $g$. Let $n=k-i$, so that $f^k(d)=f^i\big(f^n(d)\big)$. Then $$d=g^i\big(f^i(d)\big)=g^i\big(f^k(d)\big)=g^i\big(f^i\big(f^n(d)\big)\big)=f^n(d)\;.$$
(1) To show that $f$ is injective, suppose that $f(d)=f(e)$ for some $d,e\in D$. There are positive integers $m$ and $n$ such that $f^m(d)=d$ and $f^n(e)=e$. But then by an easy induction $f^{km}(d)=d$ and $f^{kn}(e)=e$ for all $k\in\Bbb N$, and therefore $d=f^{mn}(d)=f^{mn}(e)=e$.
To show that $f$ is surjective, merely observe that if $d\in D$, then there is $n\in\Bbb Z^+$ such that $d=f^n(d)=f\big(f^{n-1}(d)\big)\in\operatorname{ran}f$.
Answer: For the "prove $f$ is a bijection" part (i.e. #1): We first show $f$ is injective. So, suppose $f(a) = f(b)$, where $a, b \in D$. Now, for $a$ and $b$ there exist positive integers $n$ and $m$ such that $f^n(a) = a$ and $f^m(b) = b$ (where $f^n$ is the standard notation for iteration: $f^n = f \circ f \circ f \circ \cdots \circ f\ (n\ \mathrm{times})$, and $f^0 = \mathrm{id}$, the identity function.). These equations give $f^{n-1}(f(a)) = a$ and $f^{m-1}(f(b)) = b$. Now, since $f(a) = f(b)$, we have $f^{m-1}(f(a)) = b$. That is, $f^m(a) = b$. Now also, $f^{n-1}(f(b)) = a$ thus $f^n(b) = a$. What $f^m(a) = b$ shows is that the cycle containing $a$ also contains $b$, thus the two cycles are not disjoint, and are in fact the same cycle. Thus, $f^n(b) = b$ as well (note that a period of one point in a cycle is a period of every point), and so $a = b$.
Now to show $f$ is surjective. Suppose $a$ is an element of $D$. Then, we want to find a $b$ for which $f(b) = a$. Since $f^n(a) = a$ for some $n$, we have $f(f^{n-1}(a)) = a$, and so $b = f^{n-1}(a)$ will work.
So, $f$ is both injective and surjective. Thus, $f$ is bijective.
For the "converse" part (i.e. #2): Suppose $f$ is bijective. Now, consider $f^n(a)$ for some $a \in D$ and positive integers $n$. Now, there are only finitely many possibilities for $f^n(a)$, so there must be some n for which $f^n(a) = f^m(a)$ for some m <= n. Then, since $f$ is bijective, it is invertible, and we have the existence of the negative iterate $f^{-m} = (f^{-1})^m$, which is the inverse of $f^m$, and we can apply that to both sides to get $f^{n-m}(a) = a$.
Q. E. D.
Comment: Your answer is the closest thing to what I was thinking of when I was trying to write a proof. Thanks.
Answer: (1) First we prove that $f$ is surjective.
let $d \in A$. We know that $f[ f(f...f(d)))]=d$. Let $y=$inside of the $[ ...]$ then $f(y)=d$.
Now we prove that any surjection $f:A \to A$ is also injective.
Assume by contradiction that $f(a)=f(b)$ for some $a,b$. Let $n$ be the number of elements of $A$, then $A \backslash \{ a, b\}$ has $n-2$ elements.
Thus $f(A \backslash \{ a, b\} )$ has at most $n-2$ elements. Thus $f(A)=f(A \backslash \{ a, b\} ) \cup \{ f(a) \}$ has at most $n-1$ elements, which contradicts the fact that $f$ is onto.
2 Look at $f^n(d)$. Then, there exists two elements $n <m$ so that
$$f^n(d)=f^m(d) \,.$$
Thus
$$f^n(d)= f^n(f^{m-n}(d)) \,.$$
Since $f^n$ is injective, we get $d=f^{m-n}(d)$.
Answer: 1)Clearly, $f$ is a surjection. Now we will verify that $f$ is injective. First we note that if $f^{n}(x)$ then for any positive integer $k$ ,$f^{kn}(x)=x$.
Let $f(d_1)=f(d_2)$. We find that there exists $m,n$ such that $f^{m}(d_1)=d_1,f^{n}(d_2)=d_2$ Thus, $f^{mn}(d_1)=d_1,f^{mn}(d_2)=d_2$. Since $f(d_!)=f(d_2)$, therefore $f^{mn}(d_1)=f^{mn-1}(f(d_1))=f^{mn-1}(f(d_2))=f^{mn}(d_2)$
Comment: How is it clear that $f$ is a surjection? On mappings of finite domains to themselves, injection and surjection imply each other.
Answer: For (1), it's easier to prove that if $f$ is not injective then neither is $f^{n}$ and if $f$ is not surjective then neither is $f^n$, for any $n \ge 1$. You know that $f^n$ is bijective, and hence so must $f$ be.
For (2), note that the bijections on a set form a group under composition, and that if $D$ is finite then this group is finite, so all its elements have finite order.
Comment: You're given an $n_d$ for each $d\in D$; to use your argument for (1) you'd have to start by taking the lcm $n$ of these $n_d$'s.
Comment: @BrianM.Scott that's acceptable. This is one part of a large question, and one of the parts of the question was to show that the LCM of all $n_d$ would turn $f$ into the identity.
Comment: @CliveNewstead I was hoping not to have to use the word "group" or "order", because I'm writing the proof for first-year algebra students who haven't learned about such things.


How can I redirect requests to specific files to pages hosted by other servers?

Question: When requesting for a local file, I would like to see a 301 redirection should lead to a page on a different server (an URL is provided). This can be usually done by using a simple Redirect directive, but this would cause some maintenance headache in my case: It does not support redirecting files (given their names) under specific directories that may frequently changes. For me, the best situation would be to use something similar to symbolic links with additional support for "linking" to URLs outside the host. In addition, with Options +Indexes, this "redirection" file can also be listed.
Comment: "This can be usually done by using a simple Redirect directive, but this would cause some maintenance headache in my case: It does not support redirecting files (given their names) under specific directories that may frequently changes." - Can you please give an example of the type of redirect you are referring to. The `Redirect` directive is prefix-matching, so it can be used to target whole/specific directories if you need it to.
Answer: Add this to the .htaccess file:
RewriteEngine On

# Makes Apache redirect only if the target file doesn't exist on this server
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^assets/(.*)$ http://your-file-storage.com/$1 [R=301,L]

This configuration makes all requests to http://your-app.com/assets/* be redirected to http://your-file-storage.com/*. For example, the URL http://your-app.com/assets/foo/bar.txt will be redirected to http://your-file-storage.com/foo/bar.txt.
The ^assets/(.*)$ string is a regular expression which tests URLs. If a URL fits the regular expression, it is redirected.
The http://your-file-storage.com/$1 string is the redirect target. The $1 is replaced with the regular expression parentheses content.
If you need many redirect rules, add many RewriteRule directives to the .htaccess file:
RewriteEngine On
RewriteRule ^assets1/(.*)$ http://your-file-storage1.com/$1 [R=301,L]
RewriteRule ^assets2/(.*)$ http://your-file-storage2.com/$1 [R=301,L]

Alternatively you can add a RedirectMatch directive to the virtual host configuration in the Apache configuration file:
RedirectMatch permanent ^/assets/(.*)$ http://your-file-storage.com/$1

It works the same way.
Answer: This may do the trick: RedirectMatch 301 .*/<filename> <redirect target>.
The wildcard .* tells Apache to match anything up to the actual file name, so the frequently-changing directories won't be a problem.
If you need to match specific directory names, and you have a finite list of them, you can list all of them in a single rule: RedirectMatch 301 .*/(dir1|dir2|dir3|...)/<filename <redirect target>.


Hearing a click track above an orchestra

Question: The amateur orchestra I am in, the Cambridge Concert Orchestra, are involved in the Somme100 FILM project which means we'll be performing Laura Rossi's score alongside the silent film footage. To keep things synchronised our conductor is given a click track so that she can conduct us perfectly in sync with the film.
One challenge we are facing is what to use so that the click track is audible over the sound of a full orchestra, especially for the bits where we are all going for it. We tried a simple in-ear bud style headphone on the audio-out of an Android tablet and that was too quiet.
What should we use to keep the click-track audible for our conductor?
Comment: You could probably have a visual version of a click track displayed on the tablet.
Comment: I like the idea of a visual click - like a dancing dot conducting a 4/4 pattern or whatever. But if that's not possible, does the audible click have to be on the strong beat? I've heard of drummers asking for a syncopated click - so they mentally have to construct the strong beats but because the click occurs in the gaps between strong notes it's easier to hear. Also can you change the sound of the click? A percussive sound might cut through better then an electronic beep. And is the conductor the only one who can hear the click? Or the whole orchestra?
Answer: A proper set of live-monitoring buds like InEar StageDiver or Shure SE215 should do the trick allright. These are, unlike HiFi buds, closed, thus attenuate the ambient sound; often quite strongly (so even the murderous volume at a metal concert doesn't prevent the drummer from hearing the click) but in the better models the sound remains reasonably clear, which is obviously important for a conductor. Custom-molded earpieces can be made with a wide range of attenuations, obviously not quite cheap. Still, the attenuation may be too much for the conductor to feel comfortable; you could add microphones to make up for this, but it's probably not worth it.
The alternative are closed studio headphones, which generally sound a bit more transparent. I think it's actually somewhat preferred in the classical sector to make it visually obvious if there's some monitoring track, so that shouldn't be an argument against. The reduced freedom of motion should be considered though.
Semi-open studio headphones are also possible, but that risks leaking the click signal to be audible from the outside.
Answer: I agree that a visual click is a good thing to try. But if you do an audio click, notice that turning it up louder is not the only option. You can also use a different click sound that has a different set of frequencies that aren't being obliterated by the sound of the orchestra. For example, a very high-pitched wood block might work better at medium volume than a typical pop-click at a higher volume. Ideally, you would experiment with different sounds until you find one that works for that particular conductor in that particular situation.


Why can't MLB teams trade draft picks?

Question: Why can't MLB teams trade draft picks like the NHL or NFL?
It would make for much more interesting drafts, and teams could "stock up" on young talent, then burn picks for veterans to make a playoff push like in many baseball simulation leagues.
But is there a reasoning behind not allowing MLB teams to trade draft picks beyond "the commissioner said 'NO'"?
Comment: Not an answer, but supplemental info-  It's also important to note that MLB has a significantly higher number of players that opt not to sign after being drafted and then re-enter the draft at a later time.
Comment: @JacobG very good point. This is a function of some NCAA rules which allow baseball players to enter/stay in school even after they have entered baseball's draft, something that is not allowed in other collegiate sports.
Answer: The MLB has no salary cap. Can you imagine if the Yankees wanted draft picks? They can get almost every pick they please.
In other words, "competitive balance" is the reason. In addition, the current expired MLB Collective Bargaining Agreement (CBA) does did not allow trading of draft picks.

However, in 2013, the new MLB CBA will let some teams trade some picks.
After the 2012 MLB Draft signing deadline passes, MLB's 10 smallest-market teams and 10 lowest-revenue teams (if a team is in both lists, they will count as BOTH a smallest-market AND lowest-revenue team – which means up to 20 (but most likely not 20) teams will fall under this umbrella) will be placed in a "Competitive Balance Lottery" – a product of the new CBA.
The odds of winning a draft pick through the lottery will be based on each team's winning percentage from the previous season (like the NBA). In the 2013 MLB Draft, there will be two groups of six lottery picks; one group after the first round, one group after the second round. The teams from the first group that did not win one of the picks from the first group will be re-entered in the lottery along with any other team that receives revenue sharing. However, only a team that wins a pick in the lottery can trade it, meaning the selection can be traded just once. Picks also can't be sold for cash, and may only be dealt during the regular season.
Answer: The simple answer here is that you cannot trade draft picks because the trading of draft picks is not allowed by the collective bargaining agreement.
The CBA for any American sport league lays out the terms on which the players and owners agree to run their sports league. It, along with unions and some other legal maneuvering are required in order to escape anti-trust regulations that are set up by the United States Congress to promote competition and limit monopolies. Because Sport Leagues are functionally monopolies there are special protections in place so that they can exist (primarily CBAs and Unions for players, coaches and officials) without serious legal repercussions. When players and owners cannot come to terms on a CBA you see the kind of legal maneuvering that the NFL and their players' association participated in last summer.
Baseball just signed a brand new collective bargaining agreement before this current season that is good for a number of years. While that brought numerous changes to the draft, the trading of draft picks was not one of the changes that was made.
Comment: note: I feel like I've read something about possible amendments during this collective bargaining period that may include both the trading of draft picks and an international draft of some kind.

Why can't MLB teams trade draft picks?


Como configurar casas decimais no JS?

Question: Não estou conseguindo as casas decimais corretas, onde está o erro?

function calcula() {

  var total = 0;
  $("span[id^=linha]:visible").each(function() {

    var val_unit = parseFloat($(".class_unit input", this).val().replace(",", "."));
    var qnt = $(".class_quant input", this).val();
    var sub_total = val_unit * qnt;

    if (!isNaN(sub_total)) $(".class_total input", this).val(sub_total.toFixed(2).replace(".", ","));

    total += parseFloat($("input[id^=total]", this).val().replace(",", "."));

    somar();

  });

  if (!isNaN(total)) $("#total input.value_total").val(total.toFixed(2).replace(".", ","));

}

//Total máximo de campos que você permitirá criar em seu site:
var totalCampos = 10;

//Não altere os valores abaixo, pois são variáveis controle;
var iLoop = 1;
var iCount = 0;
var linhaAtual;

function AddCampos() {
  var hidden1 = document.getElementById("hidden1");
  var hidden2 = document.getElementById("hidden2");

  //Executar apenas se houver possibilidade de inserção de novos campos:
  if (iCount < totalCampos) {

    //Limpar hidden1, para atualizar a lista dos campos que ainda estão vazios:
    hidden2.value = "";

    //Atualizando a lista dos campos que estão ocultos.
    //Essa lista ficará armazenada temporiariamente em hidden2;
    for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
      if (document.getElementById("linha" + iLoop).style.display == "none") {
        if (hidden2.value == "") {
          hidden2.value = "linha" + iLoop;
        } else {
          hidden2.value += ",linha" + iLoop;
        }
      }
    }
    //Quebrando a lista que foi armazenada em hidden2 em array:

    linhasOcultas = hidden2.value.split(",");

    if (linhasOcultas.length > 0) {
      //Tornar visível o primeiro elemento de linhasOcultas:
      document.getElementById(linhasOcultas[0]).style.display = "block";
      iCount++;

      //Acrescentando o índice zero a hidden1:
      if (hidden1.value == "") {
        hidden1.value = linhasOcultas[0];
      } else {
        hidden1.value += "," + linhasOcultas[0];
      }

      /*Retirar a opção acima da lista de itens ocultos: <-------- OPCIONAL!!!
      if (hidden2.value.indexOf(","+linhasOcultas[0]) != -1) {
      hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
      }else if (hidden2.indexOf(linhasOcultas[0]+",") == 0) {
      hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
      }else{
      hidden2.value = "";
      }
      */
      calcula();
    }
  }
}

function RemoverCampos(id) {
  //Criando ponteiro para hidden1:
  var hidden1 = document.getElementById("hidden1");

  //Pegar o valor do campo que será excluído:
  var campoValor = document.getElementById("valor_unitario" + id).value;
  //Se o campo não tiver nenhum valor, atribuir a string: vazio:
  if (campoValor == "") {
    campoValor = "vazio";
  }

  if (confirm("O campo que contém o valor:\n» " + campoValor + "\nserá excluído!\n\nDeseja prosseguir?")) {
    document.getElementById("linha" + id).style.display = "none";
    iCount--;

    //Removendo o valor de hidden1:
    if (hidden1.value.indexOf(",linha" + id) != -1) {
      hidden1.value = hidden1.value.replace(",linha" + id, "");
    } else if (hidden1.value.indexOf("linha" + id + ",") == 0) {
      hidden1.value = hidden1.value.replace("linha" + id + ",", "");
    } else {
      hidden1.value = "";
    }

    calcula();
  }
}

$(document).ready(function() {
  $('span[id^=linha] input').on("input", calcula);
});

//Escrevendo o código-fonte HTML e ocultando os campos criados:
for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
  document.write("
Valor Unitário " + iLoop + ":<input type='text' name='valor_unitario" + iLoop + "' id='valor_unitario" + iLoop + "' />

Quantidade " + iLoop + ": <input type='text' name='qnt" + iLoop + "' id='qnt" + iLoop + "' value='0' />

SubTotal " + iLoop + ": <input type='text' name='total" + iLoop + "' id='total" + iLoop + "' readonly='readonly' />
 <input type='button' value='Remover' onclick='RemoverCampos(\"" + iLoop + "\")'>");
}

function somar() {
  var valor1 = parseInt(document.getElementById("v_total").value);
  var valor2 = parseInt(document.getElementById("v_total2").value);
  document.getElementById("v_totalG").value = (valor1 + valor2).toFixed(2);

}

<form name="form1" action="" method="post">

Total: <input id="v_total" class="value_total" readonly></input>

  <input type="button" value="Adicionar campos" onclick="AddCampos()">

<input type="text" name="hidden1" id="hidden1">
  <input type="hidden" name="hidden2" id="hidden2">

Total2: <input id="v_total2" class="value_total2" value="12,50" readonly></input>

TotalG: <input id="v_totalG" class="value_totalG" readonly></input>

</form>

Agradeço.
Answer: Primeiro que você está chamando a função somar() dentro do laço .each, o que vai ocasionar problemas. A função deve ser chamada após o laço, quando os valores tiverem sido calculados.
Depois você precisa usar parseFloat e não parseInt para trabalhar com casas decimais, mas antes é preciso substituir a vírgula por ponto. Ex.:
var valor1 = parseFloat(document.getElementById("v_total").value.replace(",", "."));

E depois do toFixed(2), substituir de volta o ponto pela vírgula.

function calcula(){

   var total = 0;
   $("span[id^=linha]:visible").each(function(){

      var val_unit = parseFloat($(".class_unit input", this).val().replace(",", "."));
      var qnt = $(".class_quant input", this).val();
      var sub_total = val_unit * qnt;

      if(!isNaN(sub_total)) $(".class_total input", this).val(sub_total.toFixed(2).replace(".", ","));

      total += parseFloat($("input[id^=total]", this).val().replace(",", "."));

   });

   if(!isNaN(total)) $("#total input.value_total").val(total.toFixed(2).replace(".", ","));
      somar();

}

//Total máximo de campos que você permitirá criar em seu site:
var totalCampos = 10;

//Não altere os valores abaixo, pois são variáveis controle;
var iLoop = 1;
var iCount = 0;
var linhaAtual;

function AddCampos() {
   var hidden1 = document.getElementById("hidden1");
   var hidden2 = document.getElementById("hidden2");

   //Executar apenas se houver possibilidade de inserção de novos campos:
   if (iCount < totalCampos) {

      //Limpar hidden1, para atualizar a lista dos campos que ainda estão vazios:
      hidden2.value = "";

      //Atualizando a lista dos campos que estão ocultos.
      //Essa lista ficará armazenada temporiariamente em hidden2;
      for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
         if (document.getElementById("linha"+iLoop).style.display == "none") {
            if (hidden2.value == "") {
               hidden2.value = "linha"+iLoop;
            }else{
               hidden2.value += ",linha"+iLoop;
            }
         }
      }
      //Quebrando a lista que foi armazenada em hidden2 em array:

      linhasOcultas = hidden2.value.split(",");

      if (linhasOcultas.length > 0) {
         //Tornar visível o primeiro elemento de linhasOcultas:
         document.getElementById(linhasOcultas[0]).style.display = "block"; iCount++;

         //Acrescentando o índice zero a hidden1:
         if (hidden1.value == "") {
            hidden1.value = linhasOcultas[0];
         }else{
            hidden1.value += ","+linhasOcultas[0];
         }

         /*Retirar a opção acima da lista de itens ocultos: <-------- OPCIONAL!!!
         if (hidden2.value.indexOf(","+linhasOcultas[0]) != -1) {
         hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
         }else if (hidden2.indexOf(linhasOcultas[0]+",") == 0) {
         hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
         }else{
         hidden2.value = "";
         }
         */
         calcula();
      }
   }
}

function RemoverCampos(id) {
   //Criando ponteiro para hidden1:
   var hidden1 = document.getElementById("hidden1");

   //Pegar o valor do campo que será excluído:
   var campoValor = document.getElementById("valor_unitario"+id).value;
   //Se o campo não tiver nenhum valor, atribuir a string: vazio:
   if (campoValor == "") {
      campoValor = "vazio";
   }

   if(confirm("O campo que contém o valor:\n» "+campoValor+"\nserá excluído!\n\nDeseja prosseguir?")){
      document.getElementById("linha"+id).style.display = "none"; iCount--;

      //Removendo o valor de hidden1:
      if (hidden1.value.indexOf(",linha"+id) != -1) {
         hidden1.value = hidden1.value.replace(",linha"+id,"");
      }else if (hidden1.value.indexOf("linha"+id+",") == 0) {
         hidden1.value = hidden1.value.replace("linha"+id+",","");
      }else{
         hidden1.value = "";
      }

      calcula();
   }
}

$(document).ready(function(){
   $('span[id^=linha] input').on("input", calcula);
});

//Escrevendo o código-fonte HTML e ocultando os campos criados:
for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
   document.write("
Valor Unitário "+iLoop+":<input type='text' name='valor_unitario"+iLoop+"' id='valor_unitario"+iLoop+"' />

Quantidade "+iLoop+": <input type='text' name='qnt"+iLoop+"' id='qnt"+iLoop+"' value='0' />

SubTotal "+iLoop+": <input type='text' name='total"+iLoop+"' id='total"+iLoop+"' readonly='readonly' />
 <input type='button' value='Remover' onclick='RemoverCampos(\""+iLoop+"\")'>");
}

function somar(){
    var valor1 = parseFloat(document.getElementById("v_total").value.replace(",", "."));
    var valor2 = parseFloat(document.getElementById("v_total2").value.replace(",", "."));
    var totalG = valor1 + valor2;
    if(!isNaN(totalG)) document.getElementById("v_totalG").value = totalG.toFixed(2).replace(".", ",");

}

<form name="form1" action="" method="post">

Total: <input id="v_total" class="value_total" readonly></input>

   <input type="button" value="Adicionar campos" onclick="AddCampos()">

<input type="text" name="hidden1" id="hidden1">
   <input type="hidden" name="hidden2" id="hidden2">

Total2: <input id="v_total2" class="value_total2" value="12,50" readonly></input>

TotalG: <input id="v_totalG" class="value_totalG" readonly></input>

</form>

Como configurar casas decimais no JS?


Android SDK friend request returns "Sorry, something went wrong"

Question: I'm using the Facebook SDK for Android and when I send a friend request using the below code, I get the following error: "Sorry, something went wrong. We're working on getting this fixed as soon as we can."
Is this a problem on my side or on Facebook's? This code was working perfectly fine a few days ago. It opens up a popup with the friend request as usual. But when I click accept, it shows me the error page. Please help me.
    private void sendRequestDialog(String friendID)
{
    Bundle params = new Bundle();

    params.putString("id", friendID);

    WebDialog friendDialog = (
            new WebDialog.Builder(context, Session.getActiveSession(), "friends", params))
    .setOnCompleteListener(new OnCompleteListener()
    {
        @Override
        public void onComplete(Bundle values, FacebookException error)
        {
            if(error != null)
            {
                if(error instanceof FacebookOperationCanceledException)
                {
                    Toast.makeText(context, "Friend Request Cancelled", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    //Toast.makeText(getApplication().getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                final String requestId = values.getString("request");
                if (requestId != null)
                {
                    Toast.makeText(context, "Friend Request Sent", Toast.LENGTH_SHORT).show();

                    removeFriend();
                }
                else
                {
                    Toast.makeText(context, "Friend Request Cancelled", Toast.LENGTH_SHORT).show();
                }
            }
        }

    })
    .build();
    friendDialog.show();
}

Comment: Please help me. I don't know how to debug this.
Comment: what are the params you're setting?
Comment: Added the parameters code to the answer. I'm passing a valid friend id. Facebook returns a friend request, but doesn't process it when the user clicks Accept. It redirects to the "Sorry" error page.
Comment: Have you found a solution to your problem ?
Answer: I was struggling with the same issue.
The workaround for me was to double-check the permissions. (first_name, last_name with name, etc arent working correctly)
You should start by removing all and only take "email" and then add the remaining permissions accordingly which will make it easier to understand.
LoginManager.getInstance().logInWithReadPermissions(
        this,
        listOf("email") //, "name", "first_name", "public_profile"
    )

Answer: Try change
params.putString("id", friendID);

to
params.putString("to", friendID);

Comment: That doesn't work. It says the parameter "id" is required. This is in accordance with the friends dialog specs: http://developers.facebook.com/docs/reference/dialogs/friends/
Comment: I still haven't found a solution. I reported this to the FB Bugs page. Others have the same problem on different platforms. How can you force the WebDialog to use facebook.com instead of m.facebook.com?
Comment: Did anyone find proper working solution ?  Is the problem at facebook's end ?


python count de diferentes palavras com apenas um contador?

Question: Tenho este código:
palavras = dataClean.split()
count = 1

for palavra, frequencia in palavras:
    aleatorio = random.uniform(0.0, 1.0)
    if aleatorio < 0.5:
        count += 1

    contProb[palavra] = count
    count = 0

print(contProb)

Por exemplo, para este txt:
olá mundo olá mundo adeus

Portanto gostaria que funcionasse desse jeito: no for
deve ser capaz de ler cada letra do texto dado e a cada letra incrementar consoante o resultado do if.
Passo a dar um exemplo:
O contador inicia sempre com o valor 1 para todas as letras. Lemos a palavra ola na variável aleatorio o número random criado é o 0.4, ou seja, deve incrementar 1 ao count. Depois disso devemos ler a segunda palavra mundo e se, por exemplo, aleatorio for 0.3 deve incrementar 1 ao count mas o count já é 2, ou seja, ao incrementar vai incrementar o 3 e guardar. E não é isso que deve fazer.
Ou seja, preciso de vários contadores? Como faço isto
Comment: Amigo, por favor, [edite](https://pt.stackoverflow.com/posts/351394/edit) sua pergunta e acrescente um exemplo como ficaria o resultado para este txt que você passou `olá mundo olá mundo adeus`; O que você quer que fique no final? Algo tipo `{'olá': 3, 'mundo': 2, 'adeus': 1}` ?
Answer: Usando essa frase:
frase = "olá mundo olá mundo adeus"
palavras = frase.split()

Agora podemos usar o defaultdict para fazer um dicionário contador que armazena um número inteiro para cada palavra - já configuramos para começar com o valor 1 para todas as palavras:
import collections
contador = collections.defaultdict(lambda: 1)

Para cada palavra, caso o sorteio dê positivo, incremente o contador daquela palavra específica diretamente:
for palavra in palavras:
    if random.random() < 0.5:
        contador[palavra] += 1

Comment: Pois é @nosklo. Tem toda a razão, confundi tudo. Vou editar agora mesmo a questão. Agradeço sua ajuda.
Comment: @Walt057 editei a resposta


An element a belongs to closure A iff there exist a sequence an belongs to A s.t an -> a

Question: I am reading a proof of a theorem stating that:
Point a belongs to closure A iff there exist a sequence an belongs to A s.t an -> a

Why the last inequality prove that a belongs to closure A?
Answer: The important thing to realize is that
$$\overline{A} = A \cup A' = A \cup \{\text{limit points of $A$}\}$$
and the statement 'for every $\epsilon>0$, $B_\epsilon(a) \cap A \neq \emptyset$' is exactly the statement that $a\in A \cup A'$.
This is because either $a\in A$, in which case we're done, or $a\notin A$, so the non-emptiness of $B_\epsilon(a) \cap A$ implies that there is some point in this intersection which isn't $a$, i.e. $(B_\epsilon(a)\setminus\{a\}) \cap A \neq \emptyset$.  Since $\epsilon$ is arbitrary, this means that $a$ is a limit point of $A$.


How can I write the matrix of the following Linear transformation

Question: Firstly I must apologise that I have tried Latex commands but they do not come out. So I hope my document is readable.
I have this definition of a linear transformation
T: P_n(R) -> P_n(R)
T(f(x))=f(x+1)

I have proved this to be a linear transformation (correct?) as follows:
Let
f(x)=A0+A1x+A2x^2+...+Anx^n, g(x)=B0+B1x+B2x^2+...+Bnx^n in P_{n}(R),
C,Ai,Bi in K, i=0,1,2,...,n
T(Cf(x)+g(x))=T(CA0+CA1x+CA2x^2+...+CAnx^n + B0+B1x+B2x^2+...+Bnx^n))
=CT(f(x))+T(g(x))
=Cf(x+1)+g(x+1)

So T is linear
Now I want to write a matrix representing this transformation relative to the basis {1, x-1, (x-1)^2, ... (x-1)^n}
T[1]=f(2) = ?(1) + ?(x-1) + ... + ?(x-1)^n
T[x-1]= f(x) =  ?(1) + ?(x-1) + ... + ?(x-1)^n
......

My problem is: What do I take as coefficients of the various basis elements, because
i) the evaluation of f(x+1) does not yield any coefficients
ii) replacing (x-1) by (x-1)+1 I lose the basis elements to
{1,x,x^n,...,x^n

Assistance will be appreciated.
Answer: In your first proof, the step from line 3 to line 4 is incorrect. You need to write what $T(CA_0+CA_1x+CA_2x^2+...CA_nx^n+B_0+B_1x+B_2x^2+...+B_nx^n)$ is using the definition. What you did is using the fact that $T$ is linear to show it is linear.
It should be
$$T(CA_0+CA_1x+CA_2x^2+...CA_nx^n+B_0+B_1x+B_2x^2+...+B_nx^n)=CA_0+CA_1(x+1)+CA_2(x+1)^2+...CA_n(x+1)^n+B_0+B_1(x+1)+B_2(x+1)^2+...+B_n(x+1)^n$$
In the next question, $T(1)=1$ since if $f(x)=1$ then $f(x+1)$ is also $1$. You can use this idea to do the others.
To find the coefficients, you need to write $x^m$ in terms of $\{1, x-1, (x-1)^2, ..., (x-1)^n\}$. Make a change of variable $y=x-1$, so $x^m=(y+1)^m$. You can then easily find the coefficients of the $y$ terms.
Comment: Thanks @KittyL for the correction and for enlightening me. My concern was that I seem to be losing the original basis, which is
Comment: My concern was that I seem to be losing the original basis, {1, (x-1), (x-1)^2, ... }
Comment: I see. Sorry I didn't notice that. I will edit my answer.


Determining null sets with Tonelli's theorem

Question: How can I show that the diagonal $D=\{(x,y)\in\mathbb R^2\vert  x=y\}$ is a Lebesgue-nullset in $\mathbb R^2$ by utilizing the theorem of Tonelli?
My solution so far, but it doesn't seem quite right:
$\int_D 1d\lambda = \int_{-\infty}^\infty\int_{y}^{y}1dxdy=\int_{-\infty}^\infty [x]^y_ydy=\int_{-\infty}^\infty0 dy=0$
Can I do it this way?
Answer: @Sigma, Your approach is essentially correct. You can prove the diagonal $D=\{(x,y)\in\mathbb R^2\vert  x=y\}$ is a nullset directly from Tonelli's theorem. Here are the details.
Since $D$ is closed in $\mathbb R^2$, $D$ is measurable and so $1_D$ is a non-negative measurable function. So we can apply Tonelli's theorem.
\begin{align*} \lambda(D)&=\int_{\mathbb R^2} 1_D d\lambda = \int_{-\infty}^{+\infty}\int_{-\infty}^{+\infty}1_D(x,y) dx dy= \\
&=\int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty}1_D(x,y) dx\right) dy = \\
&=\int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty}1_{\{y\}} dx\right) dy = \\
&=\int_{-\infty}^{+\infty} 0\; dy =0
\end{align*}
Answer: A possible approach: first rotate $D$ to the horizontal axis, and recall that the Lebesgue measure is invariant under rotations. Then observe that
$$
(-\infty,+\infty) \times \{0\} = \bigcup_{n \in \mathbb{N}} \left( [-n,n] \times \{0\} \right).
$$
If you prove that $\mathcal{L}^1 \left( [-n,n] \times \{0\} \right)=0$ for every $n$, then you can use the subadditivity of the measure to conclude.
We must show that $\mathcal{L}^1 \left( [-n,n] \times \{0\} \right)=0$ for every $n$. Pick $\varepsilon >0$ and consider the set
$$
\Omega_\varepsilon = [-n,n] \times (-\varepsilon,\varepsilon).
$$
Compute $\int_{\Omega_\varepsilon} \mathrm{d}x \, \mathrm{d}y$ and prove that the result is of order $\varepsilon$. Since $\varepsilon>0$ is arbitrary...
Edit: the first step is only for convenience. One can also consider the set $\Omega_\varepsilon$ lying between the lines $y=x+\varepsilon$ and $y=x-\varepsilon$.
Comment: Thank you. But to be honest, we haven't shown that the Lebesgue measure is invariant under rotations yet (we know it is true, but we are not allowed to utilize it).
Comment: This is not essential, you can "cover" $D$ by a slab with sides parallel to the line $y=x$.


How to show that $f^{-1}$ respects set theoretic operations

Question: I am trying to prove the inverse image w.r.t a continuous function f:R->R of every closed set is closed.  I am trying to use the fact that f is continuous means for every open subset O$\subset$R, its inverse image $f^{-1}$(O) is open.
Here is my proof:
Let $C$ be closed, $C \subset R$.  Then $R$ \ $C$ is open and so is $f^{-1}(R$ \ $C$).  I need to show that this = $f^{-1}(C)$, but I'm stuck
Comment: So, you're asking why the inverse image of the complement is the complement of the inverse image?
Answer: The following statements are equivalent:

$x\in f^{-1}(C^{\complement})$
$f(x)\in C^{\complement}$
$f(x)\notin C$
$x\notin f^{-1}(C)$
$x\in f^{-1}(C)^{\complement}$

So we have: $$x\in f^{-1}(C^{\complement})\iff x\in f^{-1}(C)^{\complement}$$ for arbitrary $x$.
This tells us that: $$f^{-1}(C^{\complement})=f^{-1}(C)^{\complement}$$
Answer: Let $x\in f^{-1}(R\setminus C)$, then $f(x)\in R\setminus C$. Therefore, $f(x)\not\in C$, so $x\not\in f^{-1}(C)$. This puts $x\in R\setminus f^{-1}(C)$.
This argument, by element-chasing, shows that the inverse image of the complement is contained in the complement of the inverse-image. By element-chasing, you can show the converse as well.


Maximum rate of increase- Directional derivatives

Question: If I have been asked:

Find the directional derivative of $$f(x, y, z) = \frac{x}{y}−\frac{y}{z}$$ at the point $P(0, −1, 2)$ in the direction from $P$
  to $Q(3, 1, −4)$ and find the maximum
  rate of increase.

For the second part 'max rate of...' is that just calculating the maximum directional derivative?
Thanks
Comment: the notation $P(a,b,c)$ is a bit strange, it is more clear write $P:=(a,b,c)$ to denote a point $P$ defined by coordinates $(a,b,c)$
Answer: Recall that the maximum rate of increase is given by the norm of the gradient vector $|\nabla f(P)|$ indeed the directional derivative in direction $\vec u$ is given by
$$\nabla f(P)\cdot \vec u=|\nabla f(P)|\cos \theta$$