How to implement menu in footer blcok

Question: I need a (D7) block print the main menu in the footer; It's not clear to me how the pieces fit together:
We implement block_info, block_view, a pre-process function and a template.
function MODULE_NAME_block_info() {
  $blocks['my-footer-menu'] = array(
    'info' => t('My Footer'),
  );
  return $blocks;
}

function MODULE_NAME_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my-footer-menu'
     $tree = menu_tree_page_data('main-menu');
     $block = array( 'subject' => t('My Footer'),
                  'content' => theme('my-footer-menu', $tree),
      );
    break;
 }
return $block;
}

function MODULE_NAME_theme() {
  return array(
    'my_footer_menu' => array(
    'template' => 'my-footer-menu',
    'variables' => array('tree' => NULL),
  ),
);
}

function template_preprocess_my_footer_menu(&$variables) {
  $variables['tree'] = menu_tree_all_data('main-menu');
}

<?php
  for ($i = 0; $i < count($tree); $i++) {
    $menu = each($tree);
     if ($menu) {
        $link = array( '#theme' => 'link',
                'title' => $menu[1]['link']['link_title'],
               'href' => $menu[1]['link']['link_path']);
          print '' . $link['title'] . '';
        //  $output = theme( 'links', $link);  //this isn't right
        //  print $output;    //returns an empty string;
        }
      }
 ?>

The above gets the top level menu items on the page, but it's not clear how to get to the children of each menu item.   Sorry if it seems a bit muddled, just trying to cut my way through the weeds here.
Answer: You can create all of the code yourself, but you could also use the menu block module instead and save yourself a lot of work.
Comment: $menu = menu_navigation_links('main-menu');
      print drupal_render(menu_tree_output(menu_tree_all_data('main-menu')));

How to implement menu in footer blcok


Playing Andy Timmons' Electric Gypsy on Electric Guitar

