Probability of winning a tournament

Question: Edited Question:
As I promised I've edited this question.  The previous version was written with the intention of simplifying the real question, but it ended in losing the real significance. Now I'm posting the "whole story". ;)
My purpose is to calculate $n$ players' equity in a poker tournament (their probability of ending the tournament) in every $j$ place (1st, 2nd, and so on).

I've previously solved this problem in 2 different ways you can find
  here:
For the Maths:
https://math.stackexchange.com/questions/92942/applying-a-math-formula-in-a-more-elegant-way-maybe-a-recursive-call-would-do-t
And for the code:
https://stackoverflow.com/questions/8605183/how-to-translate-this-math-formula-in-php

So, when I know every players' number of chips, I can easily apply those formulas and get their equity.

There are 2 problems involved that hopefully can be solved with a statistical method. (I'm not a mathematician so I'm not sure it will be feasible).

First problem, even if I know everyone's stack, when the number of players is high, the code is too slow to be implemented;
Second problem, this code should work by knowing only a limited number of stacks, belonging to the players of the analyzed table.

Optimistically these 2 problems can both be solved with some kind of approximations.
In particular the formulas mentioned above should be applicable to scenarios with 27,45,90 players who are distributed in tables of 9.
For example in the case of 27 players there would be 3 tables: when there are 18 players left they will be redistributed in 2 tables and when there are only 9 left the final table will be opened.
It's not important to take into account the players' skill since it's a high variance game where its influence is reduced to the minimum, and mostly there are coin flips that eliminate players.
So I'm in a situation where I know:

My number of chips.
The number of chips of the other 8 players of my table.
The total number of chips.
The average number of chips.
The maximum and minimum number of chips.

As I suggested in the previous question, this seems to me (from my humbles math skills) to be a gaussian curve, with a maximum, a minimum and an average number of chips.
I think that's all. If you need additional details please leave a comment, and I will add them as soon as possible.
I wanna thank you for your interest, and for all the previous comments and answers. I hope your statistics can help me solve this. :D
Best Regards,
Giorgio.

Old Question:
I'd like to calculate or approximate the probability that I have to win a tournament where every player has a determined amount of chips.
Let's consider a scenario where there are 9 players and I know everyone's number of chips, to calculate my probability of winning I would do: my chips/(tot chips - my chips).
Now imagine those 9 players are put on 3 different tables of 3 players each, and I know the chips only of the 2 players of my table and mine obviously. I also know the total number of chips, the max and min amount chips the players have and the average stack.
Is it possible to make an approximation of my probability of winning?
I have only basic math skills but I think players' stack could be approximated to a gaussian curve,  then use some "statistical trick" to calculate my probability.
Thanks in advance for any hint!
Best regards,
Giorgio
Comment: @PeterEllis: I might not discount some utility of the normal distribution. Consider a two-person game in which Player 1 starts with $a$ chips and Player 2 with $b$ chips. Suppose they are equally skilled so that at the end of each turn, the result is that one player gives the other one chip with equal probability. Then Player 1 wins with probability $b/(a+b)$. The fortune of each Player follows a random walk until an absorbing state is hit, and the walk up to this time is approximated by a Brownian motion. If we introduce a third player, we get a diffusion inside the unit simplex.
Comment: I think that there is a mistake in your formula for the probability of winning. Shouldn't it be $\frac{\textrm{my chips}}{\textrm{total chips}}$?
Comment: if skill is involved, this becomes a more difficult problem to solve. :)
Comment: @TomekTarczynski - yes, that must be the case, otherwise the sum of all players' probabilities of winning do not add up to one.
Comment: I've edited the whole question. You can find it above. I hope you can help me, and tell if this could be feasible by applying some statistical trick ;)
Best Regards
Comment: @Giorgio - if you win at your first table, can we assume that means you have all the chips from your first table, and then go on to play the winners of other tables?  Alternatively, is the winner of the tournament the winner of an individual table who has more chips at the end than the winners of the other two tables?  What is the significance of the tables, and what does it mean to "win" a tournament of 3 tables?
Comment: I've added probability and games tags - I doubt the normal distribution will be that helpful for solving this.
Comment: @PeterEllis: Sorry for the awful typo. The stated probability in the previous comment should have read $a/(a+b)$.
Comment: AS you suggested the probability is my chips/total, my fault. If you win a table you'll have all the chips you've earned when you're moved to the final table. The meaning'
Comment: The ' meaning' of tables is that you know exactly only a part of players' chips. However this is just an example the real situation can be more complex since tables can be of 9 players instead of 3 and the final table is created when 9 players are left, so there could be more than one player that advance to the next table. Oh yes, skill is involved but it has not a big influence since the variance is high.
Comment: An example to explain what I posted above is a tournament where there are 27 player on 3 tables of 9. When there are only 9 player left they are moved to the final table with their current amount of chips.
Comment: Oh sorry! I've noticed that what I wrote make no sense as it's written! This it's because the real problem to solve include to calculate the probability of each player n of ending in every place j.
Comment: So for the first place I just divide my stack from the total amount of chips, BUT for the other place I have to consider that every player can end first with a probability p, so I'd subtract his stack from the total amount and recalculate my probability of ending in second place and so on. The problem with multiple tables is that I don't know exactly every player chips.
Comment: I'll update my comment as son as I come home.:-)
Answer: The model described in the links is not the diffusion model. The model you are trying to implement is called the Independent Chip Model or ICM. They give different estimates for your expected share of second and lower place prizes. Here are two ways to describe the ICM:
(1) Determine the winner so that each player's chance to win is proportional to his chip count. Then remove that player's chips, and determine the second place player so that each non-winner's chance to place second is proportional to his chip count. Repeat.
(2) Randomly remove the chips one at a time so that each remaining chip has the same chance to be removed next. When your last chip is removed, you are eliminated.
It's not obvious that these are the same model. In fact, it's clear that the first description only depends on the proportion of chips, and doesn't require that the number of chips is an integer. It's not obvious that the second method gives the same chance to place second if the stacks are $(100,200,300)$ as for $(1,2,3)$. (In other models, these situations are different.) However, you can see that these are equivalent (when both are defined) by a third description:
(3) Each player marks all of his chips. Then they are shuffled and ordered. Players are ranked by their highest chips.
Description (1) corresponds to looking at the top of the ordering. Description (2) corresponds to looking at the bottom.
You can find a lot of information about the Independent Chip Model on the web because it is used by serious tournament poker players, particularly those who play Sit-N-Go (SNG)/Single Table Tournaments (STTs). See, for example, this Nash Equilibrium Calculator for push/fold decisions in STTs which uses the ICM. There are other models like the diffusion model, but the Independent Chip Model seems good enough and is easier to compute. You can find a section on the ICM in my book, The Math of Hold'em, and I have also made videos on it for poker instructional sites.
One of the other answers asks why bother since it's all luck. Understanding equities assuming that you have no skill advantage (but the stacks are not equal) is how many serious poker players GET an advantage. Getting all-in with a $60\%$ chance to win and negligible dead money is sometimes great, and sometimes terrible. The equities say which. Also, if you run a poker server, you need to be prepared to divide the prize money fairly in case the server crashes during the tournament. A poker server asked me for help with this.

As you have noted, a naive implementation which computes your chance to place $p$ out of $n$ players sums over many terms, $(n-1) \times (n-2) \times ... \times (n-p) = \frac{(n-1)!}{(n-p-1)!}$. This may be too large in practice. One improvement I use in my program ICM Explorer is to memoize the probabilities with each subset of up to $p-1$ opponents removed. If you are computing each probability, this takes $n 2^{n-1}$ steps instead of $(n-1)!$, which makes the difference between whether you can calculate the case $n=10$ crisply, and whether you can calculate the case $n=20$ in under a second versus not at all.
If you have repeated stack sizes among your opponents, you can remember how many of them have been eliminated instead of which subset. This is particularly useful when you are analyzing multitable tournaments where you only see the stacks at your table, or only a few front-runners, and you assume everyone else you don't see has the same stack size. This makes calculating your equity feasible for large tournaments. This method has a complexity roughly equal to $k \prod_{i=1}^k (m_i+1)$ where there are $k$ different stack sizes among your opponents whose multiplicities are $m_1, ... ,m_k$.
There is one implementation I know about which lets the user calculate ICM equities for multitable tournaments. This uses a simulation. The author assured me that it converges rapidly to within a $0.1\%$ chance for each place. In case you need more accuracy, one simple variance reduction method works very well: Estimate your luck from being chosen or not to finish next at each step by the exact calculations with fewer distinct stack sizes. Subtract this estimate of luck (a vector) from the vector of probabilities obtained in the simulation.
For example, suppose your stack is $1000$, and you have $2$ opponents with stacks of $500$ and one with $1500$.
If one of the players with $500$ wins, your remaining opponents will average $1000$, so you estimate your chances using the ICM exactly assuming $2$ opponents with $1000$ chips. Since all stacks would be equal, by symmetry all $3$ players would have an equal chance to finish second, third, and fourth, so your place distribution would be $(0,1/3,1/3,1/3)$.
If the big stack wins, your remaining opponents average $500$, and the ICM says your place distribution is $(0,1/2,1/3,1/6)$.
If you win, obviously your place distribution is $(1,0,0,0)$.
The weighted average is
$$\frac{1000}{3500}(0,1/3,1/3,1/3) + \frac{1500}{3500}(0,1/2,1/3,1/6) + \frac{1000}{3500}(1,0,0,0) = (2/7,13/42,5/21,1/6).$$
So, if in your trial, you win, then you estimate your luck for that step by $(1,0,0,0) - (2/7,13/42,5/21,1/6)$, and subtract this from the result of the trial. If the big stack wins, the trial isn't over, but you estimate your luck for this step by $(0,1/2,1/3,1/6)-(2/7,13/42,5/21,1/6)$, and subtract this and future luck estimates from the outcome of the trial.
The luck estimate averages to $(0,0,0,0)$ and greatly reduces the number of trials needed to achieve a given level of accuracy, particularly for the places closer to first, which are most important for estimating your fair share of the prize money.

The distribution of the other stacks matters, but except in extreme situations, you only see a large effect if you are close to the "money," which means that there are at most a few more players than there are prizes. Let's assume the prize structure is the one PokerStars uses for $180$ player tournaments: $0.3, 0.2, 0.119, 0.08, 0.065, 0.05, 0.035, 0.026, 0.017$ for places $1-9$, and a flat $0.012$ for places $10-18$.
Let's consider $2$ pairs of situations. First, you are one of $180$ equal stacks. Your equity is $1/180$ of the prize pool, or $0.5556\%$. Suppose you have doubled up, eliminating one player, and you have $178$ opponents with a stack half as large as yours. According to the ICM, your chance to finish in first place is $1.1111\%$, second $1.1049\%$, ... $18$th $1.0056\%$ for an equity of $1.0917\%$. The quotient $0.5556/1.0917 = 50.887\%$ is how much equity you need to want to get all-in with no dead money with $180$ equal stacks.
Suppose there are $60$ players with a stack equal to yours (including you), $60$ with half of your stack, and $60$ with half again as much as your stack. According to the ICM, your equity is $0.5572\%$ of the prize pool. Next, suppose you double up against an equal stack. Your equity increases to $1.0948\%$ of the prize pool. The equity you need to risk elimination for this is $0.5572/1.0948 = 50.894\%$.
Your expected share of the prize money didn't depend much on the stacks of the other players, and the equity you need to risk your whole stack depended even less on the stacks of the other players. These become sensitive to the stacks of your opponents once you get down to about $25-30$ players left with $18$ prizes.
Comment: and will play few hands, (or will correctly play few hands due to a dearth of playable situations) so for a long time the mode will be the initial stack minus the total of the antes. By the way, many poker sites let you see the stack distributions of tournaments in progress, so it is relatively easy to get data. However, I don't think equities are sensitive to the distribution until you have only a few more players than prizes.
Comment: Thanks for your answer! Seems like you know what you're speaking about ;) But I already know what ICM is and how to implement it into a 6-9 players scenario. I'd like to apply it when we don't have complete infos (we know only our table's/chipleader's/lowest stacks).

At the moment I'd use a t-Student Curve to approximate people's stacks but I don't have the needed math/stat skills to build a solid model for this purpouse. Hope you could help.
Comment: The probabilities of finishing in lower places are very sensitive to the sizes of other stacks, but the probabilities of finishing in the top few places (which pay prize money) are not as sensitive. You can test this using the approximation I suggested, of assuming there are few distinct stack sizes among the players you don't see. If you do feel like modelling the other stacks, then the distribution depends on the type of tournament including the schedule of blinds and antes and the playing style and skill level of your opponents. A clump of players will be overly conservative...
Answer: Do players keep playing until they run out of chips?
Suppose we assume players A B C each have some number of chips and keep playing until they have 0. Suppose we further assume odds of winning a hand are either 1/3, 1/3, 1/3 or some other value (per Michelle's comment about skill). Suppose we further assume each pot consists of either win (+2) or loss (-1) -- an unrealistic but simplifying assumption.   Then doesn't this become a question of the relative probability of hitting 0 first? There's literature I'm not really familiar with that deals with this (Martingale wagers, but without the increasing bets).  With multiple tables, equal chip pools per table and 1 winner per table 2nd round would be p=1/3.
More: I did some quick simulations along these lines. Each player is equally skilled. A always starts with 50% of the chips, B 1/3 of the chips and C 1/6 of the chips. I just varied the total number of chips.  I did 3 runs at 3 levels, each consisting of 2000 simulations until only 1 player was left (18,000 simulations total). This suggests that it might indeed be as simple as p(I win) = my proportion of chips.

Comment: From http://en.wikipedia.org/wiki/Random_walk#Gaussian_random_walk we have this formula, which seems analogous to the situation I described, but for two players. "If a and b are positive integers, then the expected number of steps until a one-dimensional simple random walk starting at 0 first hits b or −a is ab. The probability that this walk will hit b before −a is a / (a + b), which can be derived from the fact that simple random walk is a martingale."
Comment: I've edited the whole question. You can find it above. I hope you can help me, and tell if this could be feasible by applying some statistical trick ;) Best Regards
Answer: I suspect you are making this more complex than it needs to be.  If there are 27 million players (or even 27 thousand - I think you have a typo) and the game is pure chance and we can reasonably assume that no player has a significant number of chips compared to the total number of chips...
Then your chance of winning is: $\frac{my chips} {total chips}$
Your change of coming second, given you didn't win, is: $\frac{mychips}{totalchips-winnerchips}$ which is effectively the same as your chance of winning.  And so on.
Given the vast numbers involved and if as you say it is all chance I doubt it is worthwhile doing any more sophisticated calculation.  The secret of "statistical tricks" is to know when to use an approximation :-)

Probability of winning a tournament


After update to Drush 7 still version 6

Question: Running on Debian I have updated Drush to version 7:
composer global require drush/drush:7.*
composer global update
But the command 'drush --version' still tells me:
Drush Version : 6.2.0
I have looked everywhere but didn't find a solution.
Thanx for any help.
Comment: you can add alias of your new drush, do this `vim ~/.bashrc`

add this line

`alias drush='path/to/your/new/drush/'`
Answer: The problem is that the old version of Drush is still in your $PATH, and comes before the new version.
The Drush installation instructions says:

Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users) or into your ~/.bashrc (Linux users).

What it does not mention is that changes to your .bashrc file are not immediately reflected in your running system.  You need do one of:

Restart.
Close and re-open all of your terminal windows.
Type source ~/.bashrc in all of your open terminal windows.

(Listed in order from easiest and most disruptive, to more work but less disruptive.)  Substitute .bash_profile in place of .bashrc if you made your modification there.

After update to Drush 7 still version 6


Grid item height not matching responsive square child

Question: I'm creating a web application with React and Material-ui. I need a responsive square div for a map component, however, using a trick from iamsteve.me breaks the grid layout as the parent Grid div does not expand.
I have tried moving the class which is square to the grid element, but this doesn't help.
map: {
    height: '100%', width: '100%', position: 'absolute'
},
mapContainer: {
    height: '0',
    paddingBottom: '100%',
    position: 'relative'
},

<Grid item>

    <Paper className={classes.map}>
    // map
    </Paper>

</Grid>

The height of the Grid item does not match the size of the square. This is an issue for items that follow.
Answer: For responsive square, you should use Grid provided by Material-UI.
A simple change in your code to use Grid could be this
<Grid container justify={"center"}>
   <Grid item xs={6}>
      <Paper className={classes.paper}>Your Map Here</Paper>
    </Grid>
</Grid>

To constrain the width of the containing element, you can do
root: {
    flexGrow: 1,
    height: "50vh",
    width: "50vh"
  },

I have updated a Codesandbox demonstrating it at https://codesandbox.io/s/material-demo-pjssu
I hope this helps. Thanks
Comment: Unfortunately this doesn't force the contents of the Grid item to be a square, which is what I require here.
Comment: I updated the codesandbox and the link. Once you fit in your map, you should see it with in the constraints, give it a try. If not, fork this sandbox, add the map, and share it
Comment: I can't add it to the sandbox since the map element is Google-Map-React and this introduces cross origin issues. However, I have simulated the map with a div. The size of the div is not square (you can't see it). https://codesandbox.io/s/material-demo-59t49?fontsize=14
Comment: I tried again, but the CORS issue is hitting me up at https://codesandbox.io/s/material-demo-fgnse. Do you have a `apiKey` that you could share privately and delete once the problem is resolved?
Comment: You don't need to use a Google Map since it acts the same as a div with height 100% and width 100%. Thanks for helping btw.


What is protobuf-net SerializeWithLengthPrefix tag argument for?

Question: This method accepts as the last argument an integer, but I'm not sure I understand what I would use it for exactly.
Serializer.SerializeWithLengthPrefix(stream, object, PrefixStyle.Base128, [tag]);

The same holds true for the corresponding Deserialize method.
Is it just a way to tag messages to add some sort of "querying" capabilities on deserialization to filter out unwanted messages or does it have any other usages?
Answer: Basically, it is an additional marker that can be (although does not have to be) used to note the "type" of the message being added, since the presumption (when using the *WithLengthPrefix approach) is that there are multiple messages in the same stream.
By being included, it also means that the entire composite stream is itself an entirely valid protobuf message.
Ways of using this:

you can serialize a List<Foo>, and then repeatedly deserialize (with-length-prefix) individual Foo items, or vice-versa
with a heterogeneous set of objects, you can use the Serializer.NonGeneric API to allow type-resolution based on the tag, i.e. the code equivalent of "if 1 then Invoice; if 2 then Order, if 3 then skip it, if 4 then Customer", etc - this is especially useful if using a NetworkStream as a message-sending device. This approach (using a different tag per type) allows you to read objects off the stream, and deserialize them correctly, without knowing in advance the type of the next message

It is possible to omit this if you want - just pass zero (IIRC). This will save (typically) a byte per message appended, but: it means that the stream is no longer a valid protobuf itself. It can still be read, of course, by passing zero when reading.
Comment: @Simone it makes the *composite* message a valid protobuf, because `repeated MessageType` (in .proto) is encoded as a sequence of "[tag][length][payload]...[tag][length][payload]". Hence with the tag it is a valid protobuf, and without: it isn't. Re type resolution; normally yes, since it is intentionally platform independent; however, protobuf-net does also include some *additional* support for including some limited type information on the wire.
Comment: Why does including the tag make it a valid protobuf message?
Can't you deserialize individual items in a list without the tag?
Comment: Also, type resolution using tag has to be carried out by the application code, right?


Link between linear regression and correlation

Question: I happen to do a lot of linear regression,  the typical use case is predicting $Y$ with a few predictors say $X = [X_1;X_2;X_3]$.
So we we find $\hat{\beta}$ such that $$\hat{\beta} = \underset{\beta}{argmin} ||Y-X.\beta||^2$$ But actually what I am more interested in in finding the linear estimation of $Y$ such that $$corr(Y,\hat{Y}) = corr(Y,X.\hat{\beta})$$ is maximal.
I am bothered by the fact that for a given $\beta_0$, $corr(Y,X.a.\beta_0)$ is the same for all $a$, questions are then
Is the optimal linear estimator of $\beta$ in the least square sense also optimal in my correlation term, and if yes should I be bothered that the optimal $\beta$ is not unique ?
Answer: Think about $R^2$ of linear regression:
$R^2=1-\frac{\|Y-X\hat\beta_{OLS}\|^2}{\|Y-\bar Y\|^2}=[Corr(Y,X\hat\beta_{OLS})]^2$
Since denominator does not depend on $\hat\beta$ and LS minimizes the numerator the "result follows".

You correctly mentioned that the correlation coefficient is invariant under linear transformations (which preserve sign). It means that you cannot use correlation to recover the underlying parameters.
Consider the next univariate model:
$Y_i=X_i\beta+u_i$
For any $b\not=0, |Corr(Y_i. X_ib)|=|Corr(Y_i, X_i)|$
So, it meaningless to maximize sample covariance w.r.t to $b$.
On the other hand, $R^2(b)\le Corr(Y_i, X_ib)^2$ with equality for $b=b_{OLS}$.  In this sense LS yields the optimal estimator.
Comment: good that's what I thought, did not know the correl formula. Any thought about the second question (should I be bothered that an infinite number of $\beta$ maximize the correl) ?


Can I copy output from R to Word or Excel?

Question: I would like to put an output from R to my appendix in my thesis; however when I pasted it to Word, the columns were moved.
Do you have any idea how to adjust it to be exactly the same as in R? so that it is easier to read
Comment: This question appears to be off-topic because it is about correctly formatting monospaced output in Word.
Comment: This question appears to be off-topic because it is about the use of R. Please review advice about software-related questions in the help center. Nor is it really suitable for posting on Stack Overflow. You could try an R forum.
Comment: Besides the good solution offered, you can simply paste to word and then format it as any monospace font (e.g. courier new, consolas, and many others). The output won't look as pretty, but it does look rather like the session you took it from and it's a lot faster -- and in many cases quite adequate
Comment: Kniter is a neat little R package for generating html-based reports if you are interested in doing more that exporting a dataframe.
Answer: This question would better fit to Stackoverflow. However, you could export the dataframe (df) with write.csv(df, "clipboard", row.names = FALSE) to the clipboard. Paste it in Excel and copy this to Word. You now should have a table in Word.
Comment: There is also the R [xlsx package](http://cran.r-project.org/web/packages/xlsx/index.html).
Comment: Right. Thank you very much, biologue and Andre Silva. Sorry for putting this topic here.


Using the CakeDC search plugin with associated models

Question: I'm using CakePHP 1.3.8, and I've installed the CakeDC Search plugin. I have a Tutorial model, which is in a HABTM relationship with a LearningGoal model.
I have a search action & view in the Tutorials controller with which I can successfully search fields in the Tutorial model. I'd also like to filter my tutorial search results using LearningGoal checkboxes on the same form. I've tried adding various parameters to Tutorial's $filterArgs and TutorialsController's $presetVars. I've also tried moving the relevant $filterArgs to the LearningGoal model. I have not yet been able to successfully trigger the entry for learning goals in $filterArgs.
I think I must be missing something obvious. Or maybe the Search plugin doesn't support what I'm trying to do. Does anyone know how to use this plugin to search on associated models?
Answer: So here's what I've figured out. You can combine what's below with the Search plugin directions to search on related models.
The $filterArgs piece in the Tutorial model must look like this:
var $filterArgs = array(
  array('name' => 'LearningGoal', 'type' => 'subquery', 'method' => 'findByLearningGoals', 'field' => 'Tutorial.id'),
);

Here's the supporting function in the Tutorial model:
function findByLearningGoals($data = array()) {
  $ids = explode('|', $data['LearningGoal']);
  $ids = join(',', $ids);
  $this->LearningGoalsTutorial->Behaviors->attach('Containable', array('autoFields' => false));
  $this->LearningGoalsTutorial->Behaviors->attach('Search.Searchable');

  $query = $this->LearningGoalsTutorial->getQuery('all',
     array(
       'conditions' => array('LearningGoalsTutorial.learning_goal_id IN (' . $ids . ')'),
       'fields' => array('tutorial_id'),
     )
  );
  return $query;
}

In TutorialsController, $presetVars should look like this:
public $presetVars = array(
  array('field' => 'LearningGoal', 'type' => 'checkbox', 'model' => 'Tutorial'),
);

And in my search action in TutorialsController, I did this:
$this->LearningGoal = $this->Tutorial->LearningGoal;

The Prg component seems to need that.
Answer: I am using CakePHP version 2.X
Every time I come to do this in a project I always spend hours figuring out how to do it using CakeDC search behavior so I wrote this to try and remind myself with simple language what I need to do. I've also noticed that although Michael is generally correct there is no explanation which makes it more difficult to modify it to one's own project.
When you have a "has and belongs to many" relationship and you are wanting to search the joining table i.e. the table that has the two fields in it that joins the tables on either side of it together in a many-to-many relationship you want to create a subquery with a list of IDs from one of the tables in the relationship. The IDs from the table on the other side of the relationship are going to be checked to see if they are in that record and if they are then the record in the main table is going to be selected.
In this following example
SELECT Handover.id, Handover.title, Handover.description
FROM handovers AS Handover
WHERE Handover.id in
(SELECT ArosHandover.handover_id
FROM aros_handovers AS ArosHandover
WHERE ArosHandover.aro_id IN (3) AND ArosHandover.deleted != '1')
LIMIT 20

all the records from ArosHandover will be selected if they have an aro_id of 3 then the Handover.id is used to decide which Handover records to select.
On to how to do this with the CakeDC search behaviour.
Firstly, place the field into the search form:
echo $this->Form->create('Handover', array('class' => 'form-horizontal'));?>
echo $this->Form->input('aro_id', array('options' => $roles, 'multiple' => true, 'label' => __('For', true), 'div' => false,  true));

etc...
notice that I have not placed the form element in the ArosHandover data space; another way of saying this is that when the form request is sent the field aro_id will be placed under the array called Handover.
In the model under the variable $filterArgs:
'aro_id' => array('name' => 'aro_id', 'type' => 'subquery', 'method' => 'findByAros', 'field' => 'Handover.id')

notice that the type is 'subquery' as I mentioned above you need to create a subquery in order to be able to find the appropriate records and by setting the type to subquery you are telling CakeDC to create a subquery snippet of SQL. The method is the function name that are going to write the code under. The field element is the name of the field which is going to appear in this part of the example query above
WHERE Handover.id in

Then you write the function that will return the subquery:
    function findByAros($data = array())
    {
    $ids = ''; //you need to make a comma separated list of the aro_ids that are going to be checked
    foreach($data['aro_id'] as $k => $v)
    {
      $ids .= $v . ', ';
    }
    if($ids != '')
    {
      $ids = rtrim($ids, ', ');
    }
  //you only need to have these two lines in if you have not already attached the behaviours in the ArosHandover model file
    $this->ArosHandover->Behaviors->attach('Containable', array('autoFields' => false));
    $this->ArosHandover->Behaviors->attach('Search.Searchable');

    $query = $this->ArosHandover->getQuery('all',
       array(
         'conditions' => array('ArosHandover.aro_id IN (' . $ids . ')'),
         'fields' => array('handover_id'),  //the other field that you need to check against, it's the other side of the many-to-many relationship
         'contain' => false //place this in if you just want to have the ArosHandover table data included
       )
    );
    return $query;
  }

In the Handovers controller:
public $components = array('Search.Prg', 'Paginator'); //you can also place this into AppController
public $presetVars = true; //using $filterArgs in the model configuration
public $paginate = array(); //declare this so that you can change it

// this is the snippet of the search form processing
public function admin_find()
  {
    $this->set('title_for_layout','Find handovers');
    $this->Prg->commonProcess();
    if(isset($this->passedArgs) && !empty($this->passedArgs))
    {//the following line passes the conditions into the Paginator component
      $this->Paginator->settings = array('conditions' => $this->Handover->parseCriteria($this->passedArgs));
      $handovers = $this->Paginator->paginate(); // this gets the data
      $this->set('handovers', $handovers); // this passes it to the template

If you want any further explanation as to why I have done something, ask and if I get an email to tell me that you have asked I will give an answer if I am able to.


Err: documentTextDetection is not a function

Question: just follow https://cloud.google.com/vision/docs/detecting-fulltext
got err when runs to the 3rd line
const vision = require('@google-cloud/vision');
const ocr = new vision.ImageAnnotatorClient();
const [r] = ocr.documentTextDetection(file.path);
const fullText = r.fullTextAnnotation;

documentTextDetection is not a function

Ok to call .textDetection()
Environment details
OS: Win 10

Node.js version: 8.14.0

npm version: 6.4.1

@google-cloud/vision version: 1.2.0

Thanks!
Comment: documentTextDetection works for me node.js version 12.9.0   @google-cloud/vision version: 1.2.0 .  Can you post the full code you run?
Comment: @Brendan posted.
Answer: Don't know why, it works once doing it in a Promise
ocr.documentTextDetection(file.path)
      .then(
        function (data) {
          const [r] = data;
          const dr = r.fullTextAnnotation;


Absurde Demonstration strategy

Question: confused about the demonstration of the following statement :
let a, b, c $\in R^{*+}$ .

Demonstrate that: $a*b\geq1$  OR   $a+b \leq \frac{1}{a}+\frac{1}{b}$
Demonstrate that ($a*b\geq1$  And   $a+b \leq \frac{1}{a}+\frac{1}{b}$)
  if and only if $a*b=1$
Let's suppose  that  ($a*b*c\geq1$  And   $a+b+c \leq \frac{1}{a}+\frac{1}{b}+\frac{1}{c}$) , demonstrate that none of a,b and c is equal to 1 and that one of them is less than 1.
Comment: The first two propositions seem straightforward enough, but the third proposition appears to be false; take $a=b=c=1$ as a counterexample. It's also strange to say "let $a,b,c\in\mathbb R^+$" and then prove that none of $a,b,c$ are real; moreover if none are real how can you say that one of them is less than $1.$ Is the last proposition correctly stated?
Comment: @SAM.Am Can you elaborate on why you are confused? If you don't provide any details or share or own attempts, most people will feel they are doing your homework for you...
Comment: You seem to have statement c wrong.  First, the second inequality in  the comment is different from the one in the question.  Also, the comment says, "Show that none of them is equal to $1$," which is translated in the question as "none of them is real."
Comment: What are you confused about?
Comment: @PierreCarre  you are right, I tried to solve the second, which I posted underneath, but I am still  confused about the lack of information related to the first statement.
Comment: @DavidK I translated literally the third question from a French Exercise:
On suppose que  abc>=1 et  a+b+c >= 1/a +1/b +1/c ). Démontrer qu'aucun des Nombres  a,b,c  n'est égal à 1, et que l'un d'entre eux est inférieur à 1.
Comment: @saulspatz thanks for your comment, I update it. Sorry for the confusion.
Comment: The question is still missing the "$+c$" from the comment, and I still don't understand why $a=b=c=1$ isn't a counterexample. My French is extremely poor, so I don't know if there's something else in the original that is still missing from the translation.
Answer: second demonstration solution

Demonstrate that ($a*b\geq1$  And   $a+b \leq \frac{1}{a}+\frac{1}{b}$)
  if and only if $a*b=1$

$a*b\geq1$ => $a\geq \frac{1}{b}$ and $b\geq \frac{1}{a}$
so we have \begin{cases} a+b \geq \frac{1}{a}+\frac{1}{b}  \\a+b\leq \frac{1}{a}+\frac{1}{b}  \end{cases}
therefore $a+b = \frac{1}{a}+\frac{1}{b}$
$=> a+b = \frac{a+b}{ab}$ so $ab = 1$
Comment: Also it's not clear whether you considered the "if" direction of the proof, though that direction is easy.
Comment: For the "if" I would start, "Given $ab = 1.$ Then ..." and you can pretty much write the result right away. Not a big thing, just a formality.
Comment: @DavidK  you are right, it was a typo. I updated it. Thanks.  ( for the   "if". direction, do you mean I ought to start from that condition ?)
Comment: @DavidK. that was my humble translation from French language. (si et seulement si )

Absurde Demonstration strategy


Simple Fancybox not working, following instructions to a tee. Please see my code

Question: I can't get Fancybox to work. I've read the instructions on the fancybox site a million times and it just doesn't work. My image loads as if it would without fancybox. Here's my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css" media="screen" />

Comment: Plain HTML or is this in WordPress or something else?  Is your fancybox in the root folder?  Are you using jQuery for anything else on the page?  Anything else not showing up or working?
Answer: check fancybox href attribute and src attribute they point to root so you need to remove the first slash /

<link rel="stylesheet" href="fancybox/jquery.fancybox.css" type="text/css" media="screen" />

Comment: wouldn't that only matter if his site is not in the root folder?  Might have just removed his domain from the example.
Comment: and add `class="fancybox"` to the link like @dani said
Comment: This was it! Thanks so much. I was also missing the class in my example but I had it in my version. The problem was the path. Thank you!
Answer: Add class="fancybox" to the a tag.
Like this:

You're using $('.fancybox'), which makes jQuery look for fancybox class.


Campo do tipo Date do MySQL retornando valor incorreto no Java

Question: Estou tentando ler os dados de uma tabela do MySQL com o Java, porém o campo do tipo Date está retornando o seguinte código:
java.util.GregorianCalendar[time=1558656000000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT-03:00",offset=-10800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=4,WEEK_OF_YEAR=21,WEEK_OF_MONTH=4,DAY_OF_MONTH=23,DAY_OF_YEAR=143,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=-10800000,DST_OFFSET=0]

Este é o método que busca os valores do banco:
public List<Contato> getLista() {
        try {
            List<Contato> contatos = new ArrayList<Contato>();
            PreparedStatement stmt = this.connection.prepareStatement("SELECT * FROM contatos");
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Contato contato = new Contato();
                contato.setId(rs.getLong("id"));
                contato.setNome(rs.getString("nome"));
                contato.setEmail(rs.getString("email"));
                contato.setEndereco(rs.getString("endereco"));

                Calendar data = Calendar.getInstance();
                data.setTime(rs.getDate("dataNascimento"));
                contato.setDataNascimento(data); # Retorna a Data

                contatos.add(contato);
            }
            rs.close();
            stmt.close();
            return contatos;

        } catch (SQLException e) {
            throw new RuntimeException(e);

        }
}

E depois chamo no método Main:
public static void main(String[] args) {

        ContatoDao dao = new ContatoDao();

        List<Contato> contatos = dao.getLista();

        for (Contato contato : contatos) {
            System.out.println("Nome: " + contato.getNome());
            System.out.println("Email: " + contato.getEmail());
            System.out.println("Endereço: " + contato.getEndereco());
            System.out.println("Data de Nascimento: " + contato.getDataNascimento() + "\n");
        }
    }

Comment: Pra entender melhor, você gostaria de conseguir exibir a data formatada, por exemplo: 24/05/2019?
Comment: Na linha  `contato.getDataNascimento()` acrescente `getTime()`, ficando assim: `contato.getDataNascimento().getTime()`
Comment: E qual deveria ser o valor correto?
Comment: @GilvanAndré Sim neste formato dd/MM/YYYY
Comment: Obrigado @adventistaa era isso mesmo!
Comment: @hkotsubo dd/MM/YYYY.
Answer: Aproveitando o seu código na função getDtNascimento, você pode adicionar o getTime().
Exemplo:
Calendar data = Calendar.getInstance();
data.setTime(rs.getDate("dataNascimento"));
contato.setDataNascimento(data); # Retorna a Data

E na hora de chamar você chama assim:
System.out.println("Data de Nascimento: " + contato.getDataNascimento().getTime() );

Caso queira formatar a data o formato brasileiro pode fazer o seguinte antes:
SimpleDateFormat formatoBR = new SimpleDateFormat( "dd/MM/yyyy" );
String newDate = formatoBR.format( contato.getDataNascimento().getTime() );
System.out.println("Data de Nascimento: " + newDate );

Comment: Era isso mesmo , funcionou. Muito Obrigado!


Prove the locus of $M$ is a conic passing though $I$ and $J$.

Question: Problem: In the perspective plane $\mathbb{P}^2$, given a conic $(S)$ and a line $d$ having no intersection with $(S)$. Fixed two points $I$ and $J$ on $d$. Take a variety point $M$ such that the tangents from $M$ to $(S)$ intersect $d$ at two points $R$ and $S$ such that $(IJRS)=-1$. Prove the locus of $M$ is a conic passing through $I$ and $J$.
Here is what I've discovered so far.

Let the tangents from $I$ and $J$ touch $(S)$ at $I_1,I_2$ and $J_1,J_2$ respectively. Then the locus of $M$ is the conic passing through $I,I_1,I_2,J,J_1,J_2$. I also proved those 6 points lie on a conic (let's call it $(S')$).

Take any point on $(S')$, call $A$. Then the intersection $A_1, A_2$ of two tangents from $A$ to $(S)$ and $d$ satisfy $(IJ,A_1A_2)=-1$. Now I'm stucking at proving this claim.

2'. Something that might be useful for proving 2: Let $P$ the polar of $d$ wrt $(S)$. Then $PI$ and $PJ$ tangent to $(S')$.
Can I have some hints for the next steps? Any ideas would be appreciated. Thanks for reading.
Comment: I'm so sorry. Thanks for answering all my problems. I haven't noticed the button until you mention.
Answer: This locus is discussed in Milne, Cross Ratio Geometry, Article 185.
There, $P,A,B$ correspond to OP's $M,I,J$ and the condition that the lines $PA,PB$ are conjugate is equivalent to OP's $R,S$ being harmonic with $I,J$.
The proof relies on the locus conic being defined by the intersections of two homographic pencils centered at $A$ and $B$.
The excerpt is below.  But the full reference is given above if background and definitions need to be consulted.

I've added a discussion of the claim "range ($c$) = range ($d$)" in a separate answer.
Comment: I'm trying to approach the problems again and trying to understand the solution clearly. I don't really understand what does range (c) =range (d) refers to? I've been reading the whole definition in the book but still don't quite understand. Does range (c) refers to (cdCD) or range (c) refers to the range containing c and any three other fixed points in the line CD (I have checked this case in GeoGebra and it seems that it's not true ). Sir, if you have read the book, please help me, what does range (c) refer to and why range (c) = range (d)
Answer: The other answer here uses a proof by Milne that claims "range (c)=range(d)".  What does that mean?
On page 29 the notations "range (a)" and "pencil P(a)" are defined.
For our purposes, a "range" is any collection of collinear points and a "pencil" is any collection of concurrent lines.  Often ranges and pencils contain just four elements so that we can take cross ratios, but in general they contain an arbitrary number of elements.

For shortness we shall often denote a range (abcde ...) by (a), and a
pencil P{abcde ...) by P(a)

(Chapter IV is worth a read, or at least a skim)
Unfortunately, I cannot find any explicit definition by Milne of what is meant by "range(a)=range(b)" or "pencil P(a)= pencil P'(a')".  From context is seems to be that "range(a)=range(b)" means the two are homographic.  In fact, on page 187 pencils and ranges are said to be equal (homographic) as in:

the pencil $\rho(m)$ = the range of poles $(m)$ = the pencil of polars
$P(\mu)$

Does this help?  Getting back to your question, I interpret

And the range (c) = the range (d), therefore the pencil A(P) = the
pencil B(P),

as
"Because range(c) is homographic to range(d) the pencil A(P) is homographic to B(P)"
In all of the above, ranges and pencils are held to be homographic because they preserve cross ratios. In particular, you should verify that the conjugacy $c \to d$ preserves cross ratio and thus is homographic.
Comment: Yes, glad you like the book.  There's another book by Hatton that I like that also contains the theorem - look at the bottom right of pg 295: https://archive.org/details/cu31924060184045/page/n309/mode/2up.  The proof is on the following page, right hand column.  It's a slightly more elegant version than Milne's, but you still have to do some work to understand it. "projective" means "homographic"  Let me know if you need more explanation..
Comment: Now the problem becomes much brighter. I still don't know why they are homographic but as I'm gradually reading the book, I believe I will find out the answer soon. Thanks for helping me and thanks for the awesome book.


What does l.v. with a dashed line following it mean?

Question:
In the image above, I see the l.v. symbol with a dashed line following it.
Answer: L.v = laissez vibrer. Let ring. As in let the notes played carry on, so they blend into each other. Rather like using the sustain pedal. Or even the sostenuto pedal, if, there is one, and if, your playing is good enough to deploy it properly.
Let ring - written as such, is found in guitar music - mainly TAB.


How to layout in android a complex layout

Question: I'm trying to find a way to layout the following layout in Android:

Where as (4) is a background color, which should be centered on the bottom of the screen and be exactly 1/3 width of the screen. (1),(2),(3) are images, where (1) and (2) should be centered inside (4), and (3) should be centered on the right-top corner of (4).
Nothing works for me :(
How to use Android Layouts for this one?
EDIT:
I managed to create (1)+(2)+(4), but no luck with (3). Here is my code:
<code>    <LinearLayout
        android:id="@+id/layout4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:gravity="center"
        android:weightSum="1.0" >

        <LinearLayout
            android:id="@+id/layoutSaveShare_inner"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="0.33"
            android:background="@color/light_blue"
            android:gravity="center"
            android:orientation="horizontal"
            android:weightSum="1.0" >

            <ImageView
                android:id="@+id/img1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.43"
                android:src="@drawable/btn1" />

            <ImageView
                android:id="@+id/img2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.43"
                android:src="@drawable/btn2" />
        </LinearLayout>
    </LinearLayout>
</code>
Thanks
Comment: I didn't understand your answer. If you do want 3 to have it's center in 4's top-right corner then no, you can't do this in the layout, you'll need to measure and position 3 at runtime. If it doesn't need to be in the center then you could do it in the xml layout with an arbitrary value for the space. However if 3 has dynamic dimensions this could lead to some problems.
Comment: You can't place the views around the center of 3 in the xml layout.
Comment: I don't need that. (4) is centered in the screen and (3) should be placed according to (4) - in its' right-top corner
Comment: From your image it appears like 4's top-right corner is exactly in the center of 3. You don't want this?
Comment: Yeah, you can say it that way as well :) It's impossible?!
Comment: I know the dimensions of the elements, except (4) which is 1/3 width of the screen. I guess I'll have to position (3) in runtime. Many Thanks
Answer: How about something like the following sudo code:
<code><someParentLayout>
<____Layout android:weight="33">
     <child items>
</_____Layout>
<RelativeLayout android:weight="67"
      android:background="blah">
      <TextView android:id="@+id/center_reference"
            android:layout_height/width="0dp"
            android:layout_centerInParent="true"/>
      <Images 2 & 3 to the left and right of "center_reference"
            android:layout_centerVertical="true"/>
</RelativeLayout>
</someParentLayout>
</code>
The only part that you will need to experiment with is #3, I'm not too sure on that one.
Comment: Thanks, but I managed to do that part... the problem is (3) in my drawing
Comment: Hmm.. if you want it the way you describe it in text, wouldn't that place the right half of the image off the screen?
Comment: nope. (4) is centered in the screen and is only 1/3 of the screen - thus (3) is still inside the smartphone screen
Comment: Ohh, 1/3 width? height? both?


Is it possible to use "swing" for only one staff in Musescore?

Question: I have an arrangement which is played in swing through the whole song. Now, I want to remove swing for a short section, but only for one staff. Is that possible? It's meant for the playback.
Comment: I think for the notation you want to put in a line above that says "straight 8ths" (or 16ths or whatever). I'm not sure if you can affect playback on only one staff though.
Comment: Is this just for a score, or for playback?
Comment: @Richard for playback
Answer: Quick answer:  Yes in Sibelius, Dorico and Finale (current versions) but No for MuseScore.  In MuseScore 'Swing' and 'Straight' affect all the staves.
I don't think there's even any way to cheat it in MuseScore by micro-editing individual notes. Individual velocity, and even tuning, can be edited, but not playback position. Sorry.
Answer: It is very unusual to notate swung notes on the staff. Typically, the notation I see as Todd notes is the beginning of the tune is notated "Swing Feel" and then text notation for "Straight 8ths" for the straight part.
Some people like to put this in after "Swing Feel"

but honestly true swing feel is not played strictly like this and actually playing this accurately will sound clunky.


How might a user configure which video is shown on page without editing the page?

Question: A Drupal 7 site has an embedded YouTube video on the home page. It is not always displayed. Sometimes the video being displayed is changed. The home page is arranged by a Page Manager Variant, and the container with the video is "Custom Content". When someone wants to hide/show the video or change the link, they have to ask me because the Page Manager can only be accessed by an administrator. I want to give certain users the ability to show/hide the video and change the video to which it links, but without changing other content on the home page or modifying the layout of the site.
I don't really know what I'm doing when it comes to Drupal, and I'm having trouble figuring out the right things to search for to accomplish this.
I want the appropriate users to be able to choose which YouTube video is embedded and whether it is shown. What is the best way to do that?
Comment: My opinion: Custom module, new permission "edit front page video", new admin settings form only accessible to roles with the new permission, form with textfield to paste the video link, save it into a variable, then programmatically build the YouTube markup from that variable value (the link, with fallback maybe) and either preprocess the resulting markup into the page or have a custom block placed at the right place to render it.
Answer: Step 1

Create a content type: e.g. "Home Page Video".
Add fields: YouTube, text area, image, etc. Basically all the fields you would want to structure that "section" on the home page.
Give permissions for the fields with field permissions (additional security measure, you'll see why later)

Step 2

Create a few nodes for "Home Page Video"
Set your view modes

Step 3

Create a View to show only "Home Page Video" content.
Choose Bootstrap Grid (Views Bootstrap module and Bootstrap Field
Group module) and add fields
OR
Choose unformatted list: Rendered
entity and a View Mode
Set a filter: "promoted to front page"
Set a Pager: Display a specified number of items and choose 1, More
link: no
Set a sort criteria: "Content: Updated date" (The date the content
was last updated.) and set it to "descending"
Create a pane view from this view.
Save

Step 4

Enable: System - page_manager - node_edit - Node add/edit form -
/node/%node/edit
Create a new variant of node_edit template in Page Manager
Selection rule: Node being edited is bundle "Home Page Video"
Selection rule: Logged in user has one of "my user role"
Content: Add the form fields you want this user to edit AND add the
base form (General Form) in order to get the submit button. If you
have set certain fields to be required on your Home Page Video
content type, they will show in the base form UNLESS you add them in
through the cog wheel "Add content" and choose FORM and then choose
the specific form field that is required. Like that you have the
ability to choose where that field goes in your edit form layout.
More control.
Save

Step 5

Add your pane view of "Home Page Video" to your Home Page Page Variant at the position where you want it to show up on your Home Page.
In order for your pane view to show up, you might have to clear the cache. If you use Drush, simply type: drush cc all
Go look again for that pane view and add it.
Save

Et voilá.
No need for a custom module. Permissions are dealt with by the 'selection rules' in your node_edit page variant.


Como converter os caracteres dentro do formulário e imprimo em tela?

Question: Como faço com que os caracteres de - sejam convertidos em : número dentro do formulário.

Ao colar um número dentro do formulário, como no exemplo acima; quero que os - sejam convertidos em :, ficando 00:00:00:00.

function substituiPonto(){
  valor = document.calcform.visor.value;
  document.getElementById("visor").value = valor.replace("-", ":");
}
function tela(){
  window.alert(valor);
}
<form name="calcform" method="post" action="">
  <input type="text" name="visor" id="visor" value="" onKeyPress="substituiPonto()"/>
</form>

Por esse código eu só consigo que converta enquanto digito, e não converte quando dou CTRL+V dentro do formulário.
Comment: Poderia incluir a propriedade `onfocusout="substituiPonto()"` no seu _input_. No seu _JavaScript_, em vez de usar a função `replace()`, usaria `replaceAll()`. Dessa forma, ao retirar o `focus` do seu input, chamaria a função `substituiPonto()`, e faz um _replace_ em todos os `-` por `:`.
Comment: Poderia me mostrar como ficou o código pra você?
Comment: Coloquei na resposta Lucas, veja se resolve seu problema
Comment: Excelente amigo! Muito obrigado!
Answer: Colocando o onfocusout="substituiPonto(), aproveitando sua função substituiPonto(), apenas substituindo replace() para replaceAll(). Quando colar (CTRL+V) o formato 00-00-00 por exemplo, e ao sair do seu input, ou seja, no evento onfocusout, será chamado substituiPonto(), substituindo todo - encontrado por :. Aí já poderia exibir no formato que você quer, utilizando :.

function substituiPonto(){
  valor = document.calcform.visor.value;
  document.getElementById("visor").value = valor.replaceAll("-", ":");
}
function tela(){
  window.alert(valor);
}
<form name="calcform" method="post" action="">
  <input type="text" name="visor" id="visor" value="" onKeyPress="substituiPonto()" onfocusout="substituiPonto()"/>
</form>


Confidence interval length less than 2

Question: The time of execution for one program follows a normal distribution. For a sample of size $40$ we have: $\overline{x} = 32.2 s$ and $\sigma^{2} = 3.1s^{2}$
How many times we have to execute the program to obtain a $95\%$ confidence interval with the lenght of interval less than 2 seconds?
Because the program follows a normal distribution we have that de confidence interval is
$$\left[ \frac{1}{n}\sum X_{i} - \frac{Z_{\alpha/2}\sigma}{\sqrt{n}},\frac{1}{n}\sum X_{i} + \frac{Z_{\alpha/2}\sigma}{\sqrt{n}} \right]$$
so, the lenght interval is
$$2\frac{Z_{\alpha/2}\sigma}{\sqrt{n}}$$
and we need that
$$\frac{Z_{\alpha/2}\sigma}{\sqrt{n}} < 1$$
I first thought that I could use $\sigma = \sqrt{3.1}$ but this was for the sample of size $40$ so i don't know if I can use it.
Answer: In your situation you know the distribution is Gaussian but you eve do not know its variance. Given a sample size =40 you can assume that your $\hat{\sigma^2}=3.1$ is a good approximation...thus your reasonig is good and you can find
$$n\ge 1.96^2\cdot3.1\approx 11.91=12$$

Confidence interval length less than 2


When $p(n,m)=\sum\limits_{k=0}^{m}n^{k}$, find $(n,m)$ that $p(n,m)$ is square. $n \in \mathbb N,n>1$.

Question:
When $p(n,m)=\sum\limits_{k=0}^{m}n^{k}$, there are no other solution exept $(n,m)=(7,3),(3,4)$ that $p(n,m)$ is square. $n,m \in \mathbb N,n,m>1$.

I got when $m$ is square number, $(1,m)$ is solution.
When $m=2$,
$n^2 < n^2+n+1<(n+1)^2$
and I got $(7,3)$ and $(3,4)$ for $m=3$ and $4$.
I couldn't find when $m=5$. I didn't think that there are only this solution, but I thought $m=5,6,7,8$ has no solution.
Comment: @rtybase I wrote in post,$p(n)=n^m+n^{m-1}+ .......+n^2+n+1$
Comment: @rtybase I found what you confuse of. Yes, I find solution (n,m) that p(n,m) is perfect square. I fix my post about it.
Comment: What is $p(n)$?
Comment: Yes, you did, but that is followed immediately by <> which begs for "solution for what?" and as a result "what is $p(n)$?". Whether in fact you are looking for solutions for $\sum\limits_{k=0}^{m}n^k$ being a perfect square.
Answer: The solution is given in Ribenboim's book on Catalan's conjecture, where all Diophantine equations $$y^2=1+x+x^2+\cdots +x^m$$ are studied.
For example, if $m=3$, then only $(x,y)=(1,2)$ and $(x,y)=(7,20)$ are integer solutions, just as you have found.


how should i architect aws lambda to support parallel process in batch model?

Question: i have an aws lambda function to do some statistics on over 1k of stock tickers after market close. i have an option like below.

setup a cron job in ec2 instance and trigger a cron job to submit 1k http request asyn (e.g. http://xxxxx.lambdafunction.xxxx?ticker= to trigger the aws lambda function (or submit 1k request to SNS and let lambda to pickup.

i think it should run fine, but much appreciate if there is any serverless/PaaS approach to trigger task
Comment: A better approach might be to put your tasks into an SQS-queue and use that queue as event trigger for your Lambda function.
Comment: thanks for the info. if using SQS-queue as event trigger my function, how can i know all of my 1k tickets finish before my next step of batch job? I wonder if i need to write a separate process to monitor status for those 1k lambda jobs
Comment: You could have a look at AWS Step Functions and if they fit your need for that.
Comment: thanks a lot for your suggestion
Answer: On top of my head, Here are a couple of ways to achieve what you need:

Option 1: [Cost-Effective]

Post all the ticks to AWS FIFO SQS queue.
Define triggers on this queue to invoke lambda function.

Result: Since you are posting all the events in FIFO queue that maintains the order, all the events will be polled sequentially. More-over SQS to lambda trigger will help you scale automatically based on the number of message in the queue.

Option 2: [Costly and can easily scale for real-time processing]

Same as above, but instead of posting to FIFO queue, post to Kinesis Stream.
Enable Kinesis stream to trigger lambda function.

Result: Kinesis will ensure the order of event arriving in the stream and lambda function invocation will be invoked based on the number of shards in the stream. This implementation scales significantly. If you have any future use-case for real-time processing of tickers, this could be a great solution.

Option 3: [Cost Effective, alternate to Option:1]

Collect all ticker events(1k or whatever) and put it into a file.
Upload this file to AWS S3 bucket.
Enable S3 event notification to trigger proxy lambda function.
This proxy lambda function reads the s3 file and based on the total number of events in the file, it will spawn n parallel actor lambda function.
Actor lambda function will process each event.

Result: Easy to implement, cost-effective and provides easy scaling based on your custom algorithm to distribute the load in the proxy lambda function.

Option 4: [All-serverless]

Write a lambda function that gets the list of tickers from some web-server.
Define an AWS cloud watch rule for generating events based on cron/frequency.
Add a trigger to this cloudwatch rule to invoke proxy lambda function.
Proxy lambda function will use any combination of above options[1, 2 or 3] to trigger the actor lambda function for processing the records.

Result: Everything can be configured via AWS console and easy to use. Alternatively, you can also write your AWS cloud formation template to generate all the required resources in a single go.

Having said that, now I will leave this up to you to choose the right solution based on your business/cost requirements.
Answer: You can use lambda fanout option.
You can follow these steps to process 1k or more using serverless aproach.
1.Store all the stock tickers in a S3 file.
2.Create a master lambda which will read the s3 file and split the stocks in groups of 10.
3. Create a child lambda which will make the async call to external http service and fetch the details.
4. In the master lambda Loop through these groups and invoke 100 child lambdas passing in each group and return the results to the
Master lambda
5. Collect all the information returned from the child lambdas and continue with your processing here.

Now you can trigger this master lambda at the end of markets everyday using CloudWatch time based rule scheduler.
This is a complete serverless approach.


XMLUnit 2 DiffBuilder ignoreComments() raises exception with Saxon HE

Question: The following simple example demonstrates the problem:
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.builder.Input;
import org.xmlunit.diff.ComparisonControllers;
import org.xmlunit.diff.DefaultNodeMatcher;
import org.xmlunit.diff.Diff;
import org.xmlunit.diff.ElementSelectors;

public class AnyDiff {

    public static void main(String[] args) throws Exception {
        String controlstr = "<root>hello</root>";
        String teststr = "<root>hello</root>";
        Diff diff = DiffBuilder.compare(Input.fromString(controlstr))
                .withTest(Input.fromString(teststr))
                .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))
                .checkForSimilar()
                .ignoreWhitespace() // this is working with newest Saxon 9.8.0-2 (not worked with 9.7.0-15
                .ignoreComments()  // this is not working even with newest Saxon 9.8.0-2
                .withComparisonController(ComparisonControllers.Default)
                .build();
        System.out.println(diff.hasDifferences());
    }
}

Running the above example the following exception is generated:
run:
Warning at char 6 in template/@match on line 1 column 122
  XTDE0160: An error occurred matching pattern {( element() | text() | comment() |
  processing-instruction() )[not(error("XPath 1.0 Compatibility Mode is not available in
  this configuration"))]}: XPath 1.0 Compatibility Mode is not available in this configuration
Warning at char 6 in template/@match on line 1 column 122
  XTDE0160: An error occurred matching pattern {( element() | text() | comment() |
  processing-instruction() )[not(error("XPath 1.0 Compatibility Mode is not available in
  this configuration"))]}: XPath 1.0 Compatibility Mode is not available in this configuration
Error
  org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node
  where it is not permitted.
Exception in thread "main" org.xmlunit.XMLUnitException: org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
        at org.xmlunit.transform.Transformation.transformTo(Transformation.java:190)
        at org.xmlunit.transform.Transformation.transformToDocument(Transformation.java:220)
        at org.xmlunit.input.CommentLessSource.<init>(CommentLessSource.java:45)
        at org.xmlunit.builder.DiffBuilder.wrap(DiffBuilder.java:389)
        at org.xmlunit.builder.DiffBuilder.build(DiffBuilder.java:368)
        at hu.telekom.reflex.util.AnyDiff.main(AnyDiff.java:27)
Caused by: net.sf.saxon.trans.XPathException: org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
        at net.sf.saxon.dom.DOMWriter.characters(DOMWriter.java:222)
        at net.sf.saxon.event.ProxyReceiver.characters(ProxyReceiver.java:190)
        at net.sf.saxon.event.ComplexContentOutputter.characters(ComplexContentOutputter.java:277)
        at net.sf.saxon.trans.TextOnlyCopyRuleSet.process(TextOnlyCopyRuleSet.java:75)
        at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:477)
        at net.sf.saxon.trans.TextOnlyCopyRuleSet.process(TextOnlyCopyRuleSet.java:66)
        at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:477)
        at net.sf.saxon.trans.TextOnlyCopyRuleSet.process(TextOnlyCopyRuleSet.java:66)
        at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:477)
        at net.sf.saxon.Controller.transformDocument(Controller.java:2389)
        at net.sf.saxon.Controller.transform(Controller.java:1953)
        at net.sf.saxon.s9api.XsltTransformer.transform(XsltTransformer.java:589)
        at net.sf.saxon.jaxp.TransformerImpl.transform(TransformerImpl.java:73)
        at org.xmlunit.transform.Transformation.transformTo(Transformation.java:186)
        ... 5 more
Caused by: org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
        at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(ParentNode.java:361)
        at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(ParentNode.java:288)
        at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(CoreDocumentImpl.java:447)
        at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:237)
        at net.sf.saxon.dom.DOMWriter.characters(DOMWriter.java:219)
        ... 18 more

My project is running in Java 8 environment.
If I comment out the
.ignoreComments()

line the code is working as expected.
Would you help how can I ignore comments in XML comparison (of course with running Saxon as XSLT provider)? Thanks in advance.
Comment: Of course I can remove comments with a simple regex like xmlString.replaceAll("(?s)", "") but I would like to use ignoreComments()  in the chain.
Answer: There's obviously a bit of a history of recent bugs here.
https://github.com/xmlunit/xmlunit/issues/92
which refers to
https://saxonica.plan.io/issues/3241
And looking at github, I see that the relevant code in xmlunit is changing daily.
So it's going to be important to work out exactly what version of everything you are using.
I don't know if you are associated with the xmlunit project in any way. Generally if an application using Saxon is failing, it's best to raise the bug report in the first instance against the application, if only because they may well already know about it; they're also better placed to provide a repro that demonstrates the bug in Saxon if that's where it is. But if that doesn't get you anywhere, raise it at saxonica.plan.io.
StackOverflow isn't really an ideal vehicle for tracking bugs, especially ones that involve the integration of multiple products, so I'd advice following it up through support channels.
Two further observations:
(a) the warning messages
XTDE0160: An error occurred matching pattern {( element() | text() | comment() | processing-instruction() )[not(error("XPath 1.0 Compatibility Mode is not available in this configuration"))]}: XPath 1.0 Compatibility Mode is not available in this configuration
are probably significant. Saxon 9.8 has introduced a change, which I'm afraid is going to be rather inconvenient to open source projects like xmlunit: the HE product no longer supports backwards compatibility mode with 1.0. This may well mean that xmlunit will not work with Saxon-HE 9.8 unless it makes changes.
(b) the DOM HIERARCHY_REQUEST_ERR probably arises because the stylesheet is trying to write a text node as a child of the document node, which is allowed in the XDM model but not in DOM. However, I suspect this is a secondary error caused by the fact that the expected template rules have not fired, as a consequence of the error that arose during pattern matching. When an error occurs in pattern matching, the pattern is treated as not matching, and Saxon continues with a warning.
Comment: Thanks Michael for your answer. I have read your suggested documents before I have created my question here (they did not help to solve my problem just helped to bring closer to understand the situation) and I have written feedback there as well. I am using xmlunit-core 2.3.0 and Saxon-HE 9.8.0-2 from maven central. Xmlunit was my choice only for collecting differences in two XML documents.  I have only problem with ignoreComments. Do you think I can use different solution for this? Should I wait for new releases?
Comment: I would't use Saxon 9.8 with xmlunit until someone from xmlunit confirms that it's supported.
Comment: Maybe I was not clear that with Saxon 9.7 the ignoreWhitespace() also not working with xmlUnit. With Saxon 9.8 this is working now. Only the ignoreComments() is not working (it was not working in 9.7 version as well) so the situation is much better for me. First I have used xmlUnit for XML comparison, later I have moved toward Saxon because of XSLT 2.0 support which became important for me. Than I have encountered some interference between the two libraries. My unit tests are working (only ignoreComments fails).
Comment: Let's try and use the support channel to get this one resolved.
Comment: Thx Michael, I will join to the ticket at your mentioned saxonica link :-)
Comment: I have upgraded just now to xmlunit-2.4.0 and saxon-HE 9.7.0-19 and the ignoreComments() method works again perfect. I have downgraded to saxon 9.7 from 9.8 (because of strict XSLT 2.0 rule in saxon 9.8 as you have suggested).
Comment: I just add a comment about the ignoreComments() issue (https://github.com/xmlunit/xmlunit/issues/92) has it could be fix in Xmlunit2.
Comment: For information the ignoreComments() issue with Saxon 9.8 has been fixed as mentioned in https://github.com/xmlunit/xmlunit/issues/99. Waiting for 2.5.0 release


Classification on variable-length time series

Question: I have a series of transactions like the following:

[0, 2, 2, 3, 1, 0, 0, 0, 1]
[1, 0, 0]
[3, 3, 1, 1]

I would like to classify each transaction as being part of one of two categories: class A or class B, the issue is that a transaction can have any length from 2 to 150 in my case. What is the best approach for classifying similar variable size time series?
Comment: Do you have more labelled examples ? You might try adding summary values as a separate feature vector.
Answer: You can use Dynamic Time Warping distance measure, which can tell distance between different length time series. This question has some nice answers about how to do that.
However it would be instructive to construct certain summary statistics for the series and do the clustering on them.
Comment: Thank you, I applied an algorithm for the compression of the time series and applied DTW with KNN, it's working like a charm. I tested DTW before posting here but wasn't getting good results, you gave me the input to adapt the time series and retry with DTW.


Unity3D values disappear from custom editor when starting game

Question: I have a problem when changing values and trying to play game these values disappear. For example, if I enable bool in editor and the start game bool disables itself. I use custom editor to change these values.
This is my settings script and [system.serializable] doesn't help:
using UnityEngine;

[System.Serializable]
public class Settings : MonoBehaviour
{
    public static bool testMode;
    public static string androidUnitID;
    public static string iphoneUnitID;
}

And this is my editor script:
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Settings))]
class TestEditor : Editor {

    public override void OnInspectorGUI() {

        GUILayout.Label("Settings", EditorStyles.boldLabel);

        Settings.testMode = EditorGUILayout.Toggle("Test Mode", Settings.testMode);
        Settings.androidUnitID = EditorGUILayout.TextField("Android UnitID", Settings.androidUnitID);
        Settings.iphoneUnitID = EditorGUILayout.TextField("Android UnitID", Settings.iphoneUnitID);

}

First I'm changing values on editor:

Then when play mode is active all values disappear:

Is there any way to fix this problem?
Thank you for your help.
Comment: did you know you have a . at the end of `Settings.settings` in the line `Settings.settings. = EditorGUILayout.Toggle("Test Mode", Settings.testMode);`, in regards to your question can you explain it a little bit better?  Are you saying that you set these values in your editor script, but when you start the game the values change?  Are you sure you have nothing else changing those values anywhere?  since they are static and all objects will reference the same one.
Comment: Thank you for help. I made a mistake when I was rewriting code, everything is working without problem. The thing is that values are not changed anywhere but still values disappear. I've added some pictures to get the idea.
Answer: Unity doesn't support serialising static variables "out-of-the-box" (you can rewrite the serialisation to accommodate it, but effort vs. reward and all that). So, based on that, what you're essentially seeing is the values that you're setting being stored in the class during Edit, but when Unity goes into Play mode, all the class are re-initialised, deserialised and prepared for game-play. Your static values are lost.
It's the same reason why changed values during game play aren't kept when you go back the other way to Edit mode. Edit mode and Play mode are essentially two separate processes.
Your best bet here would be to create a ScriptableObject, with those fields you've marked as static in your Settings class, create a reference to the new ScriptableObject, and then, if you want, modify the values directly from the ScriptableObject.
Something along the lines of:
[CreateAssetMenu ( fileName = "Settings", menuName = "Settings/Create Settings SO", order = 1 )]
public class SettingsScriptableObject : ScriptableObject
{
  public bool testMode;
  public string androidUnitID;
  public string iphoneUnitID;
  //... Any further configuration/settings items you want should go here.
}

You would then modify your Settings class:
public class Settings : MonoBehaviour
{
  public SettingsScriptableObject SettingsSO;
}

And your editor script:
[CustomEditor(typeof(Settings))]
class TestEditor : Editor
{
  public override void OnInspectorGUI()
  {
    if ( target == null ) return;
    var settings = target as Settings;
        GUILayout.Label("Settings", EditorStyles.boldLabel);
        settings.SettingsSO.testMode = EditorGUILayout.Toggle("Test Mode", settings.SettingsSO.testMode);
        settings.SettingsSO.androidUnitID = EditorGUILayout.TextField("Android UnitID", settings.SettingsSO.androidUnitID);
        settings.SettingsSO.iphoneUnitID = EditorGUILayout.TextField("Android UnitID", settings.SettingsSO.iphoneUnitID);
  }
}

There's an excellent video at Unity about the Edit and Play modes, and how ScriptableObjects can be used to overcome the serialisation problem.


How to filter crystal report in C#?

Question:
When I select values from drop down then click on show button it should show the crystal report for that selection.
Comment: Have you created parameters in your .rpt?
Comment: I have to create .rpt after selecting options from drop down.
Comment: Ihsanullah - What code are you using to load the combo boxes up at the top of your form?  Others may be able to offer more help if they could see some of your code.
Answer: If you are filtering programatically, you can type
crystalreportViewr1.selectionformula="{Report.Fieldname}='"+filterdata+"'";

This is for filter the string data type.
For int data type to be  filtered,
crystalreportViewr1.selectionformula="{Report.Fieldname}="+filterdata;

Answer: string myQuery = "{Report.FieldName} < '1000'";

crystalReportViewer.SelectionFormula = myQuery;

Comment: Hi, I am having a bit of challenge with passing parameters to crystal report from c#. In the above code, does Report mean the full name of the report file or the database table name.
Comment: @Kunbi I had the same issue, Report refers to the table name as it is written in report. For example if the table name is `table`, in Crystal Reports, the name may be `table1`

How to filter crystal report in C#?


How to make a variable LIMIT in a query, using MYSQL

Question: I'm trying to build a query with a variable limit. As far as I know I cannot do something like select * from table limit my_variable;, but I've read on the internet about a workaround:
SET SQL_SELECT_LIMIT = variable;

I have to write this syntax before the query I want to apply the LIMIT in. This works fine if I write a SELECT query after that code line, but it does not work if I write the following code instead:
INSERT INTO table
SELECT * FROM table1;

It will insert every record of the table1 in table2, instead of inserting the quantity of records specified in the first code line I wrote in this post.
How can I accomplish this?
Answer: Using prepared statements to dynamically compose SQL queries.


wrap LaTeX command in environment

Question: How can I wrap a LaTeX command in an environment? In essence, how can I turn \somecommand{contents} into \begin{somecommand} contents \end{somecommand}? I have tried the obvious in creating a new environment as such:
\newenvironment{somecommand}[0]{
  \somecommand{
}
{
  }
}

but this causes problems with the curly brackets. Let me give a more concrete example. Say that you want to create the environment very-important and you want to use the command emph to accomplish this. An straightforward (but incorrect) solution would be to write something as
\newenvironment{very-important}[0]{
  \emph{
}
{
  }
}

The problem here is that the command works with the information that is found inside the environment, so it is not one of the opening commands of the environment, nor is it a closing command of the environment. The question is then: how can you do this?
Answer: This can be done with the environ package as follows:

\usepackage{environ}
...
\NewEnviron{very-important}{\emph{\BODY}}

\BODY contains the body of the environment, and environments may be nested. See the documentation for more details.
Answer: It seems that now I can guess what is the question.
\newenvironment{very-important}{\startimportant}{}
\def\startimportant#1\end{\emph{#1}\end}

\begin{very-important}
Something
\end{very-important}

This solution works well.
But IMHO it is bad idea to wrap all text in the environment. Why?
There are two ways to do something with the text.
For example, you want to change the font and use italic.

The first method. \textit{sentence written in italics}
The second method. {\it sentence written in italics\/}

What is the difference? The thing is that first method use the second one.
\it macro changes the font and the brace } changes it back.
\textit macro reads the full argument, changes the font and inserts the argument again:
\textit is defined roughly as follows (not exactly).
\def\texit#1{{\it#1\/}}

The first method is always doing extra work. It reads the argument twice.
Almost always, you can make changes and then you can everything back.
Eventually why do you use the environment? Use macros.
\veryimportant{
   Any thought
}

Answer: A Simpler way could be:
\newenvironment{somecommand}[0]{
  \somecommand\bgroup
}
{
  \egroup
}

Explanation: \bgroup works like { and \egroup works like }.
Answer: New environment somecommand defines the macro \somecommand.
You can not use macro with the same name \somecommand inside.
Moreover you should write
\newenvironment{name}{openning command}{closing commands}

rather than
\newenvironment{somecommand}[0]{ \somecommand{ } { } }

You obviously have a problem with closing commands.
Comment: You reiterated my problem, so I modified my original question to better explain the problem I am having. I hope this clarifies it! Thanks anyway!
Answer: define command
\newcommnad{eqn}{1}{\begin{equation}#1\end{equation}}

will change
\eqn{x^2=y}

to
\begin{equation}
  x^2=y
\end{equation}

I think
Comment: Doesn't solve the question at all

wrap LaTeX command in environment


Introduction to groups - question/proof check

Question: Prove if the following are abelian groups, if so, list the neutral element e:
(a) $G:= \Bbb Z, a*b:= max \{a,b\}$ (Z as in positive integers incl. zero (i dont know how to write it with mathjax))
(b) $G:= \Bbb R, a*b:= a^b$ (only positive real numbers)
(c) $G:= \Bbb Z, a*b:= lcm(a,b)$ (least common multiple of a and b) (integers greater than zero)
(d) G is the open interval $(0,1) \subset \Bbb R $ with
$$x*y: = \frac{xy}{1-(x+y)+2y} $$
Hi guys, the university only gave me some definitions, no further explaination whatsoever, im not even sure i understand this correctly (uni is really terrible at teaching)
First, take example a), I assume "$G:= \Bbb Z, a*b:= max \{a,b\}$ " means a group G with the elements a and b $\subset \Bbb Z $. So i need to use the 4 definitions to prove this to be a abelian group.
EDIT:
2) (b) $G:= \Bbb R, a*b:= a^b$
Associativity: $\forall a,b,c \in G: a\circ(b\circ c) = (a\circ b)\circ c$ For question b would mean $a^{b^c}=a^{b^c}$ which is correct...
Invertibility:$\forall a \in G \exists a' \in G: a' \circ a = e$ Suppose its invertible -> $a'\circ a=e \rightarrow a^{-1^{a}}=e$ However, i do see from my schools paper that $a \circ a^1=e$ should also hold, but then in this case that would be $a^{a^{-1}}$ which is not the same thing, so invertibility also fails?
Identity: $\forall a \in G: e \circ a = a$ Since invetibility fails i cant say much about identity...
Commutativity: $a \circ b = b \circ a$ $\rightarrow a^b=b^a$, unless a=b=1, that is not true either...
If someone has time to look it over and give me some suggestions or point out where is wrong or how to write the proofs more formally id be really thankfull!!!!
Comment: If you think that your university's teaching is hard, one book I would recommend is John E. Gallian Contemporary Abstract Algebra. It is practically written for dummies (like me).
Comment: Are you really sure that an actual mathematics professor used $\mathbb{Z}$ to denote the *positive* integers? I know that notations can vary, but I have never, ever, seen anyone use $\mathbb{Z}$ for anything other than the relative integers.
Comment: @CaptainLama he didnt teach that,,i just dont know how to use latex to write positive integers,,,
Comment: @AyamGorengPedes unfortunetely i wouldnt have the time, they cover this extremely quickly, 2 lectures and move on
Comment: @JerryCohen, the good thing about the book is it's simplicity. An hour with the first chapter about Groups will do wonders. A lot of Abstract Algebra is understanding the basic Axioms first, then merely expanding from there.
Comment: @JerryCohen Ok, then the correct notation is $\mathbb{N}$, as in *natural* numbers (depending on the authors it might include $0$ or not, so it's a good thing to make it clear). The notation $\mathbb{Z}$ (coming from the German word "Zahl" meaning number) refers to relative integers, ie including the negative ones.
Comment: The operation in question (b) is NOT associative. Just look at $(2\wedge 3)\wedge 2$ versus $2\wedge (3\wedge 2)$.
Answer: I think you are confusing the operation (which is often called multiplication for Groups). When we say we multiply 2 elements $a$,$b$ in a group, we mean we do the group operation "$\circ$" for $a$ and $b$. That is, $a \circ b$.
For example, The real numbers form an abelian group $G$, with operation $a \circ b = (a+2)+(b+2)$ (regular addition as a part of the operation)

Associativity: $(a \circ b) \circ c = \left((a+2) + (b+2)\right) \circ c = (a+b+4) \circ c = (a+b+4)+(c+2) = a+b+c+6 = a \circ (b+c+4) = a \circ \left((b+2)+(c+2) \right) = a \circ (b \circ c)$.
Identity: Does there exist an element $e$, such that $a \circ e = a$? Let $a$ be chosen randomly from the elements of $G$, and let $x=-4$. Notice that $a \circ x = (a+2) + (x+2) = (a+2) + (-4+2) = a$. Thus we can deduce that $e=-4$.
Invertibility Does there exist an element $a^{-1}$, such that $a \circ a^{-1} = e$? This is the same as solving $(a+2)+(a^{-1}+2)=-4$, which gives us $a^{-1}=-a-8$. Once more, since we can choose $a$ randomly (or "arbitrarily") from the elements of $G$, that means all elements of $G$ has an inverse!

It can also be shown that our group $\left(G,\circ\right)$ is commutative, however I don't want to put it there, because it is not necessary to form a group. The one thing I want to emphasize is that we are not multiplying (unless the operation is a literal multiplication) anything, but rather using the group operation. In your question, you apply the group operation first, then multiply it again.
If you would like, I can also point out why/why not (a),(b),(c),(d) are groups.
Comment: aha so its similiar to relations
Comment: @JerryCohen for question (a), no matter the order of operation, we can guarantee that by doing $a \circ b \circ c$, the answer is the max(a,b,c). However it is not a group due to another reason! Suppose it has an identity $e$. Let us check it's invertibility. Assume it is invertible, max($a$,$a^{-1}$) = $e$. Then, either $e=a$ or $e=a^{-1}$. If the former, then every element of the group is an identity (wrong! only one identity in a group). If the latter, then $e > a$. But then, max($a$,$e$) = $e$, not $a$! (remember that by definition identity is the element such that $a \circ e=a$
Comment: Thanks a became very clear !  If you have time could you have look at my edits? Thanks
Comment: So question a wouldnt hold as a group? since $a\circ (b \circ c) $is not equal to $(a\circ b)\circ c$.  Because a might be greater than b but there is no way to determine a is greater than c?
Comment: It is not commutative yes, that is enough to show that it is not an Abelian group. And yes, for any element $a \in G$, $e \circ a = a = a \circ e$
Comment: if you have time could you quickly explain what the last question 4d) meant by open interval between 0 and 1? Does that mean x*y is only within 0 andn 1, i mean i could do the all four group axioms but i dont know what that means that the thing. is between 0 and 1....if you could quckly touch on that
Comment: I opened a new post to ask that question and got. really distroyed by people for doing that.,....but i really still have absolutely 0 idea what that means
Comment: The closed interval [0,1] includes all points between 0 and 1 INCLUDING 0 and 1. The open interval (0,1) includes all points between 0 and 1 EXCLUDING 0 and 1.


Increase Number in TextView

Question: I want to implement a plus button into my app that will increase the TextView number by 1 each time the button is pressed.
The problem that I am having is that when I press the button, it displays an integer value, but does not increase when I click the button again. It stays the same.
How can I continue to increase the value each time I press the "+" button.
Here is my ViewHolder code that contains my onClickListener:
public int numItems = 0;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mImageView = itemView.findViewById(R.id.Image);
            mItemName = itemView.findViewById(R.id.itemName);
            mNumberItem = itemView.findViewById(R.id.numberOfItems);

            itemView.findViewById(R.id.plusButton).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int totalItems = (int) Math.ceil(numItems + 1);
                    mNumberItem.setText("Items: " +  totalItems);
                }
            });

            itemView.findViewById(R.id.minusButton).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mNumberItem.setText("Test");
                }
            });
        }
    }

Answer: You need to increment numItems.
mNumberItem.setText("Items: " +  ++numItems);

Increase Number in TextView


Using cssRules.cssText returns RGB value instead of HEX

Question: In my CSS file I have this code:
.class { color: #fff; }

Now I am trying to read the CSS using:
document.stylesheets[0].cssRules.cssText

which returns:
.class { color: rgb(255,255,255); }

instead of the original CSS.
Is there any way to get original, hexadecimal value using document.stylesheets[0].cssRules.cssText without conversion?
Comment: Possible duplicate of [RGB to Hex and Hex to RGB](http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb)
Comment: @ketan: Have you read question correctly? I am not trying to convert the values. Actual values written in css are in hexadecimal. But when I am trying read stylesheets using document.stylessheets[0].cssRules.cssText it is showing rgb values instead of hexadecimal. So somehow values are getting converted automatically which I dont want. I need original hexadecimal value.
Comment: That's the way it works. `cssText` contains a canonical rgb representation of the color no matter how it was specified.
Comment: @torazaburo: we know how it works. But is there any way get original hexadecimal value?
Comment: Not as far I know, without parsing the CSS file yourself. Why do you want to do this?
Answer:
Is there any way to get original, hexadecimal value?

No, not from the browser, which represents the color in normalized RGB form. Yes, if you are willing to use one of several competent CSS parsers out there, which is easier than it sounds. I suggest using rework. It is designed for use in node, but you could also run it from the browser using something like browserify. You throw CSS at it, and it returns an internal representation of its structure called AST, which you can then walk to find things you are interested in.


Creating a list of child taxonomy terms with Views

Question: I have a a taxonomy with 2 levels:

Parent 1

Child 1
Child 2
Child 3

Parent 2

Child 4
Child 5

When I am on <code>/taxonomy/term/parent1</code> I want to display a view of a list of child terms in a block:

Child 1
Child 2
Child 3

I have been through similar questions on this site, some with accepted answers, but it did not help me. Here is my Views settings.

For now, it displays the term name for each node containing the parent or child term, causing a lot of duplicates.

parent 1
parent 1
child 1
child 1
child 2
child 2

I'm using Views 3 and Drupal 7
If someone has a hint to share it would help me a lot :)
Thanks in advance
Comment: Till now what i have tried, its not possible to show child of the current term with view.
Comment: maybe grouping by parent can resolve your problem take [here](http://drupal.stackexchange.com/questions/35524/how-to-create-view-that-display-just-2-level-of-taxonomy-vocabulary) a look
Answer: I may be wrong but I guess you have created a View of type 'content' while your intention is to list 'taxonomy terms' (I understand that Child # are taxonomy terms). The type of a View is indicated by the label within parenthesis, above the top of the admin lightbox. If my assumption is right, you would want to create a new View of type 'taxonomy term'.
Answer: I think you may be looking for the Taxonomy menu module. I don't know if it will show the subtree of the taxonomy when visiting parents, but the module page says that it integrates with Views.
Comment: This module is available for Drupal 8 also.


Using signalr with sveltekit

Question: I'm trying to use signalr with sveltekit. The following line throws an error:
const hubConnection = new HubConnectionBuilder().withUrl("/api/notifications").build();

I'm sure that /api/notifications endpoint works.
The error message is: Cannot resolve '/api/notifications'. The related code is in SignalR's HttpConnection.js module:
_resolveUrl(url) {
    // startsWith is not supported in IE
    if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
        return url;
    }
    if (!Utils_1.Platform.isBrowser) {
        throw new Error(`Cannot resolve '${url}'.`);
    }
    ...
}

As expected if I pass full path of "https://localhost:5000/api/notifications", then the error goes away. But relative path does throw the above error.Then I looked into SignalR's Utils.js:
class Platform {
    // react-native has a window but no document so we should check both
    static get isBrowser() {
        return !Platform.isNode && typeof window === "object" && typeof window.document === "object";
    }
    ...
}

Somehow, isBrowser returns false, resulting in the error.
Can someone help with the issue?
Comment: The following may help: https://github.com/sveltejs/kit/discussions/3365
Answer: The issue was that the module which contained the above code in question was imported in layout.ts, and it was executed in node context. So, I factored out the code to avoid importing it in layout.ts. Yet, importing it in +layout.svelte is okay, because in this case hub connection build will be executed in browser context.

Using signalr with sveltekit