text:
Q: Qt adding drop shadow effect for QLabel using QGraphicsDropShadow I have to apply drop shadow for multiple QLabel in my Application. I used QGraphicsDropShadowEffect and it is working fine, if i am adding it for one QLabel. I tried applying the same Graphics effect for two QLabels.
QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect();
effect->setColor(Qt::white);
effect->setBlurRadius(0);
effect->setXOffset(1);
effect->setYOffset(0);
QLabel* label = new QLabel();
label->setText("QLabel1");
label->setGraphicsEffect(effect);
QLabel* label2 = new QLabel();
label2->setText("QLabel2");
label2->setGraphicsEffect(effect);

In this case,the shadow effect is applied only to label2.
I tried creating two different QGraphicsDropShadowEffect objects and setting the QLabels with that.
QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect();
effect->setColor(Qt::white);
QLabel* label = new QLabel();
label->setText("QLabel1");
label->setGraphicsEffect(effect);
QGraphicsDropShadowEffect* effect1 = new QGraphicsDropShadowEffect();
effect1->setColor(Qt::white);
QLabel* label2 = new QLabel();
label2->setText("QLabel2");
label2->setGraphicsEffect(effect1);

In this case, Application is crashing in QRasterPaintEngine::transformChanged() call.
Any idea on how to fix this issue?
I am using qt 5.3.

A: Was just trying to solve this myself. As much as this solution pains me it's the best I came up with quickly. Use QList to help yourself out here:
// List instances containing labels and drop shadows
QList<QLabel*> label_list_;
QList<QGraphicsDropShadowEffect*> shadow_list_;

// Get all UI labels and apply shadows
label_list_ = this->findChildren<QLabel*>();
foreach(QLabel *lbl, label_list_) {
    shadow_list_.append(new QGraphicsDropShadowEffect);
    shadow_list_.back()->setBlurRadius(10);
    shadow_list_.back()->setOffset(3, 3);
    lbl->setGraphicsEffect(shadow_list_.back());
}

If don't want all UI labels in your list you can add manually with append


text:
Q: Why `Loop` write more than once I try to create a guessed with javascript and this is the code:

But unfortunately the result is repeated more than once :
The result:

abb baa aac cba cbb aba bbb aac acb cba ccc bab caa bab ccc aac ccb
  aba abc bac cbb

This slows down the program,, how disband this problem
Is there a solution?
thank you

A: Since you want to not check the same password twice, generating random guesses is obviously not the right way to go. As klumme mentioned, storing an array of previous guesses would only increase time and space complexity, so that is also out. What you will have to do is use a brute force method, that is, trying every combination of characters until you get the correct answer. Here's how you can implement it:
NOTE: Keep in mind that brute force algorithms are typically pretty inefficient, and if you use the full alphanumeric string that you have in your original code to brute force passwords of more than 3-4 characters, it will take a significant amount of time (especially in a browser). JavaScript, by nature, is not an extremely powerful number crunching language - so this answer is more for the idea of it, than for use in most real-world environments.

function guesser(len) {
  var arr = Array.apply(null, Array(len));
  var propIndex = -1;
  var indexes = arr.reduce(function(total, curr) {
    propIndex++;
    total[propIndex] = 0;
    return total;
  }, {});
  var lastGuess = arr.map(function() {
    return possible[possible.length - 1];
  }).join("");
  var guess = "";
  var found = false;
  while (guess !== lastGuess) {
    guess = "";
    for (var i = 0; i < propIndex; i++) {
      // if on last char, reset to 0 and increment previous index start position
      if (indexes[propIndex - i] >= possible.length) {
        indexes[propIndex - i - 1]++;
        indexes[propIndex - i] = 0;
      }
    }
    for (var i in indexes) {
      guess += possible[indexes[i]];
    }

    document.write(guess + "
");
    if (guess === password) {
      found = true;
      break;
    }
    // increment last char
    indexes[propIndex]++;
  }
  if (found) {
    document.write("You know the secret password. Welcome.");
  } else {
    document.write("Sorry, you do not know the secret password.");
  }
}

var password = 'dcd';
var possible = "abcd";
guesser(password.length);

A: If I understand you correctly, the problem is that the random password function ("makeid") may return the same password several times. This is no surprise, there's no reason for the function to know which passwords have been tried already. You could keep track of already tried passwords and not try one if it has been tried before (as in Kind user's answer), but in this case it probably wouldn't speed up the program.
A better approach would probably be to iterate through the possible passwords systematically instead of randomly. For example, try "aaa" first, then "aab", "aac" "aba" and so on.
Here is something I came up with -- it's probably not very fast. I use an array of indices into the "possible" string until actually trying the password, because I don't wan't to mess around with indexOf() on the way.
const correctPassword = 'abc';
const possible = 'abc';
const maxIndex = possible.length - 1;

function next(previous) {
    var i = previous.length - 1;
    while (previous[i] === maxIndex) {
        previous[i] = 0;
        i--;
        // All passwords have been tried.
        if (i < 0) {
            return [];
        }
    }
    previous[i]++;
    return previous;
}

var current = Array(3).fill(0);
var currentPassword;