Question: I've seen a few videos of Andy Timmons playing that and others playing it as well and they utilize some tapping harmonics of some sort which I cannot replicate.
Is that tapping harmonics? How is it done?
Comment: If you have never tried harmonics, I think it is worth plucking them on an acoustic as well a la [Roundabout](http://www.youtube.com/watch?v=elYM1vSZX50).
Answer: From looking at Youtube videos of him playing it: yes, it's tapped harmonics.  If you listen closely you'll notice that he also struggles to make them all sing (at least I noticed on the two videos I've looked at so far), so it's clear that they're not always easy to do.
I find a light touch to be important to make them sing, and it takes practice to figure out how to tap the strings without hitting the frets too hard because that will depend on how high the action on your guitar is.  One of my guitars has a fairly high action, and I noticed they seem to be easier to do there because the strings don't hit the frets so easily.
It might be easiest to start with the octave (twelve frets above your fretted finger) before you try to tap other harmonics, and you'll need to be precise in where you tap.  Since the underlying note of your harmonic is based on the fretted note you'll need to tap the fret of the harmonic above it, instead of where you'd usually put your fretting hand.  So if your base is a D on the 5th string (5th fret), tap right on top of the 17th fret.  Thus, your tapping finger position shifts slightly compared to tapping regular notes.
With a little practice you should find them fairly easy to do, good luck!
Comment: +1 in addition, I think, from seeing videos previously, that some of the ones he has trouble with are the non-octave harmonics. Getting them positioned can be really tricky.


Why Accuracy increase only 1% after data augmentation NLP?

Question: i have small dataset 4840 samples (60% negative ,28% positive,12% negative) i use data augmentation on training set (70%train 30% test) and i have about 2000 samples for each class while test is unbalanced (800 neutral ,400 positive ,200 negative).
I use synonym replace from wordnet and insert words with contextual embedding takeed from nlpaug library.
i use 10-folds cross validation the permonace doesn't increase very much .
without data aug i have 86% accuracy 84 f1 score , with data aug 87% accuracy 85 f1 .
p.s.
I try different data augmentation the result are quite similar i have this value of train and val loss , I was expecting overfitting.
The train and val loss value after 10 epochs
val_loss = 0.22798433965072035
train_loss = 1.6610426288098097
what is the problem ?
Comment: Unbalanced classes are almost certainly not a problem, and oversampling will not solve a non-problem:
[Are unbalanced datasets problematic, and (how) does oversampling (purport to) help?](https://stats.stackexchange.com/q/357466/1352)
Comment: Don't use accuracy, precision, recall, sensitivity, specificity, or the F1 score. Every criticism at the following threads applies equally to all of these, and indeed to all evaluation metrics that rely on hard classifications:
[Why is accuracy not the best measure for assessing classification models?](https://stats.stackexchange.com/q/312780/1352)
[Is accuracy an improper scoring rule in a binary classification setting?](https://stats.stackexchange.com/q/359909/1352)
[Classification probability threshold](https://stats.stackexchange.com/q/312119/1352)
Comment: Instead, use probabilistic classifications, and evaluate these using [proper scoring rules](https://stats.stackexchange.com/tags/scoring-rules/info).
Comment: I could imagine this kind of task being easy. "Cross Validated is great, and I have learned so much here," is pretty clearly a positive, while "You're all terrible and mean and spend your time being professors and professional statisticians instead of doing my homework for me," is pretty clearly negative.
Comment: Given the sparsity of detail in the question, it's impossible to diagnose a specific problem. Moreover, I don't think there's necessarily a "problem"; it seems like there's a limit to how much the model can be improved when using data augmentation. But you might find further improvements from alternate sources, perhaps used in conjunction with data augmentation -- alternative regularization strategies or choice of model or hyper-parameter tuning, etc. Machine learning is hard, data quality is important, there's only so much that you can do with a "small" data set, and noisy problems exist.
Comment: @StephanKolassa I usually agree with you on this topic, but would you not consider this a high signal-to-noise problem [like you would consider optical character recognition](https://stats.stackexchange.com/a/494032/247274)?
Comment: I''ve stated from a work and i want improve this perfomance, I was expecting an increase of at least 2/3 percent for each metrics,why doesn't this happen?
Comment: @Dave: I don't see how this would be high or low signal to noise. How do you decide one way or the other based on the question?
Comment: I have read several articles and would like to know if it is possible to improve the model even more or am I wrong something
Answer: I'm not sure there is necessarily any problem. If you are already fine-tuning a pre-trained language model (e.g. ULMFiT, BERT or something similar), then how much you gain through augmentation is a bit variable from application to application. It may have been reasonable to hope for a bit more, but it may no add that much. If you look at this paper (also an example of sentiment classification), where round-trip translation was used as an augmentation, the gains from augmentation are huge over just fine-tuning a pre-trained model when you have very little data (e.g. 50 examples). However, they get a lot smaller (order of magnitude similar to what you see Figure 1), when the number of examples is larger. I looked at both the 5000 records case (similar number of records) and the 500 records case (similar error rate to yours + the smallest class is about similar sized to your case). I'm not exactly sure how I expect round-trip translation as an augmentation to work vs. what you did, but I'd speculate it might even be more effective (by the way, that type of augmentation is now super-easy, because huggingface offers translation models, so you could easily give it a try).
To check whether there's an issue: Did you inspect some examples to see that the augmentations really modify a lot of text without changing the meaning? Did you have a look at cases from your validation set that get mis-classified (Are they cases that are simply ambigious and no model can realistically get them right? Are the labels even wrong? etc.)?
Other ideas:

With so few examples, it's realistic to try counter-factual augmentation of your training data. I.e. create (=a human does this manually) 2 or more versions of each training example that make the smallest possible change to the text that changes (in the judgement of the human) the category to the other 2 categories. It might be enough to do this for the training data cases that are particularly hard (e.g. using something like the BatchBALD criterion).

You could try test-time-augmentation like in the paper I linked.
Comment: Thanks for the reply, yes I am using a pre-trained bert model on a financial dataset. I tried to change the sentence a little to avoid changing its meaning and not to create exactly the same sentence, for example by replacing a maximum of 3 synonyms or by inserting a maximum of 3 words, the labels are reliable.
Even trying different parameters, learning-rate, batch size, epoch, the model on average on 10 fold remains on an accuracy of 87%.
Now I give a reading to this article.
Comment: Financial texts might be somewhat different than normal internet text. I wonder whether huggingface has a FinanceBERT or something like that, or whether you could fine tune BERT on the language modelling task to a bunch of non-labelled similar documents (as self-supervised pre-pertaining prior to the supervised training)?
Comment: yes i'm using FinBert ProsusAI/finBERT this repository on github i want improve model on  this dataset


Sort View by the order of the arguments

Question: I have a view that receives some arguments from a questionnaire. In the questionnaire I calculate a list of nodes that's sorted by how well they correlate with the questionnaire. Once my view receives these arguments it will just sort them by their node id, and not the custom ordering I already applied when sending the arguments.
Is there any module that will display my nodes in a view, in the same order the arguments are received from the previous page?
I already tried views_arguments_extra, but this cannot achieve what I'm trying to do.
An example:
in my questionnaire I have determined that the 5 following nodes have the highest correlation:
7: 86%
8: 83%
12: 82%
1: 80%
2: 79%

I will then send this top 5 as an argument to my view.
So I also want my view to have that order:
7
8
12
1
2

Answer: I dont know of anyway to sort a view buy the arguments it receives. So this may not be really what your looking for but currently there's no other answers here and hopefully one of these alternative suggestions will help you.
Suggestion 1)
On your questionnaire submit function use views_get_view_result http://api.drupal.org/api/views/views.module/function/views_get_view_result/7 send the arguments to your view as normal you'll get back your 5 top hits but not sorted correctly. You can then reorder the results and manipulate the order the results appear in and print out your manipulated view.
Suggestion 2)
Using Views PHP module http://drupal.org/project/views_php you can create your own sorting with php. You can pass your view the data you need with url's or $_POST get that data in your view and create the sorting using that.
In a nut shell, I dont know how to do what you want, heres a couple of avenues I would probably try..
Comment: Thank you very much :) I did some thinking, I will probably be rendering the nodes on a page myself if your suggestions do not work.
Answer: The module that does this very thing is Views argument sort which now lives in Views argument extras.

Sort View by the order of the arguments


Back Propagation in RNNs

Question: I just started learning RNNs. I'm stuck with two basic doubts:
1.)We start with same weights for each timestamp; loss function can be the logistic loss or squared error across timestamps. In truncated BPTT, I assume we only unroll k timestamps back at each timestamp for calculating the partial derivative of loss with respect to weights. So for calculating partial derivate of loss w.r.t, last time stamp activation involves calculating partial derivative w.r.t previous k timestamps. So I assume we first start calculating partial derivatives of loss from the first stamp so they can be used at the later stage. Please correct me if I'm stating some obvious erroneous statements.
2.) Do we reset weights and perform BPPT for each training example?
Answer:
So for calculating partial derivate of loss w.r.t, last time stamp
  activation involves calculating partial derivative w.r.t previous k
  timestamps.

Yes. At time $t+1$ your cell gets input element of sequence and hidden state from time $t$. That means that you need use derivative of the function that gets this state to compute derivative at state $t+1$

2.) Do we reset weights and perform BPPT for each training example?

No, because that would mean you don't learn anything. Fitting NN is called learning, because in each batch/example you update weights. If you just started from scratch every time your model wouldn't learn anything.

Back Propagation in RNNs


Input format for response in binomial glm in R

Question: In R, there are three methods to format the input data for a logistic regression using the glm function:

Data can be in a "binary" format for each observation (e.g., y = 0 or 1 for each observation);
Data can be in the "Wilkinson-Rogers" format (e.g., y = cbind(success, failure)) with each row representing one treatment; or
Data can be in a weighted format for each observation (e.g., y = 0.3, weights = 10).

All three approach produces the same coefficient estimates, but differ in the degrees of freedom and resulting deviance values and AIC scores. The last two methods have fewer observations (and therefore degrees of freedom) because they use each treatment for the number of observations whereas the first uses each observation for the number of observations.
My question: Are there numerical or statistical advantages to using one input format over another? The only advantage I see is not having to reformat one's data in R to use with the model.
I have looked at the glm documentation, searched on the web, and this site and found one tangentially related post, but no guidance on this topic.
Here is a simulated example that demonstrates this behavior:
# Write function to help simulate data
drc4 <- function(x, b =1.0, c = 0, d = 1, e = 0){
    (d - c)/ (1 + exp(-b * (log(x)  - log(e))))
}
# simulate long form of dataset
nReps = 20
dfLong <- data.frame(dose = rep(seq(0, 10, by = 2), each = nReps))
dfLong$mortality <-rbinom(n = dim(dfLong)[1], size = 1,
                              prob = drc4(dfLong$dose, b = 2, e = 5))

# aggregate to create short form of dataset
dfShort <- aggregate(dfLong$mortality, by = list(dfLong$dose),
                     FUN = sum)
colnames(dfShort) <- c("dose", "mortality")
dfShort$survival <- nReps - dfShort$mortality
dfShort$nReps <- nReps
dfShort$mortalityP <- dfShort$mortality / dfShort$nReps

fitShort <- glm( cbind(mortality, survival) ~ dose,
                 data = dfShort,
                 family = "binomial")
summary(fitShort)

fitShortP <- glm( mortalityP ~ dose, data = dfShort,
                  weights = nReps,
                  family = "binomial")
summary(fitShortP)

fitLong <- glm( mortality ~ dose, data = dfLong,
                family = "binomial")
summary(fitLong)

Comment: In your example, the difference between the null and residual deviance is equal for all three models. If you add or remove a parameter, the change in AIC is also the same for all three.
Comment: You answered yourself: if using the same data, to same results, then how could they be different? Moreover, if the method would give different results only because of providing the data in different format, something would be deeply wrong with it, or with its implementation.
Comment: The WR format is ultimately a weighted likelihood. The problem with weights is R can't tell whether they're frequency weights, probability weights, or other. With survey weighting, e.g., you may only have n observations but they represent segments of the population/sampling frame. So the degrees of freedom is indeed 100. `svyglm` from the survey package gives you better methods of handling the weight argument.
Comment: But if you would fit a quasibinomial model using all three ways of coding they would produce different results, right, since one could have a positive overdispersion when coded as binomial data but not when coded as logistic/binary data. Or am I wrong on this?
Comment: See also https://stats.stackexchange.com/questions/97515/what-does-likelihood-is-only-defined-up-to-a-multiplicative-constant-of-proport/97522#97522
Answer: There's no statistical reason to prefer one to the other, besides conceptual clarity. Although the reported deviance values are different, these differences are completely due to the saturated model. So any comparison using relative deviance between models is unaffected, since the saturated model log-likelihood cancels.
I think it's useful to go through the explicit deviance calculation.
The deviance of a model is 2*(LL(Saturated Model) - LL(Model)). Suppose you have $i$ different cells, where $n_i$ is the number of observations in cell $i$, $p_i$ is the model prediction for all observations in cell $i$, and $y_{ij}$ is the observed value (0 or 1) for the $j$-th observation in cell $i$.
Long Form
The log likelihood of the (proposed or null) model is
$$\sum_i\sum_j\left(\log(p_i)y_{ij} + \log(1 - p_i)(1 - y_{ij})\right)$$
and the log likelihood of the saturated model is $$\sum_i\sum_j \left(\log(y_{ij})y_{ij} + \log(1 - y_{ij})(1-y_{ij})\right).$$ This is equal to 0, because $y_{ij}$ is either 0 or 1. Note $\log(0)$ is undefined, but for convenience please read $0\log(0)$ as shorthand for $\lim_{x \to 0^+}x\log(x)$, which is 0.
Short form (weighted)
Note that a binomial distribution can't actually take non-integer values, but we can nonetheless calculate a "log likelihood" by using the fraction of observed successes in each cell as the response, and weighting each summand in the log-likelihood calculation by the number of observations in that cell.
$$\sum_in_i \left(\log(p_i)\sum_jy_{ij}/n_i + \log(1 - p_i)(1 - \sum_j(y_{ij}/n_i)\right)$$
This is exactly equal to the model deviance we calculated above, which you can see by pulling in the sum over $j$ in the long form equation as far as possible.
Meanwhile the saturated deviance is different. Since we no longer have 0-1 responses, even with one parameter per observation we can't get exactly 0. Instead the saturated model log-likelihood is
$$\sum_i n_i\left(\log(\sum_jy_{ij}/n_i)\sum_jy_{ij}/n_i + \log(1 - \sum_jy_{ij}/n_i)(1-\sum_jy_{ij}/n_i)\right).$$
In your example, you can verify that twice this amount is the difference between the reported null and residual deviance values for both models.
ni = dfShort$nReps
yavg = dfShort$mortalityP
sum.terms <-ni*(log(yavg)*yavg + log(1 - yavg)*(1 - yavg))
# Need to handle NaN when yavg is exactly 0
sum.terms[1] <- log(1 - yavg[1])*(1 - yavg[1])

2*sum(sum.terms)
fitShortP$deviance - fitLong$deviance

Comment: The "saturated model" is an imagined model with one parameter per observation. So its predicted probability for every observation is 1 or 0, depending on the actual observed value. So in this case the log likelihood of the saturated model is indeed 0, the data are the only data which could be generated by the saturated model.
Comment: I think you'll have to clarify the expression for deviance of the saturated models. Log of 0 doesn't operate so well.
Comment: Thanks, I should have clarified what I meant. I added an edit to clarify that by 0log(0) I mean 0 in this context.
Comment: OK but I'm properly confused (forgive me I never covered deviance in any great detail): if you have log(y)y - log(1-y)(1-y) as the saturated model deviance, isn't every observation just 0?
Comment: But if you would fit a quasibinomial model using all three ways of coding they would produce different results, right, since one could have a positive overdispersion when coded as binomial data but not when coded as logistic/binary data. Or am I wrong on this?


Positioning problem optimal control

Question: Consider the positioning problem:
$\dot x_1 = x_2$,
$\dot x_2 = u$ with $x_1(0)=0,x_2(0)=X, X>0$. show that the bang-bang control switch can be employed to steer the system to the origin. Find the time taken and the position where the switch must be made.
Answer: I am going to do an outline and let you fill in the blanks.
For bang-bang, what are the different choices we should investigate for $u$? They are $\pm 1$. You should note why.
Case 1: $u = 1$
$$x'_1 = x_2$$
$$x_2' = 1$$
with $x_1(0)=0,x_2(0)=X, X>0$.
For this system, we have:
$\tag 1 x_2 x'_2 = x'_1, ~~\text{so}~~ \dfrac{1}{2}\left(x_2^2\right)' = x_1$
If we let $t_0$ belong to the time interval where $u = 1$, and integrate from $t_0$ to $t$, we get:
$$\dfrac{x_2^2(t)}{2} - \dfrac{x_2^2(t_0)}{2} = x_1(t) - x_1(t_0)$$
$$x_2^2(t) = 2 x_1(t) + \left(x_2^2(t_0) - 2x_1(t_0)\right)$$
Using the initial conditions, we have $t_0 = 0$ and this reduces to:
$$\tag 2 x_2^2(t) = 2x_1(t) + X^2 \rightarrow x_2^2(t) = 2x_1(t) + w$$
This tells us that we have a parabola and that as long as $u=1$, the trajectory stays on the curve $(2)$ for some constant $w$.
If we draw the trajectories for this, we have:

Case 2: $u = -1$
Repeat the steps for Case 1, but $u = -1$.
The trajectories look like:

Now that we have analyzed the system for the appropriate values of $u$, we see that the solutions $(x_1(t), x_2(t))$, lie on two different parabolas.
To design an optimal control, we start on one parabola and steer to the origin by starting with $u = -1$ and our trajectory is moving down. We just switch control to $u=1$, which causes us to move to the first parabola and we end up at the origin.
You can work the time portion since you have two parabolas and need to find the time when the switch should occur.
Comment: Here, I am feeling to be under a rain of arrows. Colorful and oriented to a hidden mysterious target. You did them all. :-)
Comment: Nice job, Amzoti!
Comment: Good for you, (and good for the OP!) g'night ;-)
Comment: Thanks - helps a lot as I have so many similar problems to do for an assignment
Comment: @Natalie: You are very welcome! Have a great day!

Positioning problem optimal control


Delete element in a slice and returning the removed one and the remaining

Question: I just want a function that having a slice of a struct type "t", returns the returns the element I'm looking for and the remaining, I tried with the partial solution for my problem like pointed out here:
Delete element in a slice
But for a weird reason, it does not work as expected
https://play.golang.org/p/tvJwkF5c_tj
    func main() {
    var names = []string{"john", "julio", "pepito","carlos"}
    fmt.Println(getMe("john", names))
}
func getMe(me string, names []string) (string, []string, bool) {
    for i := range names {
        if names[i] == me {
            return names[i], append(names[:i], names[i+1:]...), true
        }
    }
    return "", nil, false
}

but the result gives me:
julio [julio pepito carlos] true

UPDATE:
https://play.golang.org/p/1xbu01rOiMg
Taking the answer from @Ullaakut
If I do: append(names[:i], names[i+1:]...), it changes the original slice, so this does not work for me, I do not want my slice to change, because I will be using it later on
Answer: Simply use the range to get both the value and the index, instead of accessing the value by using the index.
package main

import (
    "fmt"
)

func main() {
    var names = []string{"john", "julio", "pepito", "carlos"}
    name, newNames, _ := getMe("john", names)

    fmt.Println("extracted name:\t\t\t\t", name)
    fmt.Println("new slice without extracted name:\t", newNames)
    fmt.Println("old slice still intact:\t\t\t", names)
}

func getMe(me string, names []string) (string, []string, bool) {
    var newSlice []string

    for i := 0; i < len(names); i++ {
        if names[i] == me {
            newSlice = append(newSlice, names[:i]...)
            newSlice = append(newSlice, names[i+1:]...)
            return names[i], newSlice, true
        }
    }

    return "", nil, false
}

Outputs

extracted name:                        john
new slice without extracted name:      [julio pepito carlos]
old slice still intact:                [john julio pepito carlos]

See playground example
Edit after request for a faster version: Using the manual for instead of the range loop is much faster. Since you need to create a new slice without the element, it's necessary to build a new slice within the function, which is always going to take some processing power.
Comment: At the end it's the same as the other one :D, but anyway I'll stick with that one, thanks!
Comment: Glad I could help :)
Comment: Hi, I just encounter another problem with the solution, see my updated question
Comment: Yes it changes the original slice, and that is why it didn't work originally, you were returning the first element of your slice and then deleting it, which in turn made it so that you returned the first element of your old slice :) I will update my answer.
Comment: wouldn't that be expensive if I do it multiple times?
Comment: I can write a less expensive version if you want, sure
Comment: Updated the code & link to the playground, and explained what are the speed improvements. Feel free to benchmark it, it should be quite faster than the previous version, but the main bottleneck stays the creation of a new slice, which can only be solved by changing the way you are architecturing your code to not require the creation of a second slice :/ Let me know if this is good enough for you and feel free to validate the answer if so :)
Comment: It does not work, it continues to change the original slice
Comment: Yep my bad, forgot that calling `append()` on `names` would modify it. The only obvious option I see then is to append it to the newSlice, updated the code.


Why am I always getting the same output in this loop?

Question: I have the following function:
function mattes_create_matte_array(mattes, selected_type)
{
  ...

  $(mattes).each(function(i, el) //loop through the mattes xml
  {
    fillets = $(el).find("fillet")[0];
    console.log("i: " + i);
    if(typeof(fillets) !== "undefined")
    {
      switch (i)
      {
        case 0: fillet_selected_matte = "fillet_matte_layer_top"; console.log(fillet_selected_matte);break;
        case 1: fillet_selected_matte = "fillet_matte_layer_middle"; console.log(fillet_selected_matte);break;
        case 2: fillet_selected_matte = "fillet_matte_layer_bottom"; console.log(fillet_selected_matte);break;
      }

      fillet_change($(fillets).find("imgsrc").text(), $(fillets).find("cid").text(), $(fillets).find("sku").text());
    }

    ...
}

When I output fillet_selected_matte, I always get back "fillet_matte_layer_top", when I am expecting to output each "fillet_matte_layer_..."
console.log(el) is the following
<mat>
  <item size="0">
    <imgsrc>11852997eab43ff5c7b1803692bee608</imgsrc>
    <size>0</size>
    <cpu>20</cpu>
    <cid>4208</cid>
  </item>
  <fillet>
    <imgsrc>113a2584b32539ecdc35d70b39fde504</imgsrc>
    <width>0.31</width>
    <cid>9352</cid>
    <sku>TD00060S1</sku>
  </fillet>
</mat>
<mat>
    <item size="0.5">
    <imgsrc>579767cea6941301e6f91d43580a1948</imgsrc>
    <size>0.5</size>
    <cpu>0</cpu>
    <cid>4390</cid>
  </item>
    <fillet>
    <imgsrc>fee7ec5a4b50b65e94801682ae076a5a</imgsrc>
    <width>0.31</width>
    <cid>9348</cid>
    <sku>TD00052S0</sku>
  </fillet>
</mat>
<mat>
  <item size="0.5">
    <imgsrc>11852997eab43ff5c7b1803692bee608</imgsrc>
    <size>0.5</size>
    <cpu>0</cpu>
    <cid>42089349</cid>
  </item>
  <fillet>
    <imgsrc>5ade25e607b6302691c318a94792e6eb</imgsrc>
    <width>0.31</width>
    <cid>9349</cid>
    <sku>TD00060GL1</sku>
  </fillet>
</mat>

Here's the code for fillet_change:
function fillet_change(thumb, cid, sku)
{
  if (mattes_selected_type == 15) //letter mattes
  {
    alert("Fillets can only be applied to rectangular openings. Your current layout does not contain any rectangular openings, fillet was not applied");
    return;
  }
  var img = new Image();
  img.src =  SITE_URL + '/system/components/compimg/' + thumb + '/pattern';
  img.onload = function()
  {
    width = .31;
    img.width = width * ppi; //TODO: Get actual width from xml?
    img.height = width * ppi; //TODO: Get actual width from xml?
    $( document ).ready(function()
    {
      $("div[id^='opening_']").each(function(i) //for each div that has an id of opening_(number)
      {
        //Set the values in the array with the width and height
        switch(fillet_selected_matte)
        {
          case "fillet_matte_layer_bottom":
            moulding_matte_canvas_width[i] = $("#opening_" + i).width();
            moulding_matte_canvas_height[i] = $("#opening_" + i).height();
            index = 2;
            break;

          case "fillet_matte_layer_middle":
            moulding_matte_canvas_width[i] = $("#opening_" + i).width() + 10;
            moulding_matte_canvas_height[i] = $("#opening_" + i).height() + 10;
            index = 1;
            break;

          case "fillet_matte_layer_top":
            if (mattes_default_selected == true)
            {
              moulding_matte_canvas_width[i] = $("#opening_" + i).width() + 22;
              moulding_matte_canvas_height[i] = $("#opening_" + i).height() + 22;
            }
            else
            {
              moulding_matte_canvas_width[i] = $("#opening_" + i).width();
              moulding_matte_canvas_height[i] = $("#opening_" + i).height();
            }
            index = 0;
            break;
        }
        var parser = new DOMParser(); //create a new DOMParser
        var doc = parser.parseFromString(mattes_get_mattes_xml(), "application/xml"); //convert the string to xml
        doc.getElementsByTagName('fillet')[index].innerHTML = "<imgsrc>" + thumb + "</imgsrc><width>" + width + "</width><cid>" + cid + "</cid><sku>" + sku + "</sku>";
        var serializer = new XMLSerializer(); //create a new XMLSerializer
        mattes_mattes_xml = serializer.serializeToString(doc); //convert the xml back to a string

        common_get_order_xml();
        moulding_draw(img, "fillet"); //Call the moulding_draw function, which draws the fillet on the canvas
      });
    });
  };
}

Here's the code for moulding_draw:
function moulding_draw(img, fillet)
{
  $(document).ready(function() {
    $("div[id^='opening_']").each(function(i) //for each div that has an id of opening_(number)
    {
      if (fillet == "fillet")
      {
        $("#fillet_canvas_" + fillet_selected_matte + "_" + i).remove(); //remove the selected filet canvas
      }
      else
      {
        $("#moulding_canvas").remove(); //remove the moulding canvas
      }

      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext("2d");
      if (fillet == "fillet")
      {
        canvas.id = "fillet_canvas_" + fillet_selected_matte + "_" + i; //create a fillet canvas for each element
        console.log(canvas.id);
      }
      else
      {
        canvas.id = "moulding_canvas";
      }
      canvas.style.position = "absolute";
      canvas.style.zIndex = 5;
      if (fillet == "fillet")
      {
        //Set the positioning of the fillets
        switch(fillet_selected_matte)
        {
          case "fillet_matte_layer_bottom":
            fillet_bottom_left = parseInt($("#opening_" + i).css('left')) - img.width + "px";
            canvas.style.left = fillet_bottom_left;parseInt($("#opening_" + i).css('top')) - img.width + "px";

            fillet_bottom_top = parseInt($("#opening_" + i).css('top')) - img.width + "px";
            canvas.style.top = fillet_bottom_top;
            break;

          case "fillet_matte_layer_middle":
            fillet_middle_left = parseInt($("#opening_" + i).css('left')) - img.width - 5 + "px";
            canvas.style.left = fillet_middle_left;

            fillet_middle_top = parseInt($("#opening_" + i).css('top')) - img.width - 5 + "px";
            canvas.style.top = fillet_middle_top;
            break;

          case "fillet_matte_layer_top":
            if (mattes_default_selected == true)
            {
              fillet_top_left = parseInt($("#opening_" + i).css('left')) - img.width - 12 + "px";
              canvas.style.left = fillet_top_left;

              fillet_top_top = parseInt($("#opening_" + i).css('top')) - img.width - 12 + "px";
              canvas.style.top = fillet_top_top;
            }
            else
            {
              fillet_top_left = parseInt($("#opening_" + i).css('left')) - img.width + "px";
              canvas.style.left = fillet_top_left;

              fillet_top_top = parseInt($("#opening_" + i).css('top')) - img.width + "px";
              canvas.style.top = fillet_top_top;
            }
            break;
        }
      }
      else
      {
        canvas.style.left = "-" + img.width + "px";
        canvas.style.top = "-" + img.height + "px";
      }

      canvas.height = parseInt($("#matte_canvas").height()) + (img.height * 2);
      canvas.width = parseInt($("#matte_canvas").width()) + (img.width * 2);

      moulding_draw_elements(ctx, img, i); //call the function to actually draw the moulding elements

      if (fillet == "fillet")
      {
        $(canvas).insertAfter("#opening_" + i); //insert the canvas after the specific opening
      }
      else
      {
        $("#mattes").append(canvas); //appending the canvas
      }
    });
  });
}

Comment: Without the matching HTML the code is pretty useless. e.g. what is a `fillet` element?
Comment: Can you include the relevant HTML as well?
Comment: Found the cause, but cannot post an answer while the question is on hold. Just drop the indexing on `$(el).find("fillet")[i]` e.g. `$(el).find("fillet");` You are accessing child elements based on the parent's index! :) http://jsfiddle.net/TrueBlueAussie/BTHLZ/
Comment: Why the votes to close?
Comment: Which of the logs are you actually getting? Maybe `fillets` is always undefined? Why do you have so many global variables?
Comment: I posted the xml of the "el" object
Comment: Thanks. Without that we had no clue it was XML driven.
Comment: what is in the `mattes` array ?
Comment: There's only one `` under each ``
Comment: @TrueBlueAussie: Ugh, I assumed that is what he wanted to do?
Comment: Also after its initialization the variable "fillets" will never be `undefined`.
Comment: @fillet_change: That made no sense once the data was shown. (and I think `Alison`C may not be a *he* :)
Comment: What they are all trying to say is that you need to show your full code *for everyone to appreciate its charm* :)
Comment: Any chance of placing your code into the working JSFiddle provided below?
Comment: @Pointy - sometimes there are no fillets
Answer: Just drop the indexing on $(el).find("fillet")[i]
JSFiddle: http://jsfiddle.net/TrueBlueAussie/BTHLZ
e.g. to get the only DOM element (or undefined)
$(el).find("fillet")[0];

You were accessing child elements based on the parent's index, but there is only one fillet in each mat (maximum). Note the question has been changed, so this answer may make less sense now :)
Comment: I changed that but the call to fillet_change is only taking into account "fillet_matte_layer_bottom"
Comment: You do realise you *have not* provided that code don't you (for `fillet_change`)? :)
Comment: You have changed your code to have [0] which is correct as you wanted the DOM element, but now we need your fill example in JSFiddle as you are describing subsequent problems.
Comment: It's a big project that has a lot of code that depends on each other, otherwise I'd edit that jsfiddle
Comment: The immediate question was answered, and the question changed to incorporate it, but you appear to have a number of subsequent issues. Might be better off posting new questions as this one has mutated too much now from the original. "We" really need a JSFiddle example of the part that does not function.


Media Query CSS important

Question: Making responsive website,
I wrote this, it doesn't work.
@media (max-width: 767px) {
    #nav { display:block; }
}

but, I wrote this, it works!
@media (max-width: 767px) {
    #nav { display:block !important; }
}

Why? :(
Comment: Perhaps there's a selector somewhere which has a higher priority. read about [CSS specificity](http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/).
Answer: Check your css code , something with higher specificity is changing your #nav element.
Answer: This is a little concept:
!important after the style attribute gives high priority to that style. That is why your css is working then.
!important override the existing stylesheet attribute defined in same context.
Answer: !important will override any inline style, or more specific style that may be taking precedence on your page.
For example, you can override the style on this element...

by adding this in your stylesheet...
div { background-color: black !important }

But!, if you add !important to the inline style, it will then take precedence, for example...

here is a good stackoverflow answer explaining the concept in a bit more detail.

Media Query CSS important


Como transformar uma matriz de um ÚNICO objeto?

Question: A minha dúvida é a seguinte, como eu posso fazer com que uma matriz que tenha 3 objetos, se transforme em um único objeto ? Conforme o print abaixo, a matriz está me trazendo 3 objetos, porém eu preciso montar um único objeto com o valor de cada matriz, já pesquisei algo como reduce, mas não consegui obter sucesso. Aqui está o meu código :
       //"ITEMS" é um FirebaseListObservable que transformo em um array
       //javascript

       //dadosPontoFuncionario é o meu array javascript, que está retornando
       //o que está no console, é ele que preciso que vire um único objeto

       this.items.subscribe( data => {
         this.dadosPontoFuncionario = data;
         console.log(this.dadosPontoFuncionario);
       })

Comment: Que matriz? você não tem um array de objetos?
Comment: Como você vai tratar se houverem duas chaves iguais ao juntar os objetos do seu array?
Comment: Tenho um array de objetos, porém eu gostaria de transformá-lo em um único objeto entende, unir os 3 objetos em um só, na verdade nem sei se tem como fazer isso.

Depende qual chave ele considera, a $key é única, porém eu tenho outros dois tipos de chaves que são repetidos em cada objeto desse.
Comment: Ainda não consegui entender... você gerar um único objeto consolidando todas as proprieades de todos os objetos do array? ou criar um a réplica em um único objeto onde cada objeto seria uma propriedade? Ex.: `{ item1: {}, item2:{} ...}`
Comment: Gerar um único objeto consolidando todas as propriedades de todos os objetos do array. Para você entender melhor, é uma aplicação de registro de ponto. Então cada objeto corresponde a um ponto registrado, tenho o ponto de inicio, ponto do intervalo, ponto do fim do expediente. Preciso mostra-los na tela para o usuário, porém para organizar melhor, eu queria unir os 3 objetos, assim eu posso ter acesso a informação dos 3 ao mesmo tempo e posso mostrar essas informações na tela. Se não eu tenho que mostrar os objetos separados na view.
Answer: Não sei se entendi direito, mas vou tentar...
Se for o que estou imaginando,

const arrayObject = [
{nome:'Objeto um'},
{teste:'Objeto dois'},
{nome:'Objeto tres'}
]

console.log(arrayObject.reduce((a,b)=>({...a, ...b})))

você pode fazer um reduce, o problema é que se os objetos tiverem chaves com o mesmo nome valerá o valor da chave do úlimo objeto encontrado..
Comment: Exatamente, eu cheguei ao mesmo resultado do seu código. Porém tem esse problema das chaves. Nesse listObservable, eu tenho um campo que é repetido nos 3 objetos, pois eu preciso dele para consulta do banco de dados. Acho que vou ter que arrumar outra forma de fazer...
Comment: Pois o idEmpresa e o empresaKey eu utilizo para comparar se o funcionário pertence a aquela empresa ou não, já que se trata de uma aplicação multiusuário, vou ter que ver outra forma de fazer eu acho. Mas fico agradecido pela sua resposta


Controlar velocidade de animação utilizando o componente JSlider

Question: Bom galera, estou desenvolvendo um projetinho que visa simular o ambiente controlado de trilhos de trem, onde tenho 3 trens circulando em sentido horário, onde os três passam pelo mesmo local em determinados trechos. Estou com dificuldade em implementar a velocidade dos trens dinamicamente utilizando o componente JSlider. Consegui criar os 3 componentes, porém ainda não consegui associá-los aos meus trens.
Segue o código:
public class Trens {

private static final double QUADROS_POR_SEGUNDO = 20.0;

public static void preparar() {
    JFrame t = new JFrame();
    t.setLayout(null);
    t.setSize(1200, 900);
    t.setTitle("Semáforo");
    t.setLocationRelativeTo(null);
    t.setResizable(false);
    t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Trilho t1 = new Trilho(300, 100, 300, 170);
    Trilho t2 = new Trilho(600, 100, 300, 170);
    Trilho t3 = new Trilho(450, 270, 300, 170);
    Jslider slider = new Jslider(30, 150, 300, 170);
    Jslider slider2 = new Jslider(900, 150, 300, 170);
    Jslider slider3 = new Jslider(150, 330, 300, 170);

    Trem a = new Trem(t1, Color.BLUE, 350, 100, 100.0);
    Trem b = new Trem(t2, Color.GREEN, 650, 100, 100.0);
    Trem c = new Trem(t3, Color.RED, 450, 335, 100.0);
    t.add(a);
    t.add(b);
    t.add(c);
    t.add(t1);
    t.add(t2);
    t.add(t3);
    t.add(slider);
    t.add(slider2);
    t.add(slider3);
    Runnable moverTudo = () -> {
        EventQueue.invokeLater(() -> {
            a.mover(1 / QUADROS_POR_SEGUNDO);
            b.mover(1 / QUADROS_POR_SEGUNDO);
            c.mover(1 / QUADROS_POR_SEGUNDO);
        });
    };
    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(moverTudo, 0, (int) (1000 / QUADROS_POR_SEGUNDO), TimeUnit.MILLISECONDS);
    t.setVisible(true);
}

public static void main(String[] args) {
    EventQueue.invokeLater(Trens::preparar);
}

public static class Trilho extends JComponent {
    public Trilho(int x, int y, int width, int height) {
        this.setBounds(x, y, width, height);
        this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    }
}

public static class Trem extends JComponent {
    private Color cor;
    private Trilho trilho;
    private int x;
    private int y;
    private double velocidade; // pixels por segundo
    private double restante; // Frações de pixels que faltou andar.

    public Trem(Trilho trilho, Color cor, int x, int y, double velocidade) {
        this.trilho = trilho;
        this.cor = cor;
        this.x = x;
        this.y = y;
        this.velocidade = velocidade;
        this.setBounds(x - 5, y - 5, 10, 10);

    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(cor);
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    public void mover(double deltaT) {
        if (velocidade == 0) return;
        boolean sentidoHorario = velocidade > 0;
        double distancia = Math.abs(restante + velocidade * deltaT);
        int tLeft = trilho.getX();
        int tTop = trilho.getY();
        int tRight = tLeft + trilho.getWidth();
        int tBottom = tTop + trilho.getHeight();

        for (int i = 0; i < (int) distancia; i++) {
            // Se deve ir à esquerda:
            if (x > tLeft && y == (sentidoHorario ? tBottom : tTop)) {
                x--;
            // Se deve ir à direita:
            } else if (x < tRight && y == (sentidoHorario ? tTop : tBottom)) {
                x++;
            // Se deve ir para cima:
            } else if (y > tTop && x == (sentidoHorario ? tLeft : tRight)) {
                y--;
            // Se deve ir para baixo:
            } else if (y < tBottom && x == (sentidoHorario ? tRight : tLeft)) {
                y++;
            // Se não for nenhum dos anteriores, o trem está descarrilhado. Coloca de novo no trilho.
            } else {
                x = tLeft;
                y = tTop;
            }
        }
        restante = distancia % 1;
        setLocation(x - 5, y - 5);
    }
}

public static class Jslider extends JPanel{

    private Jslider(int x, int y, int width, int height){
        this.setBounds(x, y, width, height);
        JSlider control = new JSlider(0,100,25);
        control.setMajorTickSpacing(50);
        control.setMinorTickSpacing(10);
        control.setPaintTicks(true);
        control.setFont(new Font("Serfi", Font.ITALIC, 12));
        control.setPaintLabels(true);
        control.setSnapToTicks(true);
        add(control);

    }
}

public class EventoSlider implements ChangeListener{

    @Override
    public void stateChanged(ChangeEvent e) {
         JSlider source = (JSlider) e.getSource();
         int fps = (int) source.getValue();
        System.out.println(fps);
    }

}
}

Comment: @CarlosDiego Vou dar uma olhada.
Comment: Por que está tudo estático? Pode ser bobagem, mas tudo estar estático pode ser uma das fontes de seu problema.
Comment: veja se essa resposta lhe ajuda: https://pt.stackoverflow.com/a/208128/28595
Comment: Esta pergunta é uma *follow-up* desta outra: https://pt.stackoverflow.com/q/226377/132
Comment: Como assim estatico? @Articuno. Nao é necessariamente como o exemplo que mandou.
Comment: Help-me @VictorStafusa.
Comment: @Articuno preciso implementar tbm deadlock entre os trens poderia me ajudar na logica? indenpendente da velocidade ambos nao podem colidir, um tem que esperar o outro passar para depois ele continuar caminho. O pro é fazer isso dinamicamente na medida que posso alterar a velocidade dos trens em tempo de execução
Answer: Consegui, até que foi simples:
package trens;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;

public class Trens {

    private static final double QUADROS_POR_SEGUNDO = 20.0;

    public static void preparar() {
        JFrame t = new JFrame();
        t.setLayout(null);
        t.setSize(1200, 900);
        t.setTitle("Semáforo");
        t.setLocationRelativeTo(null);
        t.setResizable(false);
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Trilho t1 = new Trilho(300, 100, 300, 170);
        Trilho t2 = new Trilho(600, 100, 300, 170);
        Trilho t3 = new Trilho(450, 270, 300, 170);

        Trem a = new Trem(t1, Color.BLUE, 350, 100, 100.0);
        Trem b = new Trem(t2, Color.GREEN, 650, 100, 100.0);
        Trem c = new Trem(t3, Color.RED, 450, 335, 100.0);
        VelocityControl slider = new VelocityControl(a, 30, 150, 300, 170);
        VelocityControl slider2 = new VelocityControl(b, 900, 150, 300, 170);
        VelocityControl slider3 = new VelocityControl(c, 150, 330, 300, 170);
        t.add(a);
        t.add(b);
        t.add(c);
        t.add(t1);
        t.add(t2);
        t.add(t3);
        t.add(slider);
        t.add(slider2);
        t.add(slider3);
        Runnable moverTudo = () -> {
            EventQueue.invokeLater(() -> {
                a.mover(1 / QUADROS_POR_SEGUNDO);
                b.mover(1 / QUADROS_POR_SEGUNDO);
                c.mover(1 / QUADROS_POR_SEGUNDO);
            });
        };
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(moverTudo, 0, (int) (1000 / QUADROS_POR_SEGUNDO), TimeUnit.MILLISECONDS);
        t.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(Trens::preparar);
    }

    public static class Trilho extends JComponent {
        public Trilho(int x, int y, int width, int height) {
            this.setBounds(x, y, width, height);
            this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        }
    }

    public static class Trem extends JComponent {
        private Color cor;
        private Trilho trilho;
        private int x;
        private int y;
        private double velocidade; // pixels por segundo
        private double restante; // Frações de pixels que faltou andar.

        public Trem(Trilho trilho, Color cor, int x, int y, double velocidade) {
            this.trilho = trilho;
            this.cor = cor;
            this.x = x;
            this.y = y;
            this.velocidade = velocidade;
            this.setBounds(x - 5, y - 5, 10, 10);
        }

        @Override
        public void paintComponent(Graphics g) {
            g.setColor(cor);
            g.fillRect(0, 0, getWidth(), getHeight());
        }

        public void setVelocidade(double novaVelocidade) {
            this.velocidade = novaVelocidade;
        }

        public void mover(double deltaT) {
            if (velocidade == 0) return;
            boolean sentidoHorario = velocidade > 0;
            double distancia = Math.abs(restante + velocidade * deltaT);
            int tLeft = trilho.getX();
            int tTop = trilho.getY();
            int tRight = tLeft + trilho.getWidth();
            int tBottom = tTop + trilho.getHeight();

            for (int i = 0; i < (int) distancia; i++) {
                // Se deve ir à esquerda:
                if (x > tLeft && y == (sentidoHorario ? tBottom : tTop)) {
                    x--;
                // Se deve ir à direita:
                } else if (x < tRight && y == (sentidoHorario ? tTop : tBottom)) {
                    x++;
                // Se deve ir para cima:
                } else if (y > tTop && x == (sentidoHorario ? tLeft : tRight)) {
                    y--;
                // Se deve ir para baixo:
                } else if (y < tBottom && x == (sentidoHorario ? tRight : tLeft)) {
                    y++;
                // Se não for nenhum dos anteriores, o trem está descarrilhado. Coloca de novo no trilho.
                } else {
                    x = tLeft;
                    y = tTop;
                }
            }
            restante = distancia % 1;
            setLocation(x - 5, y - 5);
        }
    }

    public static class VelocityControl extends JPanel {
        private VelocityControl(Trem trem, int x, int y, int width, int height) {
            this.setBounds(x, y, width, height);
            JSlider control = new JSlider(0, 100, 25);
            control.setMajorTickSpacing(50);
            control.setMinorTickSpacing(10);
            control.setPaintTicks(true);
            control.setFont(new Font("Serif", Font.ITALIC, 12));
            control.setPaintLabels(true);
            control.setSnapToTicks(true);
            this.add(control);
            control.addChangeListener(e -> trem.setVelocidade(control.getValue()));
        }
    }
}

Mudei o nome da classe Jslider para VelocityControl para não confundir com a JSlider (note que uma tem o S maiúsculo e a outra minúsculo).
O truque para fazer o valor escolhido refletir na velocidade é o control.addChangeListener(e -> trem.setVelocidade(control.getValue())); com a sintaxe do lambda, isso fica bem simples e limpo.
Para ligar os trens aos controles, bastou passar o trem como um parâmetro   mais para o construtor do VelocityControl.
Um último detalhe é que você tinha usado "Serfi" ao invés de "Serif" no nome da fonte, um erro de digitação.
Comment: Perfeito @VictorStafusa, realmente tinha errado, ja tinha ate corrigido no meu codigo.
Comment: todos os trens estao rodando numa thread so?
Comment: @CarlosDiego Sim. O `Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(moverTudo, 0, (int) (1000 / QUADROS_POR_SEGUNDO), TimeUnit.MILLISECONDS);` cria apenas uma thread para ficar executando periodicamente o `moverTudo`. Entretanto, a execução de fato acontece dentro da EDT.
Comment: no caso preciso identificar uma provavel colisao entre os trens e fazer com que uma thread pause enquanto a outra do trem siga caminho, depois a thread pausada volta a percorrer.. isso para os 3 trens. Como esta implementado tem como fazer essa logica?
Comment: @CarlosDiego Tentar fazer isso com threads diferentes só vai te trazer dor de cabeça e nenhum benefício. A resposta é colocar alguma lógica dentro do `moverTudo` ou do método `mover` de cada trem que verifique se ocorreu uma colisão e decida o que fazer nesse caso.
Comment: Realmente, ai como poderia ser a verificaçao pra saber se eles podem colidir?
Comment: @CarlosDiego `Trem outro = ...; boolean colidiu = Math.abs(this.x - outro.x) < 10 && Math.abs(this.y - outro.y) < 10;` - No caso esses valores 10 ocorre porque essa é a largura e altura dos trens. Se a largura e altura puder variar, então você usaria `(this.width - outro.width) / 2` e `(this.height - outro.height) / 2`.
Comment: Na verdade, como o nome da classe já sugere, você vai precisar usar semáforos, literalmente rs. Quando o trem chegar no ponto onde as duas linhas coincidem, coloque um semáforo ali. Quando o trem chegar ali, verifique se está "SIGA", senão fique parado e aguarde o outro trem passar. Quando o trem passa e o sinal é "SIGA", move o trem e em seguida coloca "PARE" nesse sinal. Você precisa de 3 sinais, um para cada trecho de interseção entre as linhas de trem.
Comment: @Dudaskank voce tem algum exemplo que de pra aplicar de maneira facil e pratica de entender nesse projetinho?
Comment: Ótima resposta, eu tinha uma ideia de solução, mas de longe essa é uma forma bem menos trabalhosa e proporciona mais controle de tudo, parabens victor =)


Finding the eigenvectors of a 3x3 matrix

Question: Hi how do I find the eigenvector of the eigenvalue=8 for the matrix below.
What I've done so far is:(https://i.stack.imgur.com/J4Rj8.png)
(https://i.stack.imgur.com/1hkk1.jpg)
(https://i.stack.imgur.com/KuUpH.jpg)
Answer: When dividing the last two rows by $(\pm)\,6$, you seem to replace $\tfrac{12}{6}$ by $1$ instead of $2$. It should be:
$$\begin{pmatrix}
1 & 4 & 7 \\
0 & 1 & \color{red}{2} \\
0 & 1 & \color{red}{2}
\end{pmatrix}$$
Now $R_3 \to R_3-R_2$ and $R_1 \to R_1-4R_2$ to get:
$$\begin{pmatrix}
1 & 0 & -1 \\
0 & 1 & 2 \\
0 & 0 & 0
\end{pmatrix}$$
And you have $x=z$ and $y=-2z$; so the eigenvector corresponding to eigenvalue $\lambda=8$ is any non-zero multiple of $(1,-2,1)$.
Answer: I prefer to work directly from the definition:
Saying that 8 is an eigenvalue for this matrix means that there exist a non-zero vector, $\begin{pmatrix}x \\ y \\ z\end{pmatrix}$, such that
$\begin{pmatrix}3 & - 2 & 1 \\ -2 & 6 & -2 \\ 1 & -2 & 3 \end{pmatrix}\begin{pmatrix}x \\ y \\ z\end{pmatrix}= \begin{pmatrix}3x- 2y+ z \\ -2x+ 6y- 2z \\ x- 2y+ 3z\end{pmatrix}= 8\begin{pmatrix}x \\ y \\ z\end{pmatrix}= \begin{pmatrix}8x \\ 8y \\ 8z\end{pmatrix}$.
That is equivalent to the three equations 3x- 2y+ z= 8x, -2x+ 6y- 2z= 8y, x- 2y+ 3z= 8z, which reduce to the homogeneous equations -5x- 2y+ z= 0, -2x- 2y- 2z= 0, and x- 2y- 5z= 0.  The second equation is equivalent to x+ y+ z= 0 or z= -x- y.  Putting that into the first and third equations, -5x- 2y- x- y= -6x- 3y= 0 and x- 2y+ 5x+ 5y= 6x+ 3y= 0.  Those both reduce to y= -2x and then z= -x- y= -x+ 2x= x.  For any non-zero x, $\begin{pmatrix}x \\ -2x \\ x\end{pmatrix}= x\begin{pmatrix}1 \\ -2 \\ 1\end{pmatrix}$ is an eigenvector corresponding to eigenvalue 8.


What are some good methods for detecting movement using a camera? (opencv)

Question: I am looking for some methods for detecting movement. I've tried two of them. One method is to have background frame that has been set on program start and other frames are compared (threshold) to that background frame. Other method is to compare current frame (let's call that frame A) with frame-1 (frame before A). None of these methods are great. I want to know other methods that work better.
Comment: What sort of movement? Those two algorithms are basic and will work for simple motion detection.
Comment: Yes, what kind of movement? and why, in your case, it does not work great ?
Comment: @Science_Fiction: They will work for simple motion detection. But for example one I need to "reset" that background image each time and that's bothering me, and for example two if that object that was moving suddenly slows or stops it would't be detected on other frames.
Comment: What you can also do is compare two frame accumulators (e.g. accumulateWeighted with with different alphas )... But it is hard to answer without knowing the type of noise and movement.
Comment: @Science_Fiction: I am not expert in openCV or motion detection. Could you give me some examples of types of movement so I could choose one that I think I am looking for? Basically, this is what I am trying to achieve. I want to track (and count) cars and people that are passing through my street (Why? Because I am trying to learn new stuff and that looks fun thing to make). If that car stops he wouldn't be seen on other frames using that 2nd method. If there's wind and turns my cam, I would get totally wrong results. (Help!)
Comment: You've started with a pretty tough project in the realms of image processing if you are just starting out. Maybe try doing some blob analysis/detection for the vehicles.
Answer: Check this out:

Motion detection using Python
Motion tracking Python
Answer: Lucas-Kande method is something worth looking at.
Answer: Please go through the book Learning OpenCV: Computer Vision with the OpenCV Library
It has theory as well as example codes.


circunferências responsivas em lugares específicos

Question: Olá,
Eu estava a colocar circunferências e cima de pontos específicos de uma imagem mas eu gostava que elas reduzissem o seu tamanho mas sem sair da posição que eu quero, eu tentei usar % tambem tentei usar vw mas nunca fica parado do lugar especifico da imagem e dependendo da medida do monitor as circunferências ficam demasiado pequenas.
Eu queria saber qual era a melhor forma de colocar algumas circunferências responsivas num lugar especifico da imagem sem que elas andem de um lado para o outro com a resolução do brower.
Neste Exemplo eu queria que a circunferencia fica-se em cima do cigarro como fica em FullScreen mas que mante-se a mesma posição quando se reduzi-se o screen
O meu objetivo é fazer parecer que o circulo faz parte da imagem mas depois quando clicas no circulo aparece um pop-up
Codigo:

.imagensdesktop {
        display: flex;
    }

    .imagensdesktop .img-fluid {
        padding: 5px;
max-width: 100%;
height: auto;
    }

    #circulo-modal {
        border: solid white 2px;
        border-radius: 50%;
        position: absolute;
        z-index: 1000;
        top: 0;
        width: 4.5vw;
        height: 4.5vw;
    }

    .c-1 {
            margin-top: 18.5%;
margin-left: 12.5%;
    }

Comment: já tentou usar medidas em `%` no lugar de `vw`? *viewport* pode tbm ser influenciado por barras de rolagem
Comment: Coloca #img-1 {position: relative;width: max-content} e arruma novamente as porcentagens para colocar o círculo no lugar certo
Comment: @RicardoPontual ja tentei usar %, VW, ate com algumas pesquisas encontrei uma coisa chamada EW mas tambem nao funcionou
Comment: @hugocsl e em relação a circunferência para quando a imagem ir reduzindo o circulo ir reduzindo também para parecer que o circulo mantem o mesmo tamanho?
Answer: Solução:
Primeiro, coloque #img-1 com position:relative ou as porcentagens vão se aplicar com relação ao primeiro elemento que não tenha position:static. Neste snippet é o html, por isso só em "fullscreen" que o círculo se encaixa.
Sua imagem mede originalmente 622x967 pixels.
Posicionamento:
O posicionamento do div é dado pelo seu canto superior esquerdo.
Fazendo um quadrado na imagem original começando em 237,351 até 314,428 (para conter o circulo).
Temos o canto superior esquerdo deste quadrado estará a 100x237/622 = aproximadamente 38% da margem esquerda e 100x351/967 = aproximadamente 36% da margem superior.
Tamanho:
Este quadrado desenhado tem dimensões 77x77 pixels. Fazendo as proporções temos que o div do círculo é de 12% da largura da imagem e 8% da altura.
Seu CSS ficaria assim:

.imagensdesktop {
display: flex;
}

.imagensdesktop .img-fluid {
    padding: 5px;
    max-width: 100%;
    height: auto;
}

#img-1 {position:relative}

#circulo-modal {
    border: solid white 2px;
    border-radius: 50%;
    position: absolute;
    z-index: 1000;
}

.c-1 {
    top: 36%;
    left: 38%;
    width: 12%;
    height: 8%;
}

Comment: Funcionou perfeitamente! Obrigada pela ajuda e pela explicação!


How to Add Previous/Next Navigation on Teaser based on Views?

Question: I have created a teaser based on views but don't know how to add a previous/next navigation. I have tried Views Navigation but it is for node only. The one that I am looking for is similar to the previous/next navigation with numbers in the front page.
Any help is greatly appreciated.
Comment: Have you ever tried views_slideshow module it have the option for next previous
Answer: I think you're looking for a Pager, there are standard paging options in Views or you might need something more complicated like Pagerer or perhaps Views Simple Pager


Indexing matrix element member of struct

Question: I'm trying to index an element from a matrix, which has been declared by creating a vector of vectors inside a struct.
Here's my code:
#include <vector>
using namespace std;

const int MAX_DIM = 1000;

struct TestStruct{
    int MAX_DIM;
    vector<vector<int> > matrix (int MAX_DIM, vector<int>(int MAX_DIM));
};

int main(){
    TestStruct ts;
    ts.MAX_DIM = 100;
    ts.matriz[0][0] = 1;

    return 0;
}

While compiling I've recieved the following error:
test.cpp:14:17: error: invalid types '<unresolved overloaded function type>[int]' for array subscript
  mierda.matriz[0][0] = 1;

Btw, do you know any other "cleaner" way to declare the matrix (without using anything else than vector from the class Vector)?
Thanks in advance!
Comment: That doesn't declare a matrix, it declares a function.
Comment: s/matriz/matrix/
Comment: How am I supossed to declare a matrix, then?
Answer: The problem in your code and your logic is that you think the line:
vector<vector<int> > matrix (int MAX_DIM, vector<int>(int MAX_DIM));

Creates a matrix inside your struct.
In fact, you just declared a function named matrix that returns a vector<vector<int>. To have a member object inside your struct, you need to delete the parentheses, as such:
vector<vector<int> > matrix;

I assume you want to first specify the MAX_DIM value and then create a matrix based on that value. I would either recommend creating a constructor that takes an int as argument to assign that value to MAX_DIM and then create a matrix based on that value, or to create an initialise() function that needs to be called before you access the matrix.
First, preferable solution:
using namespace std;
const int MAX_DIM = 1000;

struct TestStruct{
    TestStruct(int MD){
        MAX_DIM = MD;
        matrix = vector<vector<int>>(MD, vector<int>(MD));
    }

    int MAX_DIM;
    vector<vector<int>> matrix;

};

int main(){

    TestStruct ts(100); // matrix 100 by 100
    ts.matrix[0][0] = 1; // works

    return 0;
}

Or, if you don't want to deal with constructors:
using namespace std;
const int MAX_DIM = 1000;

struct TestStruct{

    int MAX_DIM;
    vector<vector<int>> matrix;

    void initialise(){
        matrix = vector<vector<int>>(MAX_DIM, vector<int>(MAX_DIM));
    }

};

int main(){

    TestStruct ts;
    ts.MAX_DIM = 100; // specify the size
    ts.initialise(); // construct the matrix
    ts.matrix[0][0] = 1; // works again

    return 0;
}

Note that the first solution requires less code and is more readable inside the main function. If you choose the second one, it will be easy to forget to either assign value to MAX_DIM or to call initialise().


How to Update a numeric field with the SUM of the numeric field in a different table MS-ACCESS 13

Question: I have a supply inventory database with 3 tables. Main (Warehouse Stock), Supply Issue Table, and Supply Purchases Table. All three tables share the relationship ITEM #. Supply Issue and Supply Purchases both log  transactions (i.e. Item #, Quantity Issued or purchased). I need to have the Purchase and Issue tables update the total quantity in the Main Table
I created an update query to update the two fields in the main table(PQuantity/IQuantity). Then a third auto-calculated field (MQuantity) which is (PQuantity-IQuantity). I did it this way because I understood I couldn't run an update query for an auto-calculated field?
Here's the update query SQL for purchases:
UPDATE [MAIN (WAREHOUSE STOCK)]
INNER JOIN [Supply Purchases Table]
ON [MAIN (WAREHOUSE STOCK)].[ITEM #] = [Supply Purchases Table].[ITEM #]
SET [MAIN (WAREHOUSE STOCK)].PQUANTITY = +[Supply Purchases Table]![QTY  ADDED];

Here's the update query SQL for issues:
UPDATE [MAIN (WAREHOUSE STOCK)]
INNER JOIN [Supply Issue Table]
ON [MAIN (WAREHOUSE STOCK)].[ITEM #] = [Supply Issue Table].[ITEM #]
SET [MAIN (WAREHOUSE STOCK)].IQUANTITY = +[Supply Issue Table]![QTY ISSUED];

The problem with this is it will only total the last purchase or issue that was input. I also get "Type conversion" errors.
Am I making this too difficult?
Thanks!
Answer: You have to addQTY ADDEDto the old value ofPQUANTITYlike:
UPDATE
    [MAIN (WAREHOUSE STOCK)]
    INNER JOIN
        [Supply Purchases TABLE]
    ON
        [MAIN (WAREHOUSE STOCK)].[ITEM #]  = [Supply Purchases TABLE].[ITEM #]
    SET [MAIN (WAREHOUSE STOCK)].PQUANTITY = [MAIN (WAREHOUSE STOCK)].PQUANTITY + [Supply Purchases TABLE]![QTY ADDED];

But you should rethink you data structure, as usuallay you have only one table for transactions (IN/OUT) and compute the actual stock when needed. See Ms Featured Access Templates Inventory and Allen Browne AppInventory for some hints.
Comment: Tried this but for some reason PQuantity doubles up every time I enter a new record. Is there a string that resets the formula so it doesn't do this?


Scan/Record application's outgoing IP requests?

Question: How can I scan/record IP requests from a specific application or task? Could I do this purely in command line or is extra software required?
Answer: Wireshark is a very powerful tool for tracing connections and even examining packet content. By using the appropriate filters you can monitor all network activity of your application.


Number of possible configurations by shifting the '2's in $12121212$ to the right.

Question: I came up with this question while solving another combinatorics problem.

Let's say there is a number $12121212$. Define an operation as swapping any two adjacent digits if the left digit is $2$. (For example, swapping the $2$$nd$ and $3$$rd$ digit to give $11221212$ as a result, but swapping the $3$$rd$ and $4$$th$ digit is not allowed.) There is no limit on how many operations you can do on the number(no operation is also possible). How many possible numbers can be formed?

Questions

Is there a name to this kind of problems?
How can it be solved?
Extra: What if the original is not $12121212$ but some other numbers(like for example$121212121111111111$? Will this make the question very complicated?

My attempt
I am not sure how to approach this question. My observation is that the final configuration $11112222$ remains unchanged after any operations. So it seems that the first '$2$' originally at $2$$nd$ position moves to the $5$$th$  position, the first '$2$' orginally at $4$$th$ position moves to the $6$$th$ position and so on.
However, some of the cases are invalid but at least I know that number of possible configurations is less than $4\cdot3\cdot2\cdot1 = 24$. So a possible way will be to enumerate all possible configurations, but it is a pain because I cannot find a way to do it in an organised manner. Therefore, I am curious if there is a way to do it more efficiently and smartly.
Comment: Count the number of $1$'s to the right of each $2$ and associate such a sequence of results with a tuple.  In your example of `12121212` this would be $(3,2,1,0)$.  Convince yourself that any tuple corresponds to an arrangement and vice versa.  Further convince yourself that the tuple is weakly decreasing (*weakly in the sense each number is greater or equal to the next number in the tuple, not necessarily strictly greater*) and that every weakly decreasing tuple whose entries are all less than or equal to their corresponding entries in the original tuple correspond to possible final outcomes.
Comment: I mean 12121212 (or more generally 12 repeated) case, but I think the proof https://en.wikipedia.org/wiki/Catalan_number#Second_proof can be used for 121212121111111111 (but not a random one).
Comment: This all suggests an easy way to organize your thoughts for a brute force approach, listing things in numerical order... here: 3210, 3200, 3110, 3100, 3000, 2210, ... ,0000 yielding precisely $14$ different outcomes, corresponding to 12121212, 12121122, 12112212, ... 11112222 respectively for your original problem.  As for coming up with a formula to count the number of weakly decreasing sequences $(a_1,a_2,a_3,\dots,a_k)$ subject to $a_i\leq b_i$ for each $i$ for some given initial configuration $(b_1,b_2,\dots,b_k)$, I don't see a clever way right away how to do that.
Comment: @JMoravitz Just to make sure that I am understanding it correctly, The answer to the $12121212$ case will be $14$, right?
Comment: Not sure whether this is helpful. But for the $12121212$ case, the problem has another representation:
Find a number of 8-digit numbers satisfying the following 2 condition: 1.The digits of the integer consist of exaclty 4 copies of '1' and 4 copies of '2'.
2.if we remove the last k digits from the integer(where k is any positive integer less than 8), the resulting integer has at least many '1's as '2's
Comment: Isn't this the Catalan number? https://en.wikipedia.org/wiki/Catalan_number
Comment: @Naruki do you mean the $12121212$ case or the generalised version?
Comment: @Naruki I agree
Answer: Think of these strings as describing mountain paths from $\langle 0,0\rangle$ to $\langle 2n,0\rangle$, where $n$ is the number of $1$s (or $2$s): each $1$ corresponds to an up-step from $\langle x,y\rangle$ to $\langle x+1,y+1\rangle$, and each $2$ to a down-step from $\langle x,y\rangle$ to $\langle x+1,y-1\rangle$. Initially we have a path that looks like this:
             /\/\/\/\.../\

Each legal move consists in interchanging a down-step with the step to its immediate right. If that step is also a down-step, the path doesn't change. Otherwise a sequence \/ is converted to a sequence /\. We still have $n$ up-steps and $n$ down-steps, so the path still ends at $\langle 2n,0\rangle$, and an easy induction shows that no path obtainable in this way drops below the $x$-axis.
It takes a bit more work to show that every mountain path from $\langle 0,0\rangle$ to $\langle 2n,0\rangle$ that never drops below the $x$-axis is obtainable in this way, but once we have that, we're done: it's well-known that the number of such paths is $C_n$, the $n$-th Catalan number.
The idea is simple enough. Take any such mountain path $P$. Reading from left to right, find the first peak at a height greater than $1$. (If there isn't one, we're done: it's our initial path.) That peak consists of an up-step followed by a down-step; interchange those two steps. This interchange is simply the inverse of the legal move in the original procedure. Repeat this process until there are no more peaks of height greater than $1$. At that point you have the path
             /\/\/\/\.../\,

and $P$ can clearly be obtained from it by a sequence of legal moves.
Comment: I marked this as accepted. However, what if the string is more random, say $2211212212$? Is enumerating the only possible way?
Comment: @LearningMathematics: For a given starting string? Probably, though if the initial string is restricted to some fairly narrowly defined class of forms, it might be possible to come up with a closed form for the number of possible derived strings.
Comment: is there a way to prove that there is no closed form for the general case?


What is the expected sendmail behavior if RefuseLA and QueueLA have the same value?

Question: I came across a sendmail server with QueueLA and RefuseLA set to the same value (50).  I'm not sure why the previous admin would have done this.  Is there a legitimate reason for why someone would want to set that? How would sendmail behave in that scenario?
Based off of historical logs, it almost looks to me like it flops between the two enforcement behaviors.  I see some stuff where messages instantly get queued (stat=queued) and others where the incoming connection is rejected... but no clear indication of why one action was chosen over the other.
Comment: Are you talking about `sendmail.cf`, `submi,cf` or both?
Comment: @AndrzejA.Filip `sendmail.cf`(although the param was defined in `sendmail.mc`)
Answer: Setting QueueLA and RefuseLA to the same value makes some sense if you want to reduce number of sendmail states. It configures just two states "normal" and "full overload" with no states between.
RefuseLA rejects new incoming SMTP connections/sessions but sendmail may receive further messages over already existing connections - QueueLA will handle them. It is handy in default background delivery mode. Think about fast SMTP session sending multiple messages to many slow SMTP destinations and sendmail forking delivery process after receiving each message. [It is possible to limit number of messages accepted in single SMTP session.]
I would not use such configuration myself but IMHO it is mostly matter of personal preferences (preferred "style").  I sometimes use "Keep It Simple Stupid" approach myself :-)


How to achieve api proxying in production in vue 2?

Question: There is section3 in vuejs-templates docs which explains how to proxy api request in development mode. How to make similar for production. I mean when you run production version of app how to achieve a substitution of /api to 'http://domain.dev'.
On server side, the CORS is disable
So it looks that I am supposed to proxy request no matter development or production mode.
It works fine using proxyTable in dev but not working production version of app due to CORS restriction.
Any Help would highly be appreciated
Thanks
Answer:
On server side, the CORS is disable So it looks that I am supposed to proxy request no matter development or production mode

No. In production, there is no need to run the development server (you shoulnd't, under any circumstances!) Therefore, there's no need for proxying.
You just run your production backend server and serve the built assets from the <code>/dist</code> folder.
Comment: Yes, I tried to /dist folder but still getting the CORS error.  XMLHttpRequest cannot load 'http://domain.dev/v1/intervals'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mag.prod' is therefore not allowed access. showing this error
Comment: are you serving the assets from domain.dev? are domain, protocol (http / https) and port the same for the API server and the one serving the app?
Comment: No, I am serving the assets from mag.prod and both are served from HTTP only
Comment: Then what part of your code is connecting to `domain.dev/v1/internals` ? In your production build, all URLs should point to their production counterparts, there should be no development URLs left.
Comment: what if you add header `Access-Control-Allow-Origin: *` or `Access-Control-Allow-Origin: mag.prod` to your API response


Spring MVC - Multiple submit button to a Form

Question: I am trying to have 2 submit buttons post to a form, with each button action mapped to different controllers. Here are my mappings
@RequestMapping(value="/save", method=RequestMethod.POST, params="save")
@RequestMapping(value="/save", method=RequestMethod.POST, params="renew")

And my submit buttons look like these -
<input type="submit" name="save" class="button" value="Save" />
<input type="submit" name="renew" class="button" value="Renew" />

As you can see from my mapping, I am relying on the use of params to differentiate what button was clicked on. The problem is that it works 90% of the time but sometimes I get the exception below -
java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8090/myapp/save': {public java.lang.String com.myapp.SaveController.save(MyEntity,javax.servlet.http.HttpSession), public java.lang.String com.myapp.SaveController.saveAndRenew(MyEntity,javax.servlet.http.HttpSession)}
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:248)
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:194)

Strangely, when this happens and I re-submit the page, everything works fine afterwards. Is there a better way to achieve what I'm trying to do ?
Thanks!
Comment: not sure if its your problem, but keep in mind some browsers wont send the key/value pair of any buttons if the user submits the form via enter key or certain other methods besides clicking the button. So, make sure to assume a default action, which, for browser compatibility needs to be the action of the *first button* in the html source of that form.
Answer: if the form has these buttons specified:
input type="submit" class="button" name="save" value="Save"
input type="submit" class="button" name="delete" value="Delete"
input type="submit" class="button" name="cancel" value="Cancel"

you may direct to different url request according to button pressed with one controller.
for cancel button,
@RequestMapping(params = "cancel", method = RequestMethod.POST)
public String cancelUpdateUser(HttpServletRequest request) {
    return "redirect:/users.html";
}

what request mapping does is to scan post request if it contains params name = cancel.
for save button,
@RequestMapping(params = "save", method = RequestMethod.POST)
public String saveUser(HttpServletRequest request, @ModelAttribute User user, BindingResult result, SessionStatus status) {
    // validate your result
    // if no errors, save it and redirect to successView.
}

Answer: Why not:
<input type="submit" name="action" value="save" />

and then:
@RequestMapping(value="/save", method=RequestMethod.POST)
public String handlePost(@RequestParam String action){

    if( action.equals("save") ){
       //handle save
    }
    else if( action.equals("renew") ){
       //handle renew
    }

}

Comment: Seems a bit dangerous, as the `value` attribute on `input` tag contains the text of the button. I think i18n won't be your friend with this method.
Comment: I had problems with IE (10) not posting values consistently, & adopted your approach. Whilst not ultra-clean, it worked for me.  Cheers.
Answer: If You have more controller methods with the same @RequestMapping that differs only in params attribute, You have to explicitly write:

which parameter is supposed to be present in the request, e.g. params="save"
which parameter is NOT supposed to be present in the request, e.g. params="!save"

In Your case:
@RequestMapping(value="/save", method=RequestMethod.POST, params={"save", "!renew"})
@RequestMapping(value="/save", method=RequestMethod.POST, params={"renew", "!save"})

This should fix error Ambiguous handler methods mapped for HTTP path ...
See Spring Web API 4.0.x - RequestMapping#params
Answer: Just create one controller with a method similar to this
@RequestMapping(value="/save", method=RequestMethod.POST)
public String handlePost(@RequestParam(required=false , value = "save") String saveFlag , @RequestParam(required=false , value = "renew") String renewFlag){

if(saveFlag != null{
   //handle save
}
else if(renewFlag !=null{
   //handle renew
}

}

Answer: One more solution:
@RequestMapping(value="/save", method={RequestMethod.POST}, params={"save=Save"})
@RequestMapping(value="/save", method={RequestMethod.POST}, params={"renew=Renew"})


How to monitor trumpet right?

Question: I play trumpet in a band with: drummer, bass, guitar and vocals. Drums are loud enough, and everything else is amplified. Usually I play without amplification, because places are small enough, so audience hear me and I hear myself. But last gig we played in larger place, without many reflecting surfaces, and I barely heard myself. Audience heard me OK.
In general question is 'how to monitor a trumpet right?' I guess the simpliest answer is to place a mic and play in it. But in my situation - it is not always available: sometimes we have ~5 min to prepare, sometimes place is short on mics or mic stands. Also it seems quite unnecessary, because I don't need to amplify my sound.
I'm thinking of bying portable amplifier + mic + headset and play with it. Is it right decision? I don't have an option to buy mic+stand+amplifier and transport all these in a car, because I will need a car for that.
tl;dr
I cannot hear what I play over other instruments. I am occasionaly not able to request a microphone to monitor. So:

What is right way to monitor trumpet?
What can I do in my situation?
Answer: As an alternative option, which will be much lower tech and easier to deal with, you can look into a sound reflector---they're basically a piece of plexiglas on a stand that redirects some of your sound back to you. For examples, see here or here. With a little bit of ingenuity, you could even rig up your own with a few bucks at the hardware store.
Much less expensive and more manageable than dealing with another microphone and amp, especially considering that you say the audience can hear you without amplification.
As a slight cheat, you can somewhat emulate the effect by placing a music stand nearer to the bell of your trumpet (don't play directly into your music though!).
Answer: Used to play with a harp player who had the same sort of problem, and preferred to be in control of his own sounds. Problem solved with a mic, stand and wedge powered monitor, 60 watts was enough. Took a couple of minutes to set up, and was used both as his amp and/or 'foldback' at different gigs. Could even have used an in-ear monitor with the set up. It could also be DI'd into a p.a. if needed. You've realised by now that you can expect mics, etc. to be provided at some gigs, and get let down. That's the way it often is, so be prepared, be tooled up, and leave the stuff in the car if you don't need it - on those rare occasions... There are trumpet mics that clip on to the bell that may be better for you, and going wireless these days is pretty inexpensive.
Comment: Bear in mind that if you have an instrument-mounted clip-on mic it will always be a fixed distance from your bell, so you can't move away from the mic as you play louder, or move in closer for a more intimate sound. But depending on the type of music you play, that might not be an issue.
Comment: @BrianTHOMAS - given that you can't do that when playing without a mic anyway, it's not going to be too much of an issue. As you say, it depends.
Comment: Using mutes with a clip-on mic can be awkward too. Also with a clip-on there will be mechanical thumps due to valve action. Also, with a clip-on you're tethered via a cable (which can limit your freedom to move about on stage) or you have to rely on a wireless pack (flat batteries can be a pain). Also a clip-on changes the balance of the instrument, making the bell heavier. For all these reasons, if I had the choice I'd go for a directional mic on a stand over a clip-on.
Comment: @BrianTHOMAS - mutes may be problematic, but probably wouldn't be used; clip-ons have rubber mounts, so no mechanical noise; the very idea would be to have freedom of movement, and batteries aren't a big problem; clip-ons are only a few grammes. Playing at the same level as the audience ( no stage), I know that a mic on a stand isn't always a stable affair... Have you used a clip-on while playing trumpet? I haven't, but have worked with guys who do.
Comment: Actually, trumpet clips are placed on trumpet pipes, whereas mic is on extended "arm" and is faced before the bell, so mutes and valves clicks are not problem.
Answer: Start out by testing with passive noise control ear plugs. It will be strange in the beginning, but you get used to it. Noise diminishing ear plugs allows you hear yourself better as you hear the sound "inside" your head. In addition, it will save your hearing.
I give one link to an example ear plug, not to "plug" that type explicitly.
Comment: I don't know much about trumpet, but this sounds like a very plausible suggestion to me. I sometimes use my in-ear plugs _without any actual signal_, because this makes it much easier to hit the notes when singing backing vocals. (In fact I feel it even makes my _cello_ better audible, but that's likely just a psychoacoustic phenomenon.)
Answer: Don't fuss.   If you're audible to the audience without amplification, this isn't too big a problem.  If you need amplification, use the same monitors that everyone else uses.  If you play into a reflector, remember this is restricting what the audience hear.
Don't look for a complicated solution to a non-problem.  Particularly one that involves MORE amplification!

How to monitor trumpet right?


Messageboxes gone crazy

Question: I created a user control and i put a messagebox line in a timer to test some functionality. The good news is that the test told me exactly what i expected to hear, the bad news is that the messageboxes are spawning every 1ms even while the program isnt running. I removed the messagebox spawn line from the code from outside VS but I suspect the design mode has a compiled version of that control somewhere and is running the code. I cant recompile a new version since the messageboxes wont let me touch VS.. help?
Comment: CTRL+ALT+DEL is my suggestion...
Comment: Well, edit the project with Notepad or something and comment out the control so it doesn't get created at design time.
Comment: the problem isnt closing the program, its getting back to writing my code. Every time i load up the project the messageboxes start spawning again.
Comment: as stated i did that already
Answer: found the solution, i deleted the obj folder in the project. Needs a rebuild before design mode is functional again but works ok now.

Messageboxes gone crazy


CMake boost imported targets

Question: Can you explain me how should I use something like Boost::headers in my CMake file? I tried to utilize it somehow but is seems to work in different manner than I understand it.
cmake_minimum_required(VERSION 3.15)

project(Test)

find_package(Boost COMPONENTS asio REQUIRED)

add_executable(test main.cpp)

target_include_directories(test SYSTEM PUBLIC ${Boost_INCLUDE_DIR})
target_link_libraries(test PUBLIC Boost::headers)

This example does not work. It is caused by COMPONENTS asio. ASIO seems to be treated in other way because it is header only library.
Documentation says:

Boost::[C] - Target for specific component dependency (shared or static library)
[C] is lower-case

I can agree that ASIO may not be library in the terms of CMake's definition. Documentation emphasises that it must be either static or shared library. ASIO is header only so it is just a file to be included.
So let's try to use it in another way:
cmake_minimum_required(VERSION 3.15)

project(Test)

find_package(Boost REQUIRED)

add_executable(test main.cpp)

target_include_directories(test SYSTEM PUBLIC ${Boost_INCLUDE_DIR})
target_link_libraries(test PUBLIC Boost::headers)

Right now I am assuming that if CMake managed to find Boost, ASIO will be present. It is possible to perform configuration step, but when I try to build whole project it turns out that I am missing some dependencies. Boost::headers seems to be somehow unnecessary.
Unfortunately CMake's documentation is not the best I have ever seen. It is hard to get any information related with more complicated things.
Answer: The target to include the Boost headers is named Boost::boost not Boost::headers.
If you use that, you don't need target_include_directories(... ${Boost_INCLUDE_DIRS}) (note the S at the end of the variable). ${Boost_INCLUDE_DIR} without S is used in find_package to lookup the header files.
Boost::asio is a header only library and CMakes FindBoost.cmake module does not create targets for header only libraries.
When dealing with Boost::asio you need to add system and thread to your required modules in find_package and add Boost::thread and Boost::system to your target_link_libraries call. See https://think-async.com/Asio/AsioAndBoostAsio.html for a good explanation.
So your CMakeLists.txt would look like follows:
cmake_minimum_required(VERSION 3.15)

project(Test)

find_package(Boost COMPONENTS system thread REQUIRED)

add_executable(test main.cpp)

target_link_libraries(test PUBLIC Boost::boost Boost::system Boost::thread)

Edit: Boost::headers was introduced in CMake 3.15 and Boost::boost is now an alias to it.
Comment: A target combines properties for linker, compiler, and other tools. So it might have set a property containing the include path, another property containing the name of the library for build type Release, another one for build type Debug. Additionally properties may be set for compiler definitions and switches, for linker switches, ... So a target combines all that stuff in a single name. CMake will correctly propagate the settings to the tools is use. All you have to do is adding the target to the target_link_libraries call.
Comment: But why should one link against a header file? I cannot find anything about what this target does in general. Seems to does nothing at all.
Comment: According to https://cmake.org/cmake/help/latest/module/FindBoost.html `Boost::headers` is an alias. So it should work. Besides, when I want to use for instance Boost.Filesystem, I can `find_package(... filesystem)` and then I can link `Boost::filesystem` to my main target. It should handle all dependecies. I want to do the same thing with ASIO.
Comment: So what is the actual purpose of adding Boost::boost to target_link_libraries?
Comment: The `Boost::headers` target has been added with CMake 3.15 recently, I was not aware of that. AFAIK no targets are created in FindBoost module for header only libraries. So you either create a target on your own and populate all necessary properties or you add the dependencies manually.
Comment: In case you have header only Boost libraries without further dependencies you should add the target Boost::boost (or Boost headers) to the target_link_librares call. As most Boost libraries are header only and do not have additional library dependencies this case is quite common. See https://www.boost.org/doc/libs/1_71_0/more/getting_started/windows.html#header-only-libraries for a list of non header only libraries. Good examples are Boost/Any or Boost/Array

CMake boost imported targets


How to use HAProxy in load balancing and as a reverse proxy with docker?

Question: I am using HAProxy docker image to load share between multiple similar containers. It's working fine if I am using a single address like web.abc.com to query only the API containers, which is mapped to my localhost . But now I want to use api.abc.com too with this HAProxy config file .
So the scenario is going to be if I hit web.abc.com it will share the load of web application  container using round robin and show me the contents of these containers and  if I  hit api.abc.com it gives me access of those containers which have the API  .
I have tried multiple config changes with my haproxy.cfg , but it's not working .
This is my docker-compose file, and this is the haproxy.cfg I am using , which is obviously not working
Is this scenario even possible with HAProxy ? Help me.
Comment: You should update your question to show the output of whatever tests you are carrying out that demonstrates "it's not working".
Answer: I would make use of https://github.com/jwilder/docker-gen to generate HAProxy configuration on container start / stop.
You can take a look on the use of it in nginx + letsencrypt use case : https://github.com/JrCs/docker-letsencrypt-nginx-proxy-companion


FIWARE IoT Agent-UL freezes up when delete a device that does not exists

Question: I have problems when I try to remove a FIWARE IoT Agent UL device using the REST API.
If I try to delete a device that exists, the service returns an HTTP code 204 and everything works as expected.
However, if I try to delete a device that does NOT exist, the service "hangs up" and I do not get any response from it.
This is the output of the node app, related to the service request that I made:
<code>time=2018-03-22T14:30:39.225Z | lvl=DEBUG | corr=9dff81b8-2cbe-4236-9bdc-  82b912df1ff0 | trans=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | op=IoTAgentNGSI.GenericMiddlewares | srv=foo | subsrv=/bar | msg=Request for path [/iot/devices/641tvjjr] from [localhost:4061] | comp=IoTAgent
time=2018-03-22T14:30:39.226Z | lvl=DEBUG | corr=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | trans=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | op=IoTAgentNGSI.DeviceService | srv=foo | subsrv=/bar | msg=Removing device register in Device Service | comp=IoTAgent
time=2018-03-22T14:30:39.226Z | lvl=DEBUG | corr=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | trans=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | op=IoTAgentNGSI.MongoDBDeviceRegister | srv=foo | subsrv=/bar | msg=Looking for entity with id [641tvjjr]. | comp=IoTAgent
time=2018-03-22T14:30:39.228Z | lvl=DEBUG | corr=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | trans=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | op=IoTAgentNGSI.MongoDBDeviceRegister | srv=foo | subsrv=/bar | msg=Entity [641tvjjr] not found. | comp=IoTAgent
time=2018-03-22T14:30:39.229Z | lvl=ERROR | corr=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | trans=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | op=IoTAgentNGSI.Alarms | srv=foo | subsrv=/bar | msg=Raising [MONGO-ALARM]: undefined | comp=IoTAgent
time=2018-03-22T14:30:39.230Z | lvl=ERROR | corr=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | trans=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | op=IoTAgentNGSI.DomainControl | srv=foo | subsrv=/bar | msg=TypeError: Cannot read property 'service' of undefined | comp=IoTAgent
time=2018-03-22T14:30:39.230Z | lvl=DEBUG | corr=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | trans=9dff81b8-2cbe-4236-9bdc-82b912df1ff0 | op=IoTAgentNGSI.DomainControl | srv=foo | subsrv=/bar | msg=response-time: 5 | comp=IoTAgent
</code>
I'm working with a single service, with values of Fiware-Service: "foo" and Fiware-ServicePath: "/bar", devices in that service and the default agent configuration file. Also, I am using the 1.6.0 release of IoT Agent UL, which by the way is the latest version.
Everything else works correctly, device creation, devices listing, send measurements, etc. Everything except the elimination of a device that does not exist.
Has this happened to someone? It seems very strange to me and I can not believe that it is the first person that tries to erase a device that does not exist.
Thank you in advance
Answer: For all those who share the same question as me:
Apparently it's an open issue in node lib project.

the api should return a 404, but it seems that an exception is not capture somewhere and because of that infinite response time is caused.

Fortunately there is a pull request of the same guy who report the issue which fix it. In conclusion may be in next release it the problem will be resolved.