while (current.length != 0) {
    currentPassword = current.map(function (i) {
        return possible[i];
    }).join('');
    document.write(currentPassword + '
');
    if (currentPassword === correctPassword) {
        document.write('You know the secret password. Welcome.');
        break;
    }
    current = next(current);
}

A: First of all, store the results inside an array. Secondly, add a following condition: if (arr.indexOf(guess) == -1) - if the guessed number is already in the array - skip it.

function makeid(len) {
  var text = "";
  //var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  var possible = "abc";

  for (var i = 0; i < len; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

var password = 'abc';
var correctGuess = false;
var guess;
var arr = [];

while (!correctGuess) {
  guess = makeid(3);
  if (arr.indexOf(guess) == -1) {
    arr.push(guess)
    if (guess === password) {
      correctGuess = true;
    }
  }
}
console.log(arr);

A: I got interested in this question and decided to use it as an opportunity to learn more about generators. Note: Uses ES6 syntax, so not necessarily compatible with all platforms.
I wouldn't necessarily recommend this over the other approaches already put in place, but it might be a good future reference.
/**
 * Invoke `callback` with every possible combination of `elements` up to length of `length`, until `callback` returns `true`
 * @param elements an array of elements to be passed to `callback`
 * @param length the maximum number of elements to pass to `callback`
 * @param callback a function taking an array of elements, that returns a boolean
 * @returns the first combination of elements for which `callback(combination)` returns `true`. Returns undefined if no combination up to the specified `length` returns `true`.
 */
const combineAndCall = (elements = [], length = 0, callback) => {
  const it = permuteIterator(elements, length);

  for (const el of it) {
    if (callback(el)) {
      return el;
    }
  }
};

/**
 * Returns a generator that returns permutations, with repeated elements, of an array. The maximum length of each permutation is `len`
 * @param arr the array to iterate. The first iteration will always be the empty array.
 *
 * Example:
 * const it = permuteIterator([1,2,3], 2);
 * it.next().value; // []
 * it.next().value; // [1]
 * it.next().value; // [2]
 * it.next().value; // [3]
 * it.next().value; // [1,1]
 * it.next().value; // [1,2]
 * it.next().value; // [1,3]
 * it.next().value; // [2,1]
 * it.next().value; // [2,2]
 * ...
 * it.next().value; // [3,3]
 *
 * @len the maximum length of each permutation
 * @returns a generator that iterates the array
 */
function *permuteIterator(arr, len) {
  let current = [];

  function *helper(current, arr, len) {
    if (current.length >= len) {
      yield current;
    } else {
      for (const el of arr) {
        yield* helper([...current, el], arr, len);
      }
    }
  }

  for (let i = 0; i <= len; i++) {
    yield* helper([], arr, i);
  }
}

/**
 * Validates a password
 * @param elements an array of strings (usually single characters) to combine into a a single string, and compare against the password
 * @returns true if the string resulting from `elements.join("")` exactly equals the real password, false otherwise
 */
const passwordValidator = (elements) => {
  const guess = elements.join("");
  //console.log("validating:", guess);
  return guess === "abc";
};

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//const alphabet = "abc";
const elements = alphabet.split("");
const guessedPassword = combineAndCall(elements, 3, passwordValidator);

if (guessedPassword) {
  console.log(`You know the secret password '${guessedPassword.join("")}'. Welcome.`);
} else {
  console.log("You don't know the secret password. Rejected.");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How would you explain covariance to someone who understands only the mean? ...assuming that I'm able to augment their knowledge about variance in an intuitive fashion ( Understanding "variance" intuitively ) or by saying: It's the average distance of the data values from the 'mean' - and since variance is in square units, we take the square root to keep the units same and that is called standard deviation.
Let's assume this much is articulated and (hopefully) understood by the 'receiver'. Now what is covariance and how would one explain it in simple English without the use of any mathematical terms/formulae? (I.e., intuitive explanation. ;)
Please note: I do know the formulae and the math behind the concept. I want to be able to 'explain' the same in an easy to understand fashion, without including the math; i.e., what does 'covariance' even mean?

A: To elaborate on my comment, I used to teach the covariance as a measure of the (average) co-variation between two variables, say $x$ and $y$.
It is useful to recall the basic formula (simple to explain, no need to talk about mathematical expectancies for an introductory course):
$$
\text{cov}(x,y)=\frac{1}{n}\sum_{i=1}^n(x_i-\bar x)(y_i-\bar y)
$$
so that we clearly see that each observation, $(x_i,y_i)$, might contribute positively or negatively to the covariance, depending on the product of their deviation from the mean of the two variables, $\bar x$ and $\bar y$. Note that I do not speak of magnitude here, but simply of the sign of the contribution of the ith observation.
This is what I've depicted in the following diagrams. Artificial data were generated using a linear model (left, $y = 1.2x + \varepsilon$; right, $y = 0.1x + \varepsilon$, where $\varepsilon$ were drawn from a gaussian distribution with zero mean and $\text{SD}=2$, and $x$ from an uniform distribution on the interval $[0,20]$).

The vertical and horizontal bars represent the mean of $x$ and $y$, respectively. That mean that instead of "looking at individual observations" from the origin $(0,0)$, we can do it from $(\bar x, \bar y)$. This just amounts to a translation on the x- and y-axis. In this new coordinate system, every observation that is located in the upper-right or lower-left quadrant contributes positively to the covariance, whereas observations located in the two other quadrants contribute negatively to it. In the first case (left), the covariance equals 30.11 and the distribution in the four quadrants is given below:
   +  -
+ 30  2
-  0 28

Clearly, when the $x_i$'s are above their mean, so do the corresponding $y_i$'s (wrt. $\bar y$). Eye-balling the shape of the 2D cloud of points, when $x$ values increase $y$ values tend to increase too. (But remember we could also use the fact that there is a clear relationship between the covariance and the slope of the regression line, i.e. $b=\text{Cov}(x,y)/\text{Var}(x)$.)
In the second case (right, same $x_i$), the covariance equals 3.54 and the distribution across quadrants is more "homogeneous" as shown below:
   +  -
+ 18 14
- 12 16

In other words, there is an increased number of case where the $x_i$'s and $y_i$'s do not covary in the same direction wrt. their means.
Note that we could reduce the covariance by scaling either $x$ or $y$. In the left panel, the covariance of $(x/10,y)$ (or $(x,y/10)$) is reduced by a ten fold amount (3.01). Since the units of measurement and the spread of $x$ and $y$ (relative to their means) make it difficult to interpret the value of the covariance in absolute terms, we generally scale both variables by their standard deviations and get the correlation coefficient. This means that in addition to re-centering our $(x,y)$ scatterplot to $(\bar x, \bar y)$ we also scale the x- and y-unit in terms of standard deviation, which leads to a more interpretable measure of the linear covariation between $x$ and $y$.

A: I would simply explain correlation which is pretty intuitive.  I would say "Correlation measures the strength of relationship between two variables X and Y.  Correlation is between -1 and 1 and will be close to 1 in absolute value when the relationship is strong.  Covariance is just the correlation multiplied by the standard deviations of the two variables.  So while correlation is dimensionless, covariance is in the product of the units for variable X and variable Y.

A: Sometimes we can "augment knowledge" with an unusual or different approach.  I would like this reply to be accessible to kindergartners and also have some fun, so everybody get out your crayons!
Given paired $(x,y)$ data, draw their scatterplot.  (The younger students may need a teacher to produce this for them. :-)  Each pair of points $(x_i,y_i)$, $(x_j,y_j)$ in that plot determines a rectangle: it's the smallest rectangle, whose sides are parallel to the axes, containing those points.  Thus the points are either at the upper right and lower left corners (a "positive" relationship) or they are at the upper left and lower right corners (a "negative" relationship).
Draw all possible such rectangles. Color them transparently, making the positive rectangles red (say) and the negative rectangles "anti-red" (blue).  In this fashion, wherever rectangles overlap, their colors are either enhanced when they are the same (blue and blue or red and red) or cancel out when they are different.

(In this illustration of a positive (red) and negative (blue) rectangle, the overlap ought to be white; unfortunately, this software does not have a true "anti-red" color.   The overlap is gray, so it will darken the plot, but on the whole the net amount of red is correct.)
Now we're ready for the explanation of covariance.
The covariance is the net amount of red in the plot (treating blue as negative values).
Here are some examples with 32 binormal points drawn from distributions with the given covariances, ordered from most negative (bluest) to most positive (reddest).

They are drawn on common axes to make them comparable.  The rectangles are lightly outlined to help you see them.  This is an updated (2019) version of the original: it uses software that properly cancels the red and cyan colors in overlapping rectangles.
Let's deduce some properties of covariance.  Understanding of these properties will be accessible to anyone who has actually drawn a few of the rectangles. :-)

*

*Bilinearity. Because the amount of red depends on the size of the plot, covariance is directly proportional to the scale on the x-axis and to the scale on the y-axis.

*Correlation. Covariance increases as the points approximate an upward sloping line and decreases as the points approximate a downward sloping line.  This is because in the former case most of the rectangles are positive and in the latter case, most are negative.

*Relationship to linear associations. Because non-linear associations can create mixtures of positive and negative rectangles, they lead to unpredictable (and not very useful) covariances.  Linear associations can be fully interpreted by means of the preceding two characterizations.

*Sensitivity to outliers. A geometric outlier (one point standing away from the mass) will create many large rectangles in association with all the other points.  It alone can create a net positive or negative amount of red in the overall picture.
Incidentally, this definition of covariance differs from the usual one only by a universal constant of proportionality (independent of the data set size).  The mathematically inclined will have no trouble performing the algebraic demonstration that the formula given here is always twice the usual covariance.

A: I loved @whuber 's answer - before I only had a vague idea in my mind of how covariance could be visualised, but those rectangle plots are genius.
However since the formula for covariance involves the mean, and the OP's original question did state that the 'receiver' does understand the concept of the mean, I thought I would have a crack at adapting @whuber's rectangle plots to compare each data point to the means of x and y, as this more represents what's going on in the covariance formula. I thought it actually ended up looking fairly intuitive:

The blue dot in the middle of each plot is the mean of x (x_mean) and mean of y (y_mean).
The rectangles are comparing the value of x - x_mean and y - y_mean for each data point.
The rectangle is green when either:

*

*both x and y are greater than their respective means

*both x and y are less than their respective means

The rectangle is red when either:

*

*x is greater than x_mean but y is less than y_mean

*x is less than x_mean but y is greater than y_mean

Covariance (and correlation) can be both strongly negative and strongly positive. When the graph is dominated by one colour more than the other, it means that the data mostly follows a consistent pattern.

*

*If the graph has lots more green than red, it means that y generally increases
when x increases.

*If the graph has lots more red than green, it means that y generally decreases when x increases.

*If the graph isn't dominated by one colour or the other, it means that there isn't much of a pattern to how x and y relate to each other.

The actual value of the covariance for two different variables x and y, is basically the sum of all the green area minus all the red area, then divided by the total number of data points - effectively the average greenness-vs-redness of the graph.
How does that sound/look?

A: Variance is the degree by which a random vairable changes with respect to its expected value Owing to the stochastic nature of be underlying process the random variable represents.
Covariance is the degree by which two different random variables change with respect to each other. This could happen when random variables are driven by the same underlying process, or derivatives thereof. Either processes represented by these random variables are affecting each other, or it's the same process but one of the random variables is derived from the other.

A: Covariance is a measure of how much one variable goes up when the other goes up.

A: Two variables that would have a high positive covariance (correlation) would be the number of people in a room, and the number of fingers that are in the room.  (As the number of people increases, we expect the number of fingers to increase as well.)
Something that might have a negative covariance (correlation) would be a person's age, and the number of hair follicles on their head. Or, the number of zits on a person's face (in a certain age group), and how many dates they have in a week.  We expect people with more years to have less hair, and people with more acne to have less dates.. These are negatively correlated.

A: I am answering my own question, but I thought It'd be great for the people coming across this post to check out some of the explanations on this page.
I'm paraphrasing one of the very well articulated answers (by a user'Zhop'). I'm doing so in case if that site shuts down or the page gets taken down when someone eons from now accesses this post ;)

Covariance is a measure of how much two variables change together.
  Compare this to Variance, which is just the range over which one
  measure (or variable) varies.
In studying social patterns, you might hypothesize that wealthier
  people are likely to be more educated, so you'd try to see how closely
  measures of wealth and education stay together.  You would use a
  measure of covariance to determine this.
...
I'm not sure what you mean when you ask how does it apply to
  statistics. It is one measure taught in many stats classes.  Did you
  mean, when should you use it?
You use it when you want to see how much two or more variables change
  in relation to each other.
Think of people on a team.  Look at how they vary in geographic
  location compared to each other.  When the team is playing or
  practicing, the distance between individual members is very small and
  we would say they are in the same location.  And when their location
  changes, it changes for all individuals together (say, travelling on a
  bus to a game). In this situation, we would say they have a high level
  of covariance.  But when they aren't playing, then the covariance rate
  is likely to be pretty low, because they are all going to different
  places at different rates of speed.
So you can predict one team member's location, based on another team
  member's location when they are practicing or playing a game with a
  high degree of accuracy.  The covariance measurement would be close to
  1, I believe.  But when they are not practicing or playing, you would
  have a much smaller chance of predicting one person's location, based
  on a team member's location.   It would be close to zero, probably,
  although not zero, since sometimes team members will be friends, and
  might go places together on their own time.
However, if you randomly selected individuals in the United States,
  and tried to use one of them to predict the other's locations, you'd
  probably find the covariance was zero.  In other words, there is
  absolutely no relation between one randomly selected person's location
  in the US, and another's.

Adding another one (by 'CatofGrey') that helps augment the intuition:

In probability theory and statistics, covariance is the measure of how
  much two random variables vary together (as distinct from variance,
  which measures how much a single variable varies).
If two variables tend to vary together (that is, when one of them is
  above its expected value, then the other variable tends to be above
  its expected value too), then the covariance between the two variables
  will be positive. On the other hand, if one of them is above its
  expected value and the other variable tends to be below its expected
  value, then the covariance between the two variables will be negative.

These two together have made me understand covariance as I've never understood it before! Simply amazing!!

A: I really like Whuber's answer, so I gathered some more resources. Covariance describes both how far the variables are spread out, and the nature of their relationship.
Covariance uses rectangles to describe how far away an observation is from the mean on a scatter graph:

*

*If a rectangle has long sides and a high width or short sides and a short width, it provides evidence that the two variables move together.

*If a rectangle has two sides that are relatively long for that variables, and two sides that are relatively short for the other variable, this observation provides evidence the variables do not move together very well.

*If the rectangle is in the 2nd or 4th quadrant, then when one variable is greater than the mean, the other is less than the mean. An increase in one variable is associated with a decrease in the other.
I found a cool visualization of this at http://sciguides.com/guides/covariance/, It explains what covariance is if you just know the mean. link via the wayback machine

A: Here's another attempt to explain covariance with a picture.  Every panel in the picture below contains 50 points simulated from a bivariate distribution with correlation between x & y of 0.8 and variances as shown in the row and column labels.  The covariance is shown in the lower-right corner of each panel.

Anyone interested in improving this...here's the R code:
library(mvtnorm)

rowvars <- colvars <- c(10,20,30,40,50)

all <- NULL
for(i in 1:length(colvars)){
  colvar <- colvars[i]
  for(j in 1:length(rowvars)){
    set.seed(303)  # Put seed here to show same data in each panel
    rowvar <- rowvars[j]
    # Simulate 50 points, corr=0.8
    sig <- matrix(c(rowvar, .8*sqrt(rowvar)*sqrt(colvar), .8*sqrt(rowvar)*sqrt(colvar), colvar), nrow=2)
    yy <- rmvnorm(50, mean=c(0,0), sig)
    dati <- data.frame(i=i, j=j, colvar=colvar, rowvar=rowvar, covar=.8*sqrt(rowvar)*sqrt(colvar), yy)
    all <- rbind(all, dati)
  }
}
names(all) <- c('i','j','colvar','rowvar','covar','x','y')
all <- transform(all, colvar=factor(colvar), rowvar=factor(rowvar))
library(latticeExtra)
useOuterStrips(xyplot(y~x|colvar*rowvar, all, cov=all$covar,
                      panel=function(x,y,subscripts, cov,...){
                        panel.xyplot(x,y,...)
                        print(cor(x,y))
                        ltext(14,-12, round(cov[subscripts][1],0))
                      }))


text:
Q: Update overlay live Twitch by sending data from webapp So I'm developping a spring boot web app and what I'm trying to achieve is when I push a button from the app, an overlay appears on my twitch stream
(i.e : I have a list of words stored on db and when I push the button they are showed on my stream)
It's my first experience with Twitch dev and I'm quite lost. I dont even know if its possible. It's a big project that I have to finish in 2 months so I'm taking any help, any informations !
Thanks
(Sorry for my english I'm not native speaker)


text:
Q: Unix; command line to remove all lines containing substring from file I would like to remove all lines containing a ' MCA: ' substring from /var/log/messages using a command line statement.
I tried sed but can not get it to work;
sed -i '/ MCA: /' /var/log/messages
#results in;
#sed: 1 "/ MCA: /": command expected
does anyone know how to do this? does not have to be sed

A: You are looking to delete entries and so need to add /d.
sed '/MCA\:/d' /var/log/messages

This will output the modified file to screen
Once you are happy, run:
sed -i '/MCA\:/d' /var/log/messages

To commit the changes to the file.


text:
Q: Preview and open-with I see that the file created with Realtime playground at my Google drive supports Open With functionality. Despite preview is not available, I can click it and playground app reopens. How do I do the same with my app. I have created a demo one, to add/remove list items and it creates the files in my google drive, similarly to the google realtime playground functionality. The open with is also available.
Google app files with my app it created. But, clicking it, results in

Sorry, we were unable to authorize this app for all of the files you
  attempted to open. Please try again.

 Is it because I basically have a bad karma or there is objective reason that I miss?

The first answer suggests that I have to do Google Drive API Drive UI integration. The doc says particularly, that open-with is provided by Open URL piece. With a great effort, I have added the verified Open URL in the integration settings, but this has no effect. I am still getting the same Unable to authorize this app error.

A: Make sure that you have enabled the Drive SDK service.
The error Sorry, we were unable to authorize this app for all of the files you attempted to open. Please try again. means that you need to authorize the user. Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.
All applications follow a basic pattern when accessing a Google API using OAuth 2.0. At a high level, you follow four steps:

*

*Obtain OAuth 2.0 credentials from the Google API Console.

*Obtain an access token from the Google Authorization Server.

*Send the access token to an API.

*Refresh the access token, if necessary.

Note: Save refresh tokens in secure long-term storage and continue to use them as long as they remain valid. Limits apply to the number of refresh tokens that are issued per client-user combination, and per user across all clients, and these limits are different. If your application requests enough refresh tokens to go over one of the limits, older refresh tokens stop working.


text:
Q: Javascript disabled for checkout Can a customer avoid sales tax during checkout if they turn off javascript in their browser? Does the State dropdown get validated?
Is there a built in solution?

A: A user can't complete their checkout if they don't have javascript enabled, so there's no risk in having them avoid sales tax or skipping entering a state.


text:
Q: It is necessary to make checks in the function of adding an edge to the graph I need to check that:
1) I do not insert an existing edge
that is, if I have 5 vertices in the graph - the indexes from 0 to 4 then I can not add a reverse by the indexes (0, 6) for example
2) Check to avoid inserting the same vertices
but I can not figure out how to do it right
My Code:
bool Graph::addEdge(const Edge& edge)
{
   if (edge.mStartIndex == edge.mEndIndex)
      return false;

  //if (mVertexList[edge.mEndIndex] != edge.mStartIndex)
    {
     mVertexList[edge.mStartIndex].emplace_back(edge.mEndIndex, edge.mWeight);
     mVertexList[edge.mEndIndex].emplace_back(edge.mStartIndex, edge.mWeight);
    }

    return true;
}

Edge:
struct Edge
{
  Edge(VertexIndex startIndex, VertexIndex endIndex, float weight);

  VertexIndex mStartIndex;
  VertexIndex mEndIndex;
  float mWeight;
};

 struct AdjacentVertex
{
    AdjacentVertex(VertexIndex index, float weight);

    VertexIndex mIndex;
    float mWeight;
};

class Graph
{
public:
   using AdjacencyList = std::vector<AdjacentVertex>;
   Graph(VertexIndex numVertices);

   VertexIndex numVertices() const;
   const AdjacencyList& adjacencyList(VertexIndex index) const;

   bool addEdge(const Edge& edge);
   void removeEdge(const Edge& edge);

   private:
     using VertexList = std::vector<AdjacencyList>;
     VertexList mVertexList;
};

A: *

*To check if an edge number is not too high you can do the following:
if (edge.mStartIndex >= numVertices() || edge.mEndIndex >= numVertices())
{
    // Handle situation when edge number is out of bound
}

*You can check if as adjacency list already contains this edge by using find_if:
auto it = std::find_if(
    mVertexList[edge.mStartIndex].cbegin(),
    mVertexList[edge.mStartIndex].cend(),
    [&edge](const AdjacentVertex& node) {
        /* Check if the current edge points to edge.mEndIndex */
        return node.mEnd == edge.mEndIndex;
    }
);
if (it != mVertexList[edge.mStartIndex].cend()) {
    // Handle situation when you already have this edge in the list
}


text:
Q: Run a build step on a specific branch only I have a build configuration containing two build steps "Build" and "Deploy".
This build configuration is using a Git VCS and is configured to run all branches.
Let's assume that I currently have two branches "master" and "Feature in Development".
I want to divide the "Deploy" step into two. "Deploy Production" and "Deploy Beta".
The "Deploy Production" step should only be executed when the master branch was changed and is currently building.
Is there a built in possibility to do that or do I have to check the %teamcity.build.branch.is_default% variable manually within the script?

A: It seems that JetBrains added this feature in TeamCity v9.1.
For v9.0 I used a Powershell script and checked '%teamcity.build.branch.is_default%' -eq 'true' build property.

A: You can add a condition to a build step in TC using the dropdown:

A: Why not create a two build configuration for that, one checking code from master, second from branch? IMHO it should not be steps in the same build as they are not chained.


text:
Q: How to get the name of a Thread in a Fixed Thread Pool I am trying to display the name of the running threads in the run method. These threads are created in a fixed thread pool:
ExecutorService e = Executors.newFixedThreadPool(size);
The Java API doesn't help me, how can I do this?
Also, it'd be great to know how to customize the name of those threads in the pool.

A: Here's sample which answers both your questions:
    ExecutorService es = Executors.newFixedThreadPool(4, new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "MyThread-" + counter.getAndIncrement());
        }
    });
    es.submit(new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    });

ThreadFactory is to the rescue! Note that threads aren't required to have unique names.


text:
Q: PHP T-variable in HTML form The following code is throwing a T-variable exception in line 10
 //Two Email Lines
$email_to = "contact@website.com";
$email_subject = "AUTO: WEB BETA INVITE REQUEST";

//Set equal to email form textbox
$email_form = $_POST["email_text"];

$email_message = "Email: "$email_form"";

//Create email headers
$headers = 'From: '.$email_form."\r\n".
@mail($email_to, $email_subject,$email_message,$headers);

When I change the = "Email: "$email_form""; to single quotes around the variables $email_form, it runs and throws no exception. However, it sends an email that says "Email: ''", as in, it reads the $email_form variable as blank, which it was not.
The HTML code for the form is below.
<form method="post" action="Email_Form_Script.php" enctype="text/plain" onsubmit="window.open('FormPopUp.html','popup','width=500,height=500,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0');" >

<input type="text" class="text" name="email_text" id="emailForm" value="Enter your e-mail address" onfocus="if(this.value=='Enter your e-mail address') { this.value = '' }" onblur="if(this.value=='') { this.value = 'Enter your e-mail address' }" /><input type="hidden" value="" name="email2"/><input type="hidden" name="loc" value="en_US"/><input type="submit" class="submit" value=""
            />
</form>

Thanks for the help

A: Change:
$email_message = "Email: "$email_form"";

to:
$email_message = "Email: " . $email_form . "";

You forgot to concatenate.

A: Change
$email_message = "Email: "$email_form"";
to
$email_message = "Email: " . $email_form . "";
Also it looks like you're missing a semicolon:
//Create email headers
$headers = 'From: '.$email_form."\r\n". <---


text:
Q: Add a script in  on only one specific page (React) I'm a beginner working with an existing React/Node/Express site.
On one specific page I would like add a script in the head of that page. How can I do this?
I understand that the node module React-helmet can achieve this. But since it's something I only need once, I rather do this without an extra dependency.
Is there some way to do this? For example, in the file where you manage routes or perhaps in index.html where the head is set?

A: You could look into dynamic imports in React
Basically, you can use import() to add the dependency in the page / rendered component that you are using and it will be loaded dynamically when you are on the page.

When Webpack comes across the import().then syntax, it automatically starts code-splitting your app. If you're using Create React App, this is already configured for you and you can start using it immediately.


text:
Q: Trouble embedding faster, responsive YouTube videos with Javascript I'm trying to embed YouTube videos with faster load time, and at the same time-- responsive images. The trouble is is making both the image thumbnail and the iframe (once clicked) both responsive.
I can make the responsive embeds, and I can make the faster embeds with Javascript, separately.
In Javascript, I've replaced the video iframe with a thumbnail. Once the thumbnail is clicked, it loads the video ID. However, this iframe results back to a small width and height.
Does anyone know how to combine the two methods properly?
Here is the HTML:

`</div>`

Here is the CSS:
body {
text-align: center;
background-color: #1D1F20;
color: white;
}

a, a:visited {
  color: white;
}

.embed-container {
            position: relative;
            padding-bottom: 56.25%;
            height: 0; overflow:
            hidden; max-width: 90%;
        }
.embed-container > .youtube {
            position: absolute;
            width: 50%;
            height: 50%;
        }
.youtube {
    background-position: center;
    background-repeat: no-repeat;
    position: relative;
    display: block;
    overflow: hidden;
    transition: all 200ms ease-out;
    cursor: pointer;
    margin: 40px auto 0 auto;
}

iframe {
  margin: 40px auto 0 auto;
}

.youtube .play {
    background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAERklEQVR4nOWbTWhcVRTHb1IJVoxGtNCNdal2JYJReC6GWuO83PM/59yUS3FRFARdFlwYP1CfiojQWt36sRCUurRIdVFXIn41lAoVdRGrG1M01YpKrWjiYmaSl8ybZJL3cd+YA//NLObd3++eO8x79z5jSq5Gw+8kov0AP8vMR5l1BtBZQM4B8ks75wCdZdYZZj5qLZ4hov2Nht9Z9vhKKSIaB/gI4M4w62KeAO6Mte4lYOq20FxrlqqOibhHmeWbvNC9ZfDX1mLae391aN6limO/gwgvAPJbWeAZuSDingdwXTBw7/0IsyaA/Fkh+KqOkD+YNfHej1QKD+y7iVlOhgLvFqFfNJvNGyuBJ+KDAF8MDd0tgS8y64OlgSdJMsysL4cG7SOHkyQZLhTee7+d2R2rAVy/S+Jd7/32ouBHAP4gNNRGQyTHc/84NhqNywZp5rvjjnnvt21aABFeCQ+RLwAf2hQ8s7sv9OCLk6AHNgQvIrvbfzKCD76g/O6cu7lf/iER/aQGgy448pExZmhdegAPhR9sObFWH1gT3lp7DaA/5bkIgJhZPgsNmz02novj+KqeApj1ubwXWe4kdyeznAgNvTpE/HQmvKqOMeuFogTUVQSRno+iaLRLAJF7uIgL9O4ubgL8aWgB7S44mNX+35YpICUiAvS9sBLkq1WzT+NFffl6AuoiApi6NT37h6sWkBIRZGkQ8YtLgyji6e1mBYTqCEBPG2Naz+0BWQgtoGoRgCzEsd9hAN1X5BfnFZASUfrSAFQNsyZ1FJASUVpHiLinDJG8U2cBZYogkrcNs5waBAGdstbeU9zdqpw0gPwwSAI6VUxHyFlDpOcHUUBBIuYNs14aZAE5RVwyzPr3/0EAEY0TyfGNjBWQvwZ+CTSbehfAH29mrID8bET0+0EUkAd8WYDOmqJ3ecsG30yr9wqRfm6Y+a1BEFDEjHfHvWmY9ck6CygHvBVr8Xhtb4ZE5HZA3y8DvBNA1TjnrmXWf+sioMwZX5V/VHXMGGMMoKdDCxCRvRWBdzKzdHEO+EisilbPyopHYqp6S9UCAsz4iojI7hUDAtyXVQgIDd6KnOoaWNkbI6FaPSuZGyMArsi7MZoloB4zviI/Nhr3X95jltwTRQmoIfgisy5ai+me67OI7fE4nrqjrqfK1t0eby0FPRB6oGVlchL3rgnfrq19RKbVBdhV9IOSwJmfmJi4vi/4ThERitwyCxVAFqydshuCX5awhQ9KtmuIWd8IDZED/nXT77rvVVv6sHRKwjYi91poqP7Dr+Y6JJ1VSZIMA3wkPNy6bX+o8Bcm0sXMdwM8Fxo0A3xORPaWBp6uPXsmbxCRD0NDL0dOANhVCXy6iAjMcjbcrMt3RITKwdMVRdFo+y5yvkL4eWZ+zHt/ZVD4dEVRNGotpst+dZZZH8k86lqn2pIvT/eqrNfn2xuyqYPZ8mv7s8pfn/8Pybm4TIjanscAAAAASUVORK5CYII=") no-repeat center center;
    background-size: 64px 64px;
    position: absolute;
    height: 100%;
    width: 100%;
    opacity: .8;
    filter: alpha(opacity=80);
    -webkit-transition: all 0.2s ease-out;
    -moz-transition: all 0.2s ease-out;
    -o-transition: all 0.2s ease-out;
    transition: all 0.2s ease-out;
    color: white!important;
}

.youtube .play:hover {
    opacity: 1;
    filter: alpha(opacity=100);
}

.p {
  margin-top: 60px;
}

And the JS:
"use strict";

function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
r(function(){
    if(!document.getElementsByClassName) {
        // IE8 support
        var getElementsByClassName = function(node, classname) {
            var a = [];
            var re = new RegExp('(^| )'+classname+'( |$)');
            var els = node.getElementsByTagName("*");
            for(var i=0,j=els.length; i<j; i++)
                if(re.test(els[i].className))a.push(els[i]);
            return a;
        }
    var videos = getElementsByClassName(document.body,"youtube");
}
else {
    var videos = document.getElementsByClassName("youtube");
}

var nb_videos = videos.length;
for (var i=0; i<nb_videos; i++) {
    // Based on the YouTube ID, we can easily find the thumbnail image
    videos[i].style.backgroundImage = 'url(http://i.ytimg.com/vi/' + videos[i].id + '/sddefault.jpg)';

    // Overlay the Play icon to make it look like a video player
    var play = document.createElement("div");
    play.setAttribute("class","play");
    play.style.color = "white";
    videos[i].appendChild(play);

    videos[i].onclick = function() {
        // Create an iFrame with autoplay set to true
        var iframe = document.createElement("iframe");
        var iframe_url = "https://www.youtube.com/embed/" + this.id + "?autoplay=1&autohide=1";
        if (this.getAttribute("data-params")) iframe_url+='&'+this.getAttribute("data-params");
        iframe.setAttribute("src",iframe_url);
        iframe.setAttribute("frameborder",'0');
        iframe.setAttribute("allowfullscreen", "true")
        // The height and width of the iFrame should be the same as parent
        iframe.style.width  = this.style.width;
        iframe.style.height = this.style.height;

        // Replace the YouTube thumbnail with YouTube Player
        this.parentNode.replaceChild(iframe, this);
    }
    }
});


text:
Q: Entity Framework codefirst 1 to many relations using the codefirst approach, I would like to have a CODE_YESNO table where it will have two columns C_CODE(1) and C_DESC(5) both type of string.
then I would like to reference it to my other tables.
for example lets say I have I have USERS and PRODUCTS table
and for USERS table I will have userIsActive (foreign key C_CODE)
and for PRODUCTS table I will have productIsOnDiscount (foreign key C_CODE)
I don't want to add or do any modifications on the CODE_YESNO table
so how do I do that with the code first approach?

A: Personally, I would use a boolean if it is just Yes/No. But more generally you can implement lookup tables easily.
public class YesNo
{
    [Key]
    public string C_CODE { get; set; }
    public string C_DESC { get; set; }
}

Then your classes reference through navigation properties:
public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    public string UserIsActiveCode { get; set; }
    [ForeignKey("UserIsActiveCode")]
    public YesNo UserIsActive { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }

    public string ProductIsOnDiscountCode { get; set; }
    [ForeignKey("ProductIsOnDiscountCode")]
    public YesNo ProductIsOnDiscount { get; set; }
}


text:
Q: Is there a way to regenerate the target directory in leiningen? My target directory has been rmed in Linux - does Leiningen offer a way to regenerate it?

A: Just running lein run should cause your project rebuild, thereby recreating the target directory.


text:
Q: How to send a direct message to all members of a server? I am trying to implement a function that will be sending PM to every member of channel.
How to do that? I have that fragment responsible for sending PM to user, but how to get every user from channel?

A: Theres a built-in function called forEach() in Javascript . With this you can send a DM to all members in your server with DMs open
Here is an example
client.on("message", message => {
        if (message.content === "!dmall")
            message.guild.members.cache.forEach(member => {
                member.send(`Hello`).catch(e => console.error(`Couldn't DM member ${member.user.tag}`))
            })


text: Q: Writev does not use MMAP for certain files? I have been reading about writev efficiency and came across a very interesting statement. I read that for certain files sizes, very small sizes(less than 16k) mmap is not executed when using writev. Is this allegation true? I have been searching for any mmap limits but haven't been able to find anything? For example if the file size is "X" then it will not execute, or anything similar to that. Any help is greatly appreciated.


text:
Q: While loop: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() I've been reading about Pandas and trying to write some simple snippets. I've seen many people asking about the ValueError raised by Pandas but can't figure out how to accomplish the following: I have a simple dataframe:
Driver_Name Month/Year  Km_driven   Salaray
0   Ivaylo_Ivanov   Jan/21  2168    3208.64
1   Ivaylo_Ivanov   Feb/21  2350    3478.00
2   Ivaylo_Ivanov   Mar/21  3126    4626.48
3   Ivaylo_Ivanov   Apr/21  2415    3574.20
4   Ivaylo_Ivanov   May/21  2115    3130.20
5   Mihail Styanov  Jan/21  2678    3963.44
6   Mihail Styanov  Feb/21  3185    4713.80
7   Mihail Styanov  Mar/21  3280    4854.40
8   Mihail Styanov  Apr/21  3012    4457.76
9   Mihail Styanov  May/21  2980    4410.40
10  Petar_Petkov    Jan/21  2013    2979.24
11  Petar_Petkov    Feb/21  2089    3091.72
12  Petar_Petkov    Mar/21  2163    3201.24
13  Petar_Petkov    Apr/21  2098    3105.04
14  Petar_Petkov    May/21  2179    3224.92
15  Ivan_Ivanov Jan/21  2876    4256.48
16  Ivan_Ivanov Feb/21  2900    4292.00
17  Ivan_Ivanov Mar/21  2987    4420.76
18  Ivan_Ivanov Apr/21  3016    4463.68
19  Ivan_Ivanov May/21  2019    2988.12

I would like to have a while loop as follows:
while df['Driver_Name']=='Ivaylo_Ivanov':
        do something

I know that df['Driver_Name']=='Ivaylo_Ivanov' returns a boolean series, but why can't the while statement iterate over the boolean?

A: The while keyword expects a bool expression, not an array (series) of them. If you want to iterate over such series until you find a False, you could easily accomplish that with a simple for loop, or, as the Backtrace message suggests, using the member functions all, any, etc.

A: You can do the following if you like to iterate through all rows:
for index, row in df.loc[df['Driver_Name'] == 'Ivaylo_Ivanov'].iterrows():
       do something

You are locating every row, where the condition is true and itarate through the rows.
You should'n use loops, if you have a large dataframe, thera are a many other ways.
Cheers!


text:
Q: Is Swift 3.2 production ready? Apple recently released Xcode 9, which ships with a Swift 3.2/4 compiler. Swift 3.2 includes numerous features (such as support for where constraints on associated types), while still being a member of the Swift 3 family. So, my question is:
Is Swift 3.2 production ready? Can I write and deploy apps to the App Store using Xcode 9 beta?

A: You currently cannot deploy to the App Store, it will take some time and upcoming Xcode betas until that's possible. In the last years we didn't need the GM to upload to the App Store, but the first Xcode Betas didn't let you do that.


text:
Q: Is there  equivalent I updated Swashbuckle v5 and operation.Parameters() is not valid anymore.Is there any replacement?
        {
            var apiDescription = context.ApiDescription;

            operation.Deprecated |= apiDescription.IsDeprecated();

            if (operation.Parameters == null)
            {
                return;
            }

            // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412
            // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413
            foreach (var parameter in operation.Parameters<NonBodyParameter>())
            {

                var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);

                if (parameter.Description == null)
                {
                    parameter.Description = description.ModelMetadata?.Description;
                }

                if (parameter.Default == null)
                {
                    parameter.Default = description.DefaultValue;
                }

                parameter.Required |= description.IsRequired;
            }
        }

Error   CS0307  The property 'OpenApiOperation.Parameters' cannot be used with type arguments

A: From Swashbuckle.AspNetCore GitHub site

In OpenAPI v3, body parameters are split out into a separate property
  called RequestBody. So, I think you may be able to remove OfType
  filter entirely as all values in the collection are "non-body"

I think you should be able to use OpenApiParameter.


text:
Q: Increase the intensity of heatmap points in Google Maps I'm using the Google Map v3 API to create a map showing markers and also a heat map. However when I switch over to the heat map mode the intensity of the discrete points is often too low for them to show up on the map. E.g:

What is the best way to increase the intensity of each point so they they individually show up more like the groups of points above the 'Budapest' label?
Here is my heapmap code:
var latLongArray = new google.maps.MVCArray(latLongPoints);
var heatmap = new google.maps.visualization.HeatmapLayer({
  data: latLongArray,
  map: map,
  radius: 20
});

Thanks in advance!

A: Did you try using opacity: 1 and set heatmap on the map object in the following line. Ex:
var heatmap = new google.maps.visualization.HeatmapLayer({
              data: heatMapData,
              radius: 20,
              opacity: 1
              });

heatmap.setMap(map);


text:
Q: STL container class: array I am just exploring the STL containers in C++. Have some questions...
There are two member functions max_size() and size(). They seem to be doing the same thing. I initially thought max_size() is the actual size of the array and size() is the number of elements explicitly stored. But as I tested it out, it's not the case. Then why two different functions?
Is there any place where I can read the design specs of containers like in Java(not the functional description)? I seem to have many questions such as why the std::array size is fixed but can't be changed dynamically like std::vector etc. Obviously there has to one reason or another for such design decisions. It would be useful to read such design specs to understand such limitations. I have one old "Effective STL" which doesn't include std::array. I believe Scott meyers is yet to include std::array in it.

A: As specified in the standard, max_size() is the maximum number of elements that the container can possibly store:

distance(begin(), end()) for the largest possible container

(C++11, [container.requirements.general], table 96)
For array, which is a fixed-size container, it coincides with size(), while it is completely different for dynamic containers, like std::vector (where it will return something like the size of the virtual address space divided by the size of the element).
You can find all the specifications of the containers in the C++ standard (which is quite expensive, but its drafts are freely available online), although it's just a normative specification which tends not to explain well the rationale behind some decisions (and is deliberately vague on the implementation of the containers).
Still, for the difference between std::array and std::vector, it's because std::array is intended to store the elements without resorting to the heap, providing a same-performance alternative to a local C-style array, while std::vector uses the heap to store the elements, which allows much more flexibility but comes at a cost. See this answer of mine for a more detailed comparison between std::array and std::vector.

A: The max_size method of std::array only exists to make it look like the other STL containers. By having a common interface with other containers, much of the same code can be used for arrays, vectors and lists.
Of course, since the size of an array<T, N> is part of the type, the size and max_size must both return the same value, N.

A: Re: I initially thought max_size() is the actual size of the array and size() is the number of elements explicitly stored.
I think u confused vector::capacity() with max_size().
And in my computer(32-bit),for int type max_size=1073741823,for double type max_size=536870911.which means 4G=2^32=1073741823*sizeof(int)=536870911*sizeof(double)。
So, max_size=the max size u can used in ur computer(useless!just for compatible):)
Re: Is there any place where I can read the design specs of containers like in Java(not the functional description)?
Maybe >The Annotated STL Sources< is not best for u,but it's a good book for STL.


text:
Q: Counting anonymous and logged in users - ASP.NET website I would like to implement reliable user counter. Currently I'm using session variables. Here is a look on my implementation:
void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    Application["OnlineUsers"] = 0;
    Application["LoggedInUsers"] = 0;
}

void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
    Application.UnLock();
}

void Session_End(object sender, EventArgs e)
{
    Application.Lock();
    if ((int)Application["OnlineUsers"] > 0)
    {
        Application["OnlineUsers"] = (int) Application["OnlineUsers"] - 1;
    }
    Application.UnLock();
}

protected void Login1_LoggedIn(object sender, EventArgs e)
{
    Application.Lock();
    Application["LoggedInUsers"] = (int)Application["LoggedInUsers"] + 1;
    Application.UnLock();
}

protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
    Application.Lock();
    if ((int)Application["LoggedInUsers"] > 0)
    {
        Application["LoggedInUsers"] = (int) Application["LoggedInUsers"] - 1;
    }
    Application.UnLock();
}

Downsides of that approach are well known. I couldn't find anything more accurate. Can you help me, please?

A: Given the somewhat fuzzy nature of Session_End, the approach I've used is to just define an "Online User" as someone who has had activity within the last 5 minutes.  You can then just count the number of users who have activity within that time frame.


text:
Q: Multi Direction Bullets[read] Been trying to code something for a while for a project im still working on for school, even though it's done.
I want to make a grenade that shoots out bullets on enemies colliding with it, but what I need help with atm is making 8 bullets shoots in all different directions at once.
here's the code my teacher gave me to do it(I asked him for help)
if (mouse.LeftButton == ButtonState.Pressed)
            {
                Texture2D pewTexture;
                pewTexture = game.Content.Load<Texture2D>("pew");
                game.firingSound.Play();
                //Tweak pews to shoot at mouse, rather than just going straight on the y axis.
                pew = new CPew(game, pewTexture);
                pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;
                pew.position = position + pew.velocity * 5;

                //easy cheesy way:
                //pew.position = position;
                //pew.position.X += 15f;
                //pew.position.Y -= 20f;

                //super awesome cool way for cool people and celebrities
                pew.position = position +
                    new Vector2(
                        texture.Width * .2f - pew.texture.Width * .2f,
                        -pew.texture.Height);

                game.pews.Add(pew);

                myFiringDelay = 10;

            }
            else
            {
                if (mouse.RightButton == ButtonState.Pressed)
                {
                    float pi2 = (float)Math.PI * 2.0f;
                    int numShots = 10;
                    float pi2overnum = pi2 / numShots;

                    for (int i = 0; i < numShots; i++)
                    {
                        Vector2 direction = PiToVec2(pi2overnum * i);

                        //particles[i].reset(position,direction, vector2.zero, 6);
                        game.pews[i].Reset(pew.position, direction, Vector2.Zero);

                    }

           Vector2 PiToVec2(float piT)
           {
              return new Vector2((float)Math.Sin(piT), (float)Math.Cos(piT));

           }

apparently this will make it shoot in every direction on mouse right click but every time I try it and my game crashes straight up
Then we have a pew class which is bullets and thats what I want to be shot in those directions at the same time
you guys may not be able to help with the code i've shown you, i've spent a while looking for a way to do this but i can't seem to find anything
A former example and or source code would be really helpful, just at least another way to look at this thanks.
Showingme when it crashed, it tells me index goes out of range or is negative, if you guys could just show me base code for multidirectional bullets id be happy

A: The problem your having is that when you try and loop through your game.pews collection you are trying to call Reset() on the first 10 items in the collection. However there appear to not be 10 pews in there. So when you get to the end and try to access the next one, that's where you get the "Index out of range" error.
For your 8 bullets from a grenade part of the question, I think you want to do something like this.
//Once a grenade has collided with an enemy
float pi2 = (float)Math.PI * 2.0f;
int numShots = 8;
float pi2overnum = pi2 / numShots;

for (int i = 0; i < numShots; i++)
{
   Vector2 direction = PiToVec2(pi2overnum * i);

   pew = new CPew(game, pewTexture);

   pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;

   //Set the position based off of the grenades last position.
   //Set the direction.
   //Set any other attributes needed.

   game.pews.Add(pew);
}

Now you have eight bullets moving in different directions from where the grenade exploded.
To update them and draw them I would recommend using a foreach loop so you don't have to worry about "Index out of range" errors.
foreach CPew pew in game.pews
{
   pew.Update();
}


text:
Q: FirstPersonControls start by looking at an object My camera.lookAt(cube.position); works only if I disable FirstPersonControls. How do I make so that I start my exploration by looking at first at my object ?
Thanks,

A: As of three.js R101, it's possible to use FirstPersonControls.lookAt(). FirstPersonControls.lat and FirstPersonControls.lon have been removed.


text:
Q: different positioned columns css There are some plugins to make pintrest style columns that are basically calculating where to place the divs with unique absolute positioning for every element. My design is more simple and I would think there should be a css3 solution...
Can you make every other column pushed down like 20px? The design is responsive so depending on browser size will depend on how many columns there are so I would not just want to wrap every column in a div and move it down...
http://jsfiddle.net/3eVHU/1/
$('.container div').each(function() {
        if($(this).prev().length > 0) {
            if($(this).position().top != $(this).prev().position().top) return false;
            listInRow++;
        }
        else {
            listInRow++;
        }
    });

so somehow in my fiddle I would need a way to calculate the number of divs in the first row only and position every other element / row downward just a bit just like in this pic below

Is there any way to do this simply or would I still need to use something like masonry or another pintrest style reproducing library?

A: http://css-tricks.com/seamless-responsive-photo-grid/
BOOYA! Cant say how excited I was to find this. My calculation script wont work to find the number of elements on the first row which I need but it all works without any JS to at least position the elements!


text:
Q: Have to set border color of edittext android? I have used
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ffffff" />
 </shape>

and in my Edittext I set this set as background
android:background="@drawable/rounded_edittext"

I only want to set border color only in order to achieve this, i try to use color in corners but it doesn't allow to compile.
<corners
        android:Color="#00ff00"
        android:radius="0dp" />

A: try this
<?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
   android:shape="rectangle" >
   <solid android:color="#FFFFFF" />
   <stroke
   android:width="2dp"
   android:color="#00ff00" />

</shape>


text:
Q: Get HTML data from webpage after X seconds in Python I'm fetching data from the tesla used inventory, to program a price checker to find prices that fit a user's given budget. However, the Tesla webpage only loads the cars after a certain period of time, and when I use requests to fetch the html data, it doesn't load that. Is there a way to get the HTML data after some period of time, once all of it is loaded? This is the page I'm scraping: https://www.tesla.com/inventory/used/m3 (The url params change based on the user's input, so that's why I'm not including them. When I'm accessing the page, I do include the zip code and other parameters).

A: From the sound of your question you've already got the HTML scraping handled and your really after how you can do the delay before executing the next lines of code.
The simple answer is you can put python to sleep.
import time
time.sleep(5) # equivalent to 5 seconds


text:
Q: How to make my menu stay using scroll function? I have a header, When I scroll down the page, the header is supposed to shrink, and the menu is supposed to remain as it is.
When I scroll down the page, my menu does not stay. How do I make the menu stay?
Here is my jsfiddle:

https://jsfiddle.net/1vfLub67/1/

Home

Room Featured

                    Members

Register

Feedback

Statistics

Deco Ideas

Shopping

Contact Us

Please advise thank you!

A: Add position:fixed;to your header class, and it can let your menu stay in the same position. Hope that helps.

A: To make your menu stay in its position as you scroll, you just need to use css position: fixed
See the demo:
https://jsfiddle.net/1vfLub67/2/
And you should always indent your code like I do in the demo. That way it's a lot easier for people to find the problems and tweak the code.


text:
Q: How to get complete control of ViewVector? I need to rotate a 3D object with the mouse, get the new ViewPoint, and scale that by dist to get a new ViewPoint and use that in ViewVector.
  And do this while preserving the orientation.
  (In the code, I also get the orientation jumping with the size slider. I don't want this either.)
This is extending Matt's solution in this question Changing the Actions in EventHandler.
Manipulate[
 vp = ViewPoint /. Options[Graphics3D, ViewPoint];
 uvp = Normalize[vp];
 vp = dist*uvp;

 Show[
  {
     Graphics3D[{Red, Opacity[0.5],
        Cylinder[size {{0, 0, -1}, {0, 0, 1}}]}],
     Graphics3D[{Black, Opacity[0.5], Sphere[]}],
     Graphics3D[{Black, Sphere[{0, 0, 0}, .2]}]
   },

  PlotRange -> 10 {{-1, +1}, {-1, +1}, {-1, +1}},

  ViewAngle -> Dynamic[vAngle \[Degree]],
  ViewVector -> {Dynamic[vp], Dynamic[Flatten@{center, 0}]}
  ],

 {{vAngle, 30, "Zoom"}, 90, 10, 1},
 {{center, {0, 0}, "Pan"}, 2 {-1, -1}, 2 {1, 1}},
 {{size, 1, "size"}, 0, 5, .1},
 {{dist, 10, "dist"}, 0, 20, .1},

 TrackedSymbols :> {vAngle, center, size, dist},
 ControlPlacement -> Left
 ]


text:
Q: scala version of swap algorithm for null models The problem I am having is with trying to find an efficient way to find swappable elements in a matrix in order to implement a swap algorithm for null model creation.
The matrix consists of 0's and 1's and the idea is that elements can be switched between columns so that the row and column totals of the matrix remain the same.
For example, given the following matrix:
   c1 c2 c3 c4
r1  0  1  0  0 = 1
r2  1  0  0  1 = 2
r3  0  0  0  0 = 0
r4  1  1  1  1 = 4
   ------------
    2  2  1  2

columns c2 and c4 in r1 and r2 can each be swapped in such a way that totals are not altered i.e.:
   c1 c2 c3 c4
r1  0  0  0  1 = 1
r2  1  1  0  0 = 2
r3  0  0  0  0 = 0
r4  1  1  1  1 = 4
   ------------
    2  2  1  2

This all needs to be done randomly so as not to introduce any bias.
I have one solution that works. I randomly select a row and two columns. If they yield a 10 or 01 pattern then I randomly select another row and check the same columns to see if they yield the opposite pattern. If either of them fail I start over and select a new element.
This method works but I only "hit" the correct patterns about 10% of the time. In a large matrix or in one with few 1's in the rows I waste a lot of time "missing". I figured that there had to be a more intelligent way of choosing elements in the matrix but still doing it randomly.
The code for the working method is:
def isSwappable(matrix: Matrix): Tuple2[Tuple2[Int, Int], Tuple2[Int, Int]] = {
  val indices = getRowAndColIndices(matrix)

  (matrix(indices._1._1)(indices._2._1), matrix(indices._1._1)(indices._2._2)) match {
    case (1, 0) => {
      if (matrix(indices._1._2)(indices._2._1) == 0 & matrix(indices._1._2)(indices._2._2) == 1) {
        indices
      }
      else {
        isSwappable(matrix)
      }
    }
    case (0, 1) => {
      if (matrix(indices._1._2)(indices._2._1) == 1 & matrix(indices._1._2)(indices._2._2) == 0) {
        indices
      }
      else {
        isSwappable(matrix)
      }
    }
    case _ => {
      isSwappable(matrix)
    }
  }
}

def getRowAndColIndices(matrix: Matrix): Tuple2[Tuple2[Int, Int], Tuple2[Int, Int]] = {
  (getNextIndex(rnd.nextInt(matrix.size), matrix.size), getNextIndex(rnd.nextInt(matrix(0).size), matrix(0).size))
}

def getNextIndex(i: Int, constraint: Int): Tuple2[Int, Int] = {
  val newIndex = rnd.nextInt(constraint)
  newIndex match {
    case `i` => getNextIndex(i, constraint)
    case _ => (i, newIndex)
  }
}

I figured a more efficient way to handle this was to remove any rows that could not be used (all 1's or 0's) and then choose an element randomly. From there I could filter out any columns in the row that had the same value and the choose from the remaining columns.
Once the first row and column are chosen I then filter out the rows that can not provide the required pattern and then choose from the remaining rows.
This works for the most part but the problem that I can't figure out how to deal with is what happens when there are no columns or rows to choose from? I don't want to loop infinitely trying to find the pattern I need and I need a way of starting over if I do get an empty list of rows or columns to choose from.
The code that I have so far that sort of works (until I get an empty list) is:
def getInformativeRowIndices(matrix: Matrix) = (
  matrix
    .zipWithIndex
    .filter(_._1.distinct.size > 1)
    .map(_._2)
    .toList
  )

def getRowsWithOppositeValueInColumn(col: Int, value: Int, matrix: Matrix) = (
  matrix
    .zipWithIndex
    .filter(_._1(col) != value)
    .map(_._2)
    .toList
  )

def getColsWithOppositeValueInSameRow(row: Int, value: Int, matrix: Matrix) = (
  matrix(row)
    .zipWithIndex
    .filter(_._1 != value)
    .map(_._2)
    .toList
  )

def process(matrix: Matrix): Tuple2[Tuple2[Int, Int], Tuple2[Int, Int]] = {
  val row1Indices = getInformativeRowIndices(matrix)
  if (row1Indices.isEmpty) sys.error("No informative rows")

  val row1 = row1Indices(rnd.nextInt(row1Indices.size))
  val col1 = rnd.nextInt(matrix(0).size)
  val colIndices = getColsWithOppositeValueInSameRow(row1, matrix(row1)(col1), matrix)
  if (colIndices.isEmpty) process(matrix)
  val col2 = colIndices(rnd.nextInt(colIndices.size))
  val row2Indices = getRowsWithOppositeValueInColumn(col1, matrix(row1)(col1), matrix)
    .intersect(getRowsWithOppositeValueInColumn(col2, matrix(row1)(col2), matrix))
  println(row2Indices)
  if (row2Indices.isEmpty) process(matrix)

  val row2 = row2Indices(rnd.nextInt(row2Indices.size))
  ((row1, row2), (col1, col2))
}

I think the recursive methods are wrong and don't really work here. Also, I am really just trying to improve the speed of cell selection so any ideas or suggestions would be greatly appreciated.
EDIT:
I have had a chance to play with this little more and have come up with another solution but it does not seem to be much faster then just randomly choosing cells in the matrix. Also, I should add that the matrix needs to be swapped about 30000 times in succession in order for it to be considered randomised and I need to generate 5000 random matrices for each test of which I have at least another 5000 to do so performance is kind of important.
The current solution (besides random cell selection is:

*

*Randomly select 2 rows from the matrix

*subtract one row from the other and put it in an Array

*if the new Array contains both a 1 and -1 then we can swap

The logic of the subtraction looks like this:
  0  1  0  0
- 1  0  0  1
---------------
 -1  1  0 -1

The method that does this looks like this:
 def findSwaps(matrix: Matrix, iterations: Int): Boolean = {
   var result = false

   val mtxLength = matrix.length

   val row1 = rnd.nextInt(mtxLength)
   val row2 = getNextIndex(row1, mtxLength)

   val difference = subRows(matrix(row1), matrix(row2))

   if (difference.min == -1 & difference.max == 1) {
     val zeroOne = difference.zipWithIndex.filter(_._1 == -1).map(_._2)
     val oneZero = difference.zipWithIndex.filter(_._1 == 1).map(_._2)

     val col1 = zeroOne(rnd.nextInt(zeroOne.length))
     val col2 = oneZero(rnd.nextInt(oneZero.length))

     swap(matrix, row1, row2, col1, col2)
     result = true
   }
   result
 }

The matrix row subtraction looks like this:
 def subRows(a: Array[Int], b: Array[Int]): Array[Int] = (a, b).zipped.map(_ - _)

And the actual swap looks like this:
 def swap(matrix: Matrix, row1: Int, row2: Int, col1: Int, col2: Int) = {

   val temp = (matrix(row1)(col1), matrix(row1)(col2))
   matrix(row1)(col1) = matrix(row2)(col1)
   matrix(row1)(col2) = matrix(row2)(col2)

   matrix(row2)(col1) = temp._1
   matrix(row2)(col2) = temp._2
   matrix
 }

This works much better than before in that I get have between 80% and 90% success for an attempted swap (it was only about 10% with the random cell selection) however... it is still taking about 2.5 minutes to generate 1000 randomised matrices.
Any ideas on how to improve the speed?

A: I'm going to assume the matrices are big so that storage of the order of (matrix size squared) is not viable (for reasons of either speed or memory).
If you have a sparse matrix, you can enter the index of each 1 in each column in a set (here I show the compact way to do things, but you may wish to iterate with while loops for speed):
val mtx = Array(Array(0,1,0,0),Array(1,0,0,1),Array(0,0,0,0),Array(1,1,1,1))
val cols = mtx.transpose.map(x => x.zipWithIndex.filter(_._1==1).map(_._2).toSet)

Now for each column, a later column contains compatible pairs (at least one) if and only if only the following two sets are nonempty:
def xorish(a: Set[Int], b: Set[Int]) = (a--b, b--a)

So the answer will involve computing these sets and testing whether they're both nonempty.
Now the question is what you mean by "sample randomly".  Randomly sampling single 1,0 pairs is not the same as randomly sampling possible swaps.  To see this, consider the following:
1 0       1 0
1 0       1 0
1 0       1 0
0 1       1 0
0 1       1 0
0 1       0 1

The two columns on the left have nine possible swaps.  The two on the right have only five possible swaps.  But if you are looking for (1,0) patterns, you will sample only three times on the left vs. five on the right; if you are looking for either (1,0) or (0,1), you will sample six and six, which again distorts the probabilities.  The only way to fix this is either to not be clever, and randomly sample a second time (which in the first case will work out with a usable swap 3/5 of the time, while only 1/5 in the second), or to basically compute every possible pair for swapping (or at least how many pairs there are) and select from that predefined set.
If we want to do the latter, we note that for each pair of nonidentical columns, we can compute the two sets to swap among, and we know the sizes and the product is the total number of possibilities.  In order to avoid instantiating all the possibilities, we can create
val poss = {
  for (i<-cols.indices; j <- (i+1) until cols.length) yield
    (i, j, (cols(i)--cols(j)).toArray, (cols(j)--cols(i)).toArray)
}.filter{ case (_,_,a,b) => a.length>0 && b.length>0 }

and then count how many there are:
val cuml = poss.map{ case (_,_,a,b) => a.size*b.size }.scanLeft(0)(_ + _).toArray

Now to pick a number at random, we pick a number between 0 and cuml.last and pick out which bucket this is and which item within the bucket:
def pickItem(cuml: Array[Int], poss: Seq[(Int,Int,Array[Int],Array[Int])]) = {
  val n = util.Random.nextInt(cuml.last)
  val k = {
    val i = java.util.Arrays.binarySearch(cuml,n)
    if (i<0) -i-2 else i
  }
  val j = n - cuml(k)
  val bucket = poss(k)
  (
    bucket._1, bucket._2,
    bucket._3(j % bucket._3.size), bucket._4(j / bucket._3.size)
  )
}

This ends up returning (c1,c2,r1,r2) selected randomly.
Now that you have the coordinates, you can create the new matrix however you wish.  (Most efficient is probably to do an in-place swap of the entries, and then swap back when you want to try again.)
Note that this is only sensible for a large number of independent swaps from the same starting matrix.  If you instead want to do this iteratively and maintain independence, you are probably best off doing this randomly after all unless the matrices are extremely sparse, at which point it's worth simply storing the matrices in some standard sparse matrix format (i.e. by index of nonzero entries) and doing your manipulation on those (probably with mutable sets and an update strategy, since the consequences of a single swap are confined to about n of the entries in an n*n matrix).


text:
Q: jQuery links from HTML I have the following code in JQuery to create a footer with links:
;(function($) { $.fn.piepagina = function(options) {
    return this.each(function() {
        var defaults = {images: [
            'About -',
            'Report an issue -',
        'Contribute -',
        'Contact Us -',
        'Terms of Trade - ',
        'Email updates ']};
        var settings = $.extend(defaults, options || {});
    });
};})(jQuery);

I'm calling the function like follows from my HTML:

But I can not see anything on my footer.
What I'm doing wrong?
Thanks much

A: You are not doing anything in your code....
Why don't you just try:
  this.append(
    'About -',
    'Report an issue -',
    'Contribute -',
    'Contact Us -',
    'Terms of Trade - ',
    'Email updates '
  );

I think that is what you wanted to do... but I cannot be sure....
Not sure why you need a plugin for this....

A: Suppose you need to modify your code like this:
(function($) {
    $.fn.piepagina = function (options) {
        return this.each(function () {
            var defaults = {
                images: [
                    'About -',
                    'Report an issue -',
                    'Contribute -',
                    'Contact Us -',
                    'Terms of Trade - ',
                    'Email updates '
                ]
            };
            var settings = $.extend(defaults, options || {});
            for(var i =0; i < settings.images.length; i++) {
                $(this).append(settings.images[i]);
            }
            $(this).data("piepagina", { settings: settings });
        });
    };
})(jQuery);

for loop after var settings = ... line will add all images (links) available in settings.images into selected element.


text:
Q: Google GeoCoding API multiple search results Currently I am using the following URL to get the addresses and coordinates of a search string in my app.
https://maps.googleapis.com/maps/api/geocode/json?address=<Address>&sensor=false

The URL returns multiple results only when the  string is given in a particular format. For example, I am trying to search for a business named "Yashoda Hospital, Hyderabad" and the results give only one address although the same search string gives multiple results in Google Maps website. But when I enter the string with a slight variation ("Yashoda Hospitals, Hyderabad") by adding an 's', it returns two addresses.
Is there a particular URL through which we can get all the possible results? Or what should be the approach to capture all the possible addresses that are returned in Google Maps website?


text:
Q: split dataframe at each repeating point in a column I have a dataframe
df<-data.frame(var1=c(1:11),I_var1=c(11:21),
               var2=c(rep(c(0,0.1),each=5),0.1),var4=c(rep(c(0:4),2),4))

var1 I_var1 var2 var4
  1     11  0.0    0
  2     12  0.0    1
  3     13  0.0    2
  4     14  0.0    3
  5     15  0.0    4
  6     16  0.1    0
  7     17  0.1    1
  8     18  0.1    2
  9     19  0.1    3
 10     20  0.1    4
 11     21  0.1    4

I have to split at each repeating cell of a particular number i.e. where df$var4==4
I tried-
X <- split(df,cut(df$var4,4))

But this is giving wrong result.
What i want is-
2 dataframes (or lists as split gives list) where var4 is between 0 and 4. The second one should have both rows with var4==4.
I do not want to use subset as original dataframe has >10Mil records.
How do I do this and very fast?

A: Simply:
split(df,duplicated(df$var4))

$`FALSE`
  var1 I_var1 var2 var4
1    1     11    0    0
2    2     12    0    1
3    3     13    0    2
4    4     14    0    3
5    5     15    0    4

$`TRUE`
   var1 I_var1 var2 var4
6     6     16  0.1    0
7     7     17  0.1    1
8     8     18  0.1    2
9     9     19  0.1    3
10   10     20  0.1    4
11   11     21  0.1    4

A: This
library(data.table)
library(dplyr)

df<-data.frame(var1=c(1:11),I_var1=c(11:21),
               var2=c(rep(c(0,0.1),each=5),0.1),var4=c(rep(c(0:4),2),4))

cuts <- which(df$var4==0)
cuts <- c(cuts,nrow(df))
df <- as.data.table(df)
df[,nrow:=.I]
intervals <- list()
for(i in 1:(length(cuts)-1)){ # i <- 1
  intervals[[i]] <- seq(cuts[i],cuts[i+1]-1,1)
}
intervals[[i]] <- c(intervals[[i]],max(intervals[[i]])+1)

list <- list()
for(i in 1:length(intervals)){ # i <- 1
  list[[i]] <- df[nrow%in%intervals[[i]],]
}

Gives as output
> list
[[1]]
   var1 I_var1 var2 var4 nrow
1:    1     11    0    0    1
2:    2     12    0    1    2
3:    3     13    0    2    3
4:    4     14    0    3    4
5:    5     15    0    4    5

[[2]]
   var1 I_var1 var2 var4 nrow
1:    6     16  0.1    0    6
2:    7     17  0.1    1    7
3:    8     18  0.1    2    8
4:    9     19  0.1    3    9
5:   10     20  0.1    4   10
6:   11     21  0.1    4   11

UPDATE
Or shorter
library(data.table)
library(dplyr)

df<-data.frame(var1=c(1:11),I_var1=c(11:21),
               var2=c(rep(c(0,0.1),each=5),0.1),var4=c(rep(c(0:4),2),4))

cuts <- which(df$var4==0)
df <- as.data.table(df)
df[,nrow:=.I]
list <- list()
for(i in 1:length(cuts)){ # i <- 2
 if(i==length(cuts)){
   list[[i]] <- df[nrow%in%c(cuts[i]:nrow(df)),]
 }else{
   list[[i]] <- df[nrow%in%c(cuts[i]:(cuts[i+1]-1)),]
 }
}

A: (Not sure, if I fully understood you ..)
df<-data.frame(var1=c(1:11),I_var1=c(11:21),
               var2=c(rep(c(0,0.1),each=5),0.1),var4=c(rep(c(0:4),2),4))

df$lagvar4<-c(0,df$var4[-length(df$var4)])
split(df[!(colnames(df) %in% c("var4","lagvar4"))],cumsum(df$lagvar4==4))

A: Here is a dplyr solution:
df <- data.frame(var1=c(1:11),I_var1=c(11:21),
           var2=c(rep(c(0,0.1),each=5),0.1),var4=c(rep(c(0:4),2),4))

df %>%
  group_by(var4) %>%
  mutate(split = row_number()) %>%
  split(., f = .$split)


text:
Q: Linux Git repository and TortoiseGIT I've browsed the web to find the solution but found many variants none of which solves my problem. I'm just starting to use Git and want to have main repository on Linux server but to work locally on windows. I have created repository in the root of website using git init:
cd /var/www
git init

Then I've successfuly added files to it and committed them. I have the history displayed in logs:
commit eac728dc06731788e6f39e5ed2a819aa7f0fae1e
Author: Max <my_email@gmail.com>
Date:   Sun Jul 21 15:06:56 2013 +0400

Now I want to be able to clone this repository to Windows. I want to use TortoiseGit for that purpose. I've read that I need to create .ssh keys on Linux and copy them to Windows. I've generated them using ssh-keygen -t rsa -C "my_email@example.com" on Linux and copied to C:\Documents and Settings\User on Windows. But the other article says that I have to put them to gitosis-admin/keydir- I don't know where that is. So my first question is

*

*Do I need to copy keys generated on Linux to Windows? If so, what folder should I place them at?
Then when I open TortoiseGit it asks for URL to git repository. I'm accessing root folder with the IP like 77.777.7.77. I tried to specify the IP only as the URL since git repository is created in the root folder but I get the error

fatal: repository '77.777.7.77' does not exist

I've also tried the like this - 77.777.7.77/var/www but to no avail.

*What URL should be specified if repository is created in the root folder?
And I assume that I should also create local repository to commit to. But how do I then get it to remote repository?

*Do I need to create local repository?

A: This qualifies for FAQ. You never create a repository, you clone it.
OK - You need to generate key pair in git bash and copy ~/.ssh/id_rsa.pub from windows to user@linux:.ssh/authorized_keys.
Ideally you could use gitolite.


text:
Q: Issue with Getx 4.6.1 After adding a get:^4.6.1 I got the below error.
Code:
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter web One',
      home: HomePage(),
    );
  }
}

Error:
  const CupertinoApp({

        ^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:275:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/material/app.dart:217:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp.router({

        ^^^^^^^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:322:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,

                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/material/app.dart:166:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp({
        ^^^^^^^^^^^

and also if I try to downgrade getx version 4.6.1 to 4.3.8 still i am getting the same error and in the error, it shows get-4.6.1 version.

A: The above problem is happening in get version >= 4.6.0. Use the exact version below 4.6.0 withing using ^ sign, which upgrades the package to the maximum compatible version.
In pubspec.yaml use get package like below:
get: 4.5.1     #Don't use ^


text:
Q: A function that modifies functions - well-defined operation? Here's my basic setup:
Say I have a list of specific symbols and a function noSymbol, which accepts a mathematica expression and checks whether any symbol from my list is contained in it, for example:
symbols = {basisElement};
noSymbol[x_] := And @@ ( Length[Position[x, #]] === 0 & /@ symbols );

An examle use-case could be that basisElement is a function enumerating basis vectors of some n-dimensional algebra, so that I could define the multiplication of the algebra as
mult[basisElement[i_], basisElement[j_]] := Sum[strucConst[i, j, k] * basisElement[k], {k, 1, n}];

with structConst the structure constants of the algebra.
Of course in this situation it is natural to define linear functions, and what I would often find myself doing is
Clear[f];
f[0] := 0;
f[v_ + w_] := f[v] + f[w];
f[a_ * v_] := a * f[v] /; noSymbol[a];
f[v_ * a_] := a * f[v] /; noSymbol[a];
(* actual function definition *)

at the beginning of every definition of a linear function.
This adds a lot of repetition to my code, so I wanted to ask if using a "linearizing function" like
linearize[f_] := (
    f[0] := 0;
    f[v_ + w_] := f[v] + f[w];
    f[a_ * v_] := a * f[v] /; noSymbol[a];
    f[v_ * a_] := a * f[v] /; noSymbol[a];
);

Clear[f];
linearize[f];
(* actual function definition *)

is considered good practices and makes sense, or if it could lead to any serious issues.
EDIT:
Additionally, if this is good practice, how can I extend my linearize function so that it can "multilinearize"? For example, my multiplication from above would have to be linear in each argument.

A: First, a note regarding noSymbol: You can more easily implement it using FreeQ:
symbols = Alternatives[basisElement];
noSymbol := FreeQ[symbols]

Also, you don't need to define both f[a_ * v_] and f[v_ * a_], since Times is Orderless.
As for the actual question: I don't see any reason why this shouldn't be done, in fact, I've used very similar functions in the past.
Finally, for multi-linearization: You can do something like the following:
linearize[f_] := (
   f[___, 0, ___] := 0;
   f[pre___, v_ + w_, post___] := f[pre, v, post] + f[pre, w, post];
   f[pre___, a_ * v_, post___] := a*f[pre, v, post] /; noSymbol[a];
   );

Clear[f];
linearize[f];

f[a basisElement, c + d]
(* a f[basisElement, c] + a f[basisElement, d] *)

The rules simply apply the linearity properties to any argument, while keeping all the others (if any exist) unmodified


text:
Q: App Attribution not displayed on iOS I am using SSO in my application, and I see my application in Facebook for iPhone "Apps" section, and when tapping on it it launches my app. This is normal and works perfectly. Now, when I use a feed dialog on my App to publish a feed story, I do not see the App Attribution next to the "via APP_NAME" like I should. I also marked my app as "SSO enabled" in the apps settings.

Do you have any idea why it's not showing up the little icon to launch my app on the iOS device?
Thanks a lot

A: After facing the same issue i finally got it to work. You need to make sure that in your facebook app settings you have set the "app namespace" under the "Basic Info" section. After I've set it, it took several minutes to propagate throughout their servers but then it worked for all the stories published by the app.


text:
Q: How to create yum proxy repository with nexus OSS complete example I have some question:
How to write the url of remote repository while creating proxy repository in nexus OSS.What is the value of $releasever and $basearch
- http://path/to/repo/releases/$releasever/server/$basearch/os/

A: There is a nexus alternative and more lightweight, named Repocache.


text:
Q: Adding listener to firebase having List like data I have this structure in Firebase
    "shared_items" : {
    "-KgGHdgE3L_m6ppVgn99" : {
      "_id" : 14,
      "added_date" : "08/Mar/2017",
      "shared_with_emails" : "{\"abc@abc*com\":{\"name\":\"Customer Care\"},\"xyz@xyz*com\":{\"name\":\"Customercare\"}}",
      "user_display_name" : "Logged in user",
      "users_email" : "loggedinUser@gmail.com"
    }
  }

My questions:

*

*When I am saving JSON data in "shared_with_emails" key then my data is automatically appended with "\" slash. Is this normal or I am doing something wrong here?

*How can I get entire node based on email Ids present in this JSON object.

Function to create JSON objects from provided contacts..

public class JsonUtils {
    final private static String TAG = JsonUtils.class.getSimpleName();

    public String ContactsToJson() {
        ArrayList<ContactsModel> listOfContacts = new ArrayList<>();
        listOfContacts.add(new ContactsModel("abc@gmail.com", "abc"));
        listOfContacts.add(new ContactsModel("xyz@gmail.com", "xyz"));
        listOfContacts.add(new ContactsModel("mnop@yahoo.com", "mnop"));

        JSONObject jsonObjectChild;
        JSONObject jsonObjectRoot = new JSONObject();

        for (int i = 0; i < listOfContacts.size(); i++) {
            ContactsModel model = (ContactsModel) listOfContacts.get(i);
            try {
                jsonObjectChild = new JSONObject();
                jsonObjectChild.put("name", model.getContactName());
                jsonObjectRoot.put(model.getContactMail(), jsonObjectChild);
            } catch (JSONException e){
                e.printStackTrace();
            }

        }

        System.out.println(jsonObjectRoot.toString());
        return jsonObjectRoot.toString();
    }

    public class ContactsModel {

        private int id;
        private String mContactName;
        private String mContactMail;

        public ContactsModel(String contactMail, String contactName) {
            this.mContactName = contactName;
            this.mContactMail = contactMail;
        }

        public String getContactName() {
            return mContactName;
        }

        public String getContactMail() {
            return mContactMail;
        }
    }

}

Json data on Firebase

A: You can use ArrayList<String> to have multiple emails saved under shared_with_email. When you retrieve your data, save it inside an object and search whether the object contains the email.
ArrayList<String> keys = new ArrayList<>;

rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(Datasnapshot snap:datasnapshot.getChildren()){
                ArrayList<yourObject> current = snap.getValue();
                if (current.shared_with_email.contains(someEmail)){
                    keys.add = snap.getKey(); //Check this, all we need is the key of our object. kd47qjB.... in this case
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Once you have all the keys. Add listeners.
for(String key: keys){
    rootRef.child(key).addValueEventListener(new ValueEventListener(){
        @override
        public void onDataChange(Datasnapshot datasnapshot){
            //You successfully added listener to the key where user has its email.
            //Do your work here.
        }
    });
}

You will have to create a class yourObject which resembles the data in your firebase database.


text:
Q: How to cancel all unneccesary requests in vuex, axios I have a situation: when I live a page, async functions in mounted hook continue working (such as await this.getUser({id: 1})). I'm trying to use axios.CancelToken, but unfortunately it cancels only the first request (not all requested).
Send request function:
const source = axios.CancelToken.source();
const config = {
    headers: {
        authorization: `${prefix}${localStorage.getItem('authorization')}`
    },
    cancelToken: source.token
};
store.commit('SET_CANCEL_SOURCE', source);

const response = await axios.get(url, config);

Store mutations:
SET_CANCEL_SOURCE: (state, cancel: CancelTokenSource) => {
    state.cancelTokens.push(cancel);
},
RESET_CANCEL_TOKENS: (state) => {
    if (state.cancelTokens.length) {
        state.cancelTokens.map((item: any, index: number) => {
            console.log(index, item);
            item.cancel();
        });
        state.cancelTokens = [];
    }
}

Store action:
clearToken ({commit}) {
    commit('RESET_CANCEL_TOKENS');
}

And beforeUnmount for component:
beforeUnmount() {
    this.clearToken();
}

Any ideas?

A: The point is that CancelToken cancels only those requests that are already sent.
The best solution I found is to make stages of loading information, create a variable, that represents the current stage and in beforeUnmount make variable isCancelled = true. So that next stages will not be excuted. Example:
data: () => ({
    stage: 0,
    isCancelled: false,
}),
async setInitialData() {
    if (this.stage >= 4 || this.isCancelled) {
        return;
    }

    switch (this.stage) {
        case 0:
            await action1();
            break;

        case 1:
            await action2();
            break;

        case 2:
            await action3();
            break;

        case 3:
            await action2();
            break;

        default:
            break;
    }

    this.stage++;
    await this.setInitialData();
},
async mounted() {
    await this.setInitialData();
},
beforeUnmount() {
    this.isCancelled = true;
},