Suitable data structure for fast search on sets. imput: tags, output: sentence

Question: I have the following problem.
I get 1-10 tags, related to an image, each have a probability of existence in image.
inputs: beach, woman, dog, tree ...
I would like to retrieve from database an already composed sentence which is most related to the tags.
e.g:
beach -> "fun at the beach" / "chilling on the beach" ....
beach, woman -> "woman at the beach"
beach, woman, dog - > none found!
take the closest exist but consider probability
lets say: woman 0.95, beach 0.85, dog 0.7
so if exist take woman+beach(0.95, 0.85) then woman+dog and last beach+dog, the order is that higher are better but we are not summing.
I thought of using python sets but I am not really sure how.
Another option will be defaultdict:
db['beach']['woman']['dog'], but I want to get the same result also from:
db['woman']['beeach']['dog']
I would like to get a nice solution.
Thanks.
EDIT: Working solution
from collections import OrderedDict
list_of_keys = []
sentences = OrderedDict()
sentences[('dogs',)] = ['I like dogs','dogs are man best friends!']
sentences[('dogs', 'beach')] = ['the dog is at the beach']
sentences[('woman', 'cafe')] = ['The woman sat at the cafe.']
sentences[('woman', 'beach')] = ['The woman was at the beach']
sentences[('dress',)] = ['hi nice dress', 'what a nice dress !']

def keys_to_list_of_sets(dict_):
    list_of_keys = []
    for key in dict_:
        list_of_keys.append(set(key))

    return list_of_keys

def match_best_sentence(image_tags):
    for i, tags in enumerate(list_of_keys):
        if (tags & image_tags) == tags:
            print(list(sentences.keys())[i])

list_of_keys = keys_to_list_of_sets(sentences)
tags = set(['beach', 'dogs', 'woman'])
match_best_sentence(tags)

results:
('dogs',)
('dogs', 'beach')
('woman', 'beach')

This solution run over all keys of an ordered dictionary,
o(n), I would like to see any performance improvement.
Comment: As far as I understand your issue, you don't know what data structure to choose to store your tag pairs?
Comment: How big is the database? how many sentences and keywords does it contain? Is it static or does it change dynamically adding and removing new sentences?
Comment: static, not changing.
Comment: 1000 sentences and growing...
Comment: @SamperMan I don't really know what I don't know. I don't have a proper solution for both storing and retrieving.
Comment: The find done once in few seconds, but this application runsX500 instances, so it need to be not so slow.
Answer: What seems to be the simplest way of doing this without using DBs would be to keep sets for each word and take intersections.
More explicitly:
If a sentence contains the word "woman" then you put it into the "woman" set. Similarly for dog and beach etc. for each sentence. This means your space complexity is O(sentences*average_tags) as each sentence is repeated in the data structure.
You may have:
>>> dogs = set(["I like dogs", "the dog is at the beach"])
>>> woman = set(["The woman sat at the cafe.", "The woman was at the beach"])
>>> beach = set(["the dog is at the beach", "The woman was at the beach", "I do not like the beach"])
>>> dogs.intersection(beach)
{'the dog is at the beach'}

Which you can build into an object which is on top of defaultdict so that you can take a list of tags and you can intersect only those lists and return results.
Rough implementation idea:
from collections import defaultdict
class myObj(object): #python2
    def __init__(self):
        self.sets = defaultdict(lambda: set())

    def add_sentence(self, sentence, tags):
         #how you process tags is up to you, they could also be parsed from
         #the input string.
         for t in tags:
             self.sets[tag].add(sentence)

    def get_match(self, tags):
         result = self.sets(tags[0]) #this is a hack
         for t in tags[1:]:
             result = result.intersection(self.sets[t])

         return result #this function can stand to be improved but the idea is there

Maybe this will make it more clear how the default dict and sets will end up looking in the object.
>>> a = defaultdict(lambda: set())
>>> a['woman']
set([])
>>> a['woman'].add(1)
>>> str(a)
"defaultdict(<function <lambda> at 0x7fcb3bbf4b90>, {'woman': set([1])})"
>>> a['beach'].update([1,2,3,4])
>>> a['woman'].intersection(a['beach'])
set([1])
>>> str(a)
"defaultdict(<function <lambda> at 0x7fcb3bbf4b90>, {'woman': set([1]), 'beach': set([1, 2, 3, 4])})"

Comment: I find this option as a good solution, but I would change one thing:
Instead of sentances I will put numbers, each number is a represantaion of a sentence in a list i.e. my_list[1] = 'dog at the beach', this way I will save memory.
Comment: We do miss the probability part
Comment: I forgot to mention that this solution doesn't address that, as I did not understand your intent. Numbers would speed it up, you could also wrap an object around each string, which may or may not be good depending on your problem.
Comment: I will post a solution based on your answer with the probability implemented.
Comment: I do got into situation where a sentence must have beach and woman but will not be valid for beach\woman by itself.
Answer: It mainly depends on the size of the database and on the number of combinations between keywords.  Moreover, it depends also on which operation you do most.
 If it's small and you need a fast find operation, a possibility is to use a dictionary with frozensets as keys which contain the tags and with values all the associated sentences.
For instance,
d=defaultdict(list)
# preprocessing
d[frozenset(["bob","car","red"])].append("Bob owns a red car")

# searching
d[frozenset(["bob","car","red"])]  #['Bob owns a red car']
d[frozenset(["red","car","bob"])]  #['Bob owns a red car']

For combinations of words like "bob","car" you have different possibilities according to the number of the keywords and on what matters more. For example

you could have additional entries with for each combination
you could iterate over the keys and check the ones that contain both car and bob
Comment: What if you want ["bob", "car"] as a lookup?
Comment: It depends, if the space is not an issue (i.e., small amount of keywords) you could have additional entries with all the combinations, otherwise iterating over the keys and check the ones that contain both car and bob.


Grouping or Counting after a Sum

Question: Using Oracle/SQL, I am looking for a way to count the number distinct IDs above or below a specified value following a sum. For example, I need to find how many customers have ordered $1,000 or more in goods last year, regardless of whether it was in one large order or several smaller orders. I don't need to identify each customer specifically, just find the total number of customers over this amount.
So far I am able to find the total of orders with:
select sum (Order_Amount), Customer_ID
from table.orders_placed
where year = 2013
group by Customer_ID
order by Customer_ID
I can also expand it doing this:
select count (dinstinct Customer_ID)
from(
    select sum (Order_Amount), Customer_ID
    from table.orders_placed
    where year = 2013
    group by Customer_ID
    order by Customer_ID
    )

but this just gives me the total number of distinct Customer_ID. Any other argument that I add to try to narrow what the "count" gives me results in an error. How can I specify that I want the total Order_Amount of $1,000 or more?
Comment: Why not use a `HAVING`?
Comment: I would consider a subquery.
Comment: I hadn't appreciated how similar ORACLE was to MySQL
Comment: Did you try giving alias to aggregated column and then use that alias to filter?
Answer: Try (no need to order by in inner query)
select count (dinstinct Customer_ID)
from(
   select sum (Order_Amount) total_order_amount, Customer_ID
   from table.orders_placed
   where year = 2013
   group by Customer_ID
) where total_order_amount > 1000

OR with Having
   select sum (Order_Amount) total_order_amount, Customer_ID
   from table.orders_placed
   where year = 2013
   group by Customer_ID
   having sum(order_amount) > 1000

Answer: Use a HAVING clause to restrict the results of the grouping:
select sum (Order_Amount) as Total, Customer_ID
from table.orders_placed
where year = 2013
group by Customer_ID
having sum (Order_Amount) >= 1000

Then you can use this as a subquery to perform your aggregation and filtering.

Grouping or Counting after a Sum


Are heat maps "one of the least effective types of data visualization"?

Question: Question: When (for what types of data visualization problems) are heat maps most effective? (In particular, more effective than all other possible visualization techniques?)
When are heat maps least effective?
Are there any common patterns or rules of thumb one can use to decide whether or not a heat map is likely to be an effective way of visualizing the data, and when they are likely to be ineffective?
(Principally I have in mind heat maps for 2 categorical variables and 1 continuous variable, but am also interested in hearing about opinions regarding other types of heat maps.)
Context: I am taking an online course about data visualization, and right now they are discussing ineffective and over-used plot types. They already mentioned dynamite plots and pie charts, and the reasons given for why those are ineffective and why there are better alternatives to them were clear and convincing to me. Moreover, it was easy to find other sources corroborating the given opinions about dynamite plots and pie charts.
However, the course also said that "heat maps are one of the least effective types of data visualization". A paraphrasing of the reasons why are given below. But when I tried to find other places on Google corroborating this view point, I had a lot of difficulty, in contrast to looking up opinions about the effectiveness of pie charts and dynamite plots. So I would like to know to what extent the characterization of heat maps given in the course is valid, and when the factors against them are least important and most important for a given context.
The reasons given were:

It is difficult to map color onto a continuous scale.
There are some exceptions to this rule, so this is not usually a deal breaker, but in the case of heat maps, the problem is particularly difficult, because our perception of a color changes depending upon the neighboring colors. Thus heat maps are not well-suited for seeing individual results, even in small data sets. Which leads to:

Answering specific questions using a table look-up method is generally not feasible, since it is impossible to infer with sufficient accuracy the numerical value corresponding to a given color.

Often the data are not clustered in such a way to bring out trends.
Without such clustering it is often difficult or impossible to infer anything about general overall patterns.

Heat maps are often only used to communicate a "wow factor" or just to look cool, especially when using a multicolor gradient, but there are usually better ways to communicate the data.

Plotting continuous data on a common scale is always the best option. If there is a time component, the most obvious choice is a line plot.
Comment: The criticism of "heat maps" comes down to the last line of (4): exactly what are these "better ways" to communicate? (If there are no better ways, then (1)-(3) are scarcely relevant.)  If the purpose literally is to communicate *the data*, then obviously there are better ways: write down the numbers. The purpose of a visualization, though, is rarely to communicate the data: instead, it is to support  an *interpretation* or send a *message.*  What interpretations does your source have in mind and what does it claim are the better ways to present those interpretations?
Comment: The color is superfluous (and, admittedly, poorly chosen--it's just the default image colormap in R), but [here is an example about Minesweeper play](https://math.stackexchange.com/a/62714/7003) that I worked up several years ago. I found the heatmap immediately illuminating in that it reveals structure about the problem that becomes intuitively clear once you see it and think about it for a moment, but which is not immediately obvious (to most people) prior to seeing the plot.
Comment: @whuber As a supplement for that - one very nice thing about heat maps is that in many cases it's easy to supplement them by displaying the raw data (perhaps appropriate rounded) directly on each tile. Even using conditional formatting for the background colour of cells on a spreadsheet is a very effective, and very common, "heat map" of sorts, in which context it is hard to see how they can be improved upon.
Comment: My comment pertains only to critique 1. It is correct that color (hue) does not map to an ordered scale psychologically although it does physically (wave length). However, by adding a redundant dimension such as brightness  can make them more easily interpreted. You could have dark higher than light but use colors such as light blue and dark red.
Comment: Depends on the context. [Here's a great example](https://ux.stackexchange.com/q/105899/44275) of valuable, actionable information gained from a heat map, for which I can think of no other more convenient or useful data visualization type.
Comment: I think point (1) is partly related to the fact that some default heatmap colour scales like jet look discrete when they're supposed to be continuous. Newer colour scales like `viridis` decrease the problem somewhat (see [here](https://stats.stackexchange.com/questions/223315/why-use-colormap-viridis-over-jet))
Comment: Regarding the case of image analysis/classification, heatmaps come in quite handy and are intuitively interpretable. Great examples for the use of heatmaps in image classification can be found here http://www.heatmapping.org/
Comment: @cardinal I think what you're showing is that heat maps are good at showing structure.  The exact values in your minesweeper chart don't really matter, the structure matters and instantly reveals something I hadn't realized--that you expose more cells with an edge click.
Comment: @Chill2Macht Am I correct to assume that you want the answer to focus on a heatmap with the two categorical variables in the axes and a continuous variable plotted as a `rectangle` mark and encoded via `color`? Here is an example on the [vega-lite's editor](https://vega.github.io/new-editor/?mode=vega-lite&spec=rect_heatmap). More specifically, what kind of categorical variables do you mean: `nominal` or `ordinal` ? For `nominal`, you can have latent variable which sorts the order of categories drawn in the axis.
Comment: @Chill2Macht, with nominal variables on the axes, the challenge you need to take care of in a heatmap is how to order the individual categories. For example, you could order the categories by alphabet, by the category count or by some other quantitative variable. Hopefully there's a natural way to order them - domain knowledge is key. Anyhow, the way you order them (or don't order them) will allow you to detect a pattern (or not). However, in this particular case, you do face exactly the same challenge when designing a two-dimensional table.
Comment: Can you post a link to that course? I'd like to see it
Comment: @Chill2Macht: I only meant tell us the name and vendor of the course. It sounds useful.
Comment: Can someone explain to me how this isn't either opinion based or too broad?
Comment: @spacetyper First, only questions which are _primarily_ opinion-based are off-topic. Data visualization is at the intersection of statistics and design, so because of the design component there is necessarily some degree of opinion, but that does not preclude there being best practices and objectively verifiable principles. So even if the question were about data visualization in general (which it is not), it would still not be primarily opinion-based. So you might still worry that the question is too broad. However, the question is not about the entirety of data visualization in general.
Comment: In fact, the question is about heat maps, and not only that, heat maps for 2 categorical variables and 1 continuous variable at that, which is a substantial restriction. Moreover, the question is about identifying the type of plots for which there are objectively-verifiable principles and best practices for using or not using heat maps (with 2 categorical variables or 1 continuous variable). Which again is another restriction. The question also lists 4 specific objections to be either refuted or supported. Which is yet another (a fourth) restriction of the question's scope.
Comment: I agree that if one only read the question title and nothing else that they might not appreciate any of the nuances I've mentioned above. But the title is supposed to be short and capture attention for the question as a whole -- it cannot always be representative of the question's entire essence. So it hardly makes sense to hold the question accountable for answerers or commenters who only read the title and not the question itself. You do appear to be correct that this might be happening unfortunately.
Comment: @g3o2 I imagine I mean nominal, since ordinal variables can kind of be thought of as quantized continuous variables in many cases (see leftaroundabout's answer). Also since the use of heatmaps which I am most familiar with, for microarray/gene expression data, probably uses nominal categorical variables (for the genes). Also the instructor of the course was trained as a bioinformatician, it seems that may have been what he had in mind when criticizing heat maps.
Answer: There is no such thing as a "best" plot for this or for that.
How you plot your data depends on the message you want to convey. Commonly used plots have the advantage that users are more likely to be able to read them. Nevertheless, that does not mean that they are necessarily the best choice.
Regarding heat maps, I've ordered my response by the supposed arguments against them.
1) If you don't trust color as an encoding channel, use brightness instead, with a scale encompassing dark gray to light gray "color" tones. Most often, you want to bin continuous variables (also see 5), so you can keep the number of colors low and make it easier to decode by users. This is not a must though. Take a look at this example, in which the continuous variable is not binned.
2) Certainly, they should not be used as an alternative to look up precise values. Heat maps should primarily be used to illustrate patterns, not to replace tables.
3,4) I don't see how this would be related to heat maps only.
5) Heat maps are ideally but not necessarily used with discrete variables. For continuous variables, heat maps can be used as a sort of two-dimensional histogram or bar chart, with proper binning, as well as brightness as an encoding channel.
Comment: @gung Not really, IMO. It has no connotations, unlike pace - it just means in addition, addendum, in reference to, as for... Not to mention it was universal in the West, coming from Latin and used extensively in theology and scientific and political literature, among other things. In a (mail) dialog, the two parties would use it to reference the arguments to each of the points. It seems to be falling into disfavour as written language gets trimmed, though. The usual replacement is just using "1.1" instead of "Ad 1.1", which can be a bit confusing and seems a bit rude to me, but oh well.
Comment: Awesome answer! Except I don't know what "Ad" means. Latin? Abbreviation?
Comment: Thanks! "ad" means "on" or "concerning",  I guess it comes from Latin.
Comment: Also remember to gamma-correct your brightness-based heat maps.
Comment: I've never seen "ad" used that way either (cc, @xan). From your description, I think I might use [pace](https://www.merriam-webster.com/word-of-the-day/pace-2012-04-23).
Answer: Someone can not say Heat Map is the least effective type of visualization. I would rather say it depends on your requirement. In some cases Heat maps are very useful. Let's say you have to make a report on crime in a country state-wise (or city-wise). Here you will have a huge data set which can have time dependencies.
Similarly, let's say you have to prepare a report on electricity consumption for cities. In these cases you can easily visualize through Heat map. It will make more sense and be less cumbersome.
So, in a nutshell, if you have lots of continuous data and you want to make a report which can pin-point the answers quickly then Heat map is best.
Comment: For energy consumption, there often is no better plot than a heatmap : http://argustech.be/wp-content/uploads/2012/04/heatmap.png Week-ends and work hours jump right at the viewer. You can see the base load, you can see peaks, you can see when they happen. You can detect any weird pattern in a few seconds, for example if some electrical device is always on or starts too early or too late.
Comment: @Amelian: Thanks! Wayback machine to the rescue! https://web.archive.org/web/20160508090343/http://argustech.be/wp-content/uploads/2012/04/heatmap.png
Comment: @EricDuminil letting you know that your link seems to be broken!
Answer: As aforementioned by others, it is really improper to say that heat maps are always ineffective. Actually, they are quite effective in many instances.
For example, if you want to visualize 4D data, it is simple enough to do the first three dimensions in many plotting software. However, the whole concept of 4D is pretty difficult to conceptualize at all. What is the "4th" direction/dimension?
That's where a heat map may be effective, because it will allow to plot the first three dimensions on coordinate axis, and the fourth can be visualized by stacking a heat map onto your plotted plane (or line, but that's less likely).
Bottom line is that you need context. What are you looking for in your visualization? Also, as a fellow self-teacher, I can tell you that these online courses tend to be very trivial and unhelpful. You are much better off only using them when you are looking for information/help on specific topics rather than looking to be taught about a whole subject.
Best of luck anyway though.
Answer: Critique 1 in the original question covers the biggest drawback - that it is difficult for someone reading the heat map to decode the quantitative information that is conveyed. Consider an xy-scatter plot or dot plot, where the underlying quantity is directly related to the distance on the chart - very straightforward for interpretation.
In a heat map, on the other hand, the person reading the chart is at liberty to interpret 10% 'redder' or 'darker' to their own satisfaction. On top of that is the problem of differing abilities of people to discern colour and shade to begin with. These are genuine disadvantages, but they are not universally fatal.
The third critique, by contrast, seems to inadvertently identify an occasion when heat maps are especially useful - when the data is clustered on a 2D plane so that similar values in a third dimension show as patches of a particular shade or colour. So while heat maps are ineffective at some things, they are useful for others, and they should stay in your bag, in the same way that golfers often carry pitching wedges or similar despite their being useless for driving or putting, or carpenters don't disregard hammers because they are no good for cutting wood.
In general visualising data should be seen as iterative activity that will take some time as you try a number of visualisations that bring out the important features of the data, including trying more than one kind of visualisation, and then experimenting to find the best settings within particular choices. Nor should it be assumed that the result will be one visualisation - sometimes a number of visualisations of data will needed to highlight multiple important features of the data. In this context, there will be times where for particular features of particular data sets, the heat map will be the most effective, and communicating clusters as described may be one of those times. Overall, there will be frequent occasions where a single visualisation cannot do everything, and more than one will be required.
Answer: Heat maps are great at providing a simplistic view of multiple variables from  a time series perspective- the data can be absolute changes over time or  standardized using Z scores or other means to examine variables with different measurements intervals or relative changes of subgroups. It does provide a very visually noticeable view that one can spot correlations- or inverses and replaces a multitude of graphs. They can also be used in preprocessing to assess possible dimensionality reduction- i.e. Factoring or PCA.
The bad- intervening variables and other factors can become hidden and passed by when using this approach to spot correlations. The same hidden aspects do occur with line graphs- however given the large number of variables- my experience is that heat maps brings so much information that a user does not consider the intervening aspects nor other hidden factors.
This from a a data scientist from a progressive economist perspective with 20 years in the field producing data  and tasked at educating the general public with such data.
Answer: By nature, a heat map displays data with two continuous independent variables (or, not quite equivalently, one independent variable from a two-dimensional vector space), and one continuous dependent variable. For data of that type, a heat map is definitely one of the most effective types of data visualisation. Yes, it has its problems, but that's inevitable: you really have only two dimensions to work with and a three-dimensional space cannot be mapped to that in a structure-preserving way, therefore you need a hack like mapping one dimension to colour or drawing contour lines etc..
If the independent variables are categorical, the heat map immediately makes much less sense: there's generally no reason why a categorical variable would map onto a real axis. In fact a categorical variable, by definition, does not come with any pre-determined topology, or we might say, with the discrete topology. Now unlike $\mathbb{R}^2$, which is only homeomorphic to another two-dimensional space, the cartesian product $X\times Y$ of two discrete spaces is actually homeomorphic to any space of the cardinality $|X| \cdot |Y|$, which is finite for a categorical variable – in other words, the cartesian product of two categorical variable can be considered as a single categorical variable! And in that light, you can just as well use other plots, which don't have the problems of a heat map.
If you find yourself in a situation where a heat map over two categorical variables appears useful, it's an indication that these are probably not really categorical variables, but rather quantised continuous variables.
Comment: This answer is interesting, but I think gives short shrift to the notion of using heatmaps with categorical variables. For example, one might rank categorical levels by their counts (or some other relevant sorting variable) and then use a heatmap to visualize the joint distribution or some other quantity that varies with the joint categorical levels. This can be tied to *copulas* (and generalized notions thereof). Such visualizations, when done well, can reveal real structure in the data which would otherwise be very difficult to detect. (...)
Comment: (...) And, such an approach is independent of any (direct) notion of embedding the categorical levels into a Euclidean space.
Comment: I was wondering if you have any comment on the practice of using heat maps for gene expression/microarray data then -- these would seem like cases of using heat maps for 2 categorical and one continuous variable for which the categorical variables can't really be interpreted as quantized continuous variables. Or I guess heat maps for correlation matrices of categorical variables in general.
Answer: Heatmaps are advantageous over scatterplots when there are too many data points to view on a scatterplot. This can be mitigated in a scatterplot using translucent data points but beyond a certain threshold it becomes better to summarize the data.
In this blog post a compelling example of scatterplots being hard to interpret is given.

A scatterplot can only visually represent density up to a certain threshold - the threshold of "points everywhere"...
Plot density, not points
The solution is to plot the binned point density rather than the points themselves. We already know this method in one dimension as the histogram.
In two dimensions, there are multiple ways of doing it. The bin shapes can be taken from any method of uniformly tiling the plane, such as squares or hexagons. For each tile, the number of data points inside the tile are counted. The tile is then assigned a color according to the number of points.

A similar statement from the ggplot2 docs on heatmap of 2d bin counts:

This is a useful alternative to <code>geom_point()</code> in the presence of overplotting.

In the docs of <code>geom_point()</code>:

Overplotting
The biggest potential problem with a scatterplot is overplotting: whenever you have more than a few points, points may be plotted on top of one another. This can severely distort the visual appearance of the plot. There is no one solution to this problem, but there are some techniques that can help. You can add additional information with <code>geom_smooth()</code>, <code>geom_quantile()</code> or <code>geom_density_2d()</code>. If you have few unique x values, <code>geom_boxplot()</code> may also be useful.
Alternatively, you can summarise the number of points at each location and display that in some way, using <code>geom_count()</code>, <code>geom_hex()</code>, or <code>geom_density2d()</code>.
Another technique is to make the points transparent (e.g. <code>geom_point(alpha = 0.05)</code>) or very small (e.g. <code>geom_point(shape = ".")</code>).


Resolving the Standard new/delete operators

Question: Please see this question for some context: Linking unreferenced libraries breaks my program
I have the following program:
#include <iostream>

int main( int argc, char* argv[] )
{
    std::cout << "Hello world" << std::endl;

    int *p;
    p = new int(3);
    std::cout << *p << std::endl;
    delete p;

    return 0;
}

It works fine until I link to third-party libraries. When I link to the Abaqus libraries that I'll need in a much larger program, the above program crashes when trying to run delete p;. Using Dependency Walker, I found that the call to operator new is linked to an operator new definition provided by Abaqus. However, the call to operator delete is linked to the standard definition.
I have replaced new/delete with ::new/::delete and get the same result.
Is there a way to resolve the standard new/delete operators? Alternatively, can I force Visual Studio to link to the correct (standard) definition of these operators?
Comment: Does [this](http://stackoverflow.com/a/4163102/241631) fix your problem? It's hard to believe that the library is overriding `::operator new` without doing the same for `::operator delete`.
Comment: @Derek Well, that kinda explains the problem. There should be some other Abaqus supplied lib where the corresponding `operator delete` definition resides. You'll probably need to contact their support if you can't find anything about this in the documentation.
Comment: @Praetorian Not quite, although it is relevant. Here I am not trying to use the Abaqus ODB API (yet). I believe that Abaqus has defined both `new` and `delete`. In that case this is more of a linking issue.
Comment: @Derek: Seems to me that Praetorian is right - you can't use `new` or `delete` that is part of the Abaqus library, until you have called the Abaqus init function. Since the standard library is linked after Abaqus, you will get the Abaqus version, rather than the one in the C runtime. Which seems a rather loony way to do things, but hey, I don't work for Abaqus, so I don't know what they were smoking, drinking or thinking when they came up with that solution - maybe it fixes some other problem that is really difficult to fix in some other way.
Comment: @MatsPetersson I'm sorry, maybe my question is unclear. I've spent many months working with the Abaqus ODB API, so I am very familiar with the proper initialization of it. Please see my code. I'm *not* trying to use the Abaqus ODB API. I don't want to use the `new` or `delete` operators provided by Abaqus -- those should not be polluting the global namespace. However, I have found that their implementation *is* in the global namespace and I want to get around their implementation. Does this help?
Comment: @MatsPetersson Perhaps, it is worth mentioning that yes, you and Praetorian are correct. I'm *not* initializing the Abaqus ODB API. If I initialize the Abaqus ODB API properly, my code is fine under Abaqus 6.9 EF1. However, it does not work with Abaqus 6.12. That is the larger problem at hand. I'm receiving the same error message using Abaqus 6.12 and the above code as I'm receiving in my large program (regardless of initialization). It's rather confusing :).
Comment: Yes, and I'm saying that according to the linked answer, you will get an error message/crash from simply calling `new` when you have linked with Abaqus, whether you are using the services of that library or not, because they replace `new` and `delete` (which is nasty), causing your application to crash if it hasn't called the Abacus init function.
Comment: @MatsPetersson All right. I'll reread that answer. However, I've had great success in the past using `new` and `delete` with Abaqus 6.9 EF1.
Comment: Well, I know nothing about Abaqus - I'm just reading the answer to the other question, and seeing something that looks like the same thing. It may of course be that you are having a different problem. But it's also worth noting that the Abaqus appears to indicate that ANY allocation using `new` will crash - this means a global `std::string s = "A rather long string goes here .....";` in your main code could cause this to happen, because it's using `new` before you hit main. Again, I think this is a very bad design, but I'm sure Abaqus had some reason for this.
Comment: Using advice I received here: http://stackoverflow.com/questions/12408787/call-a-function-before-static-member-allocation I can guarantee that the Abaqus ODB API is initialized properly. I get the same error using Abaqus 6.12 regardless of whether or not I initialize the Abaqus ODB API.
Comment: @MatsPetersson I believe everything boils down to Visual Studio linking the `new` to the Abaqus `new` and the `delete` to the standard implementation. These cannot be used together, but since the Abaqus `new` is in the global namespace, Visual Studio doesn't know any better. I appreciate your comments!
Comment: Yes, that's what I think too - and that's why I'm saying it's not a great thing to do. Of course, there can only be ONE ::new function, and to allow your application to replace it, the standard library one is linked last, meaning that the one from Abaqus is taking priority. And like I said, if there is ANY global object that calls new inside the constructor, or a global `T* x = new T;` (or array variant thereof), this will cause this to go wrong, since that will happen before the odb initialization.
Comment: @Praetorian I used DUMPBIN to see the functions in the .lib that `operator new` is defined in. I found many definitions for `operator new` and nothing for `operator delete`.
Answer: Specifying the linker option "/DEFAULTLIB:MSVCRT.LIB" causes the program to execute successfully.
Comment: Although, Dependency Walker is still showing that the Abaqus .dll containing their definition of `operator new` is linked.


Encrypt data with BCrypt

Question: I've a web application (asp.net mvc) and I need to encrypt some data that will be stored in the database.
Since I'm using BCrypt for the user password, I was thinking on using it as well to encrypt other data… what do you think? Is BCrypt just for passwords or can I use it as well for other data? Or maybe there is a best way to do it?
Thanks in advance!
Comment: You need to learn the difference between **hashing** and **encryption**.
Comment: Security is _hard_.  You need to learn a lot more about it before you can use encryption properly.  In particular, where will you store the key?
Answer: BCrypt does not encrypt anything.  It is a HASHING algorithm that uses Blowfish internally, but does not actually encrypt your data.
The main difference:
Hashing is an algorithm that takes data of variable size and generates a fixed-size representation of that data.  The original data, unless stored elsewhere, is lost AND cannot be retrieved.
Encrypting is an algorithm that takes data of variable size and generates a similarly-sized chunk of data.  The original data, unless stored elsewhere (thereby voiding the purpose of encryption), is lost.  It CAN, however, be retrieved.  The Encryption process uses a separate piece of data called a Key.  Provided the associated decryption algorithm is used, the same key will decrypt the data and the original information can be retrieved.
So:
Before anyone can answer your question, you must first understand what you are asking.  Do you, in fact, need to store encrypted information, or rather is it hashed information?  If you merely need to store sensitive information, but never need to return the original value back to the user, then continue using BCrypt, as it will hash your data (thereby making it unreadable, but still comparable).  If, on the other hand, you want to store sensitive information that you one day may need to supply to someone (for instance, a credit card number), then look into sql encryption algorithms.
As you explore the world of security, you will quickly find that it is very painful, but very important.  For instance: SLaks brings up a good point.  If you encrypt your data, somewhere, somehow, you need to store your key.  But if that key is found, then someone can steal all of your data!  You must find a way to properly encrypt your data while hiding the key from the public.  There are several ways of doing this; google around a bit before you commit to one, as it may not be as secure as you think.
Microsoft has some good recommendations: http://technet.microsoft.com/en-us/library/ms345262.aspx
You did not specify what flavor of sql you are using, so a flavor-specific answer cannot be supplied.
Comment: Thank you for the very clear and well worded answer. This helped me +1

Encrypt data with BCrypt


Wilcoxon signed-rank test in R

Question: I am trying to duplicate a Wilcoxon signed-rank test example in this Wikipedia post using R.
The data is as follows:
after = c(125, 115, 130, 140, 140, 115, 140, 125, 140, 135)
before = c(110, 122, 125, 120, 140, 124, 123, 137, 135, 145)
sgn = sign(after-before)
abs = abs(after - before)
d = data.frame(after,before,sgn,abs)
d$rank = rank(replace(abs,abs==0,NA), na='keep')
d$multi = d$sgn * d$rank

(W=abs(sum(d$multi, na.rm = T)))
W = 9

However, the test statistic value that R produces (undoubtedly due to some mistake that I am making in setting up the function or interpreting the output) is:
wilcox.test(d$before,d$after, paired = T, alternative = "two.sided", correct=F)
    Wilcoxon signed rank test

data:  d$before and d$after
V = 18, p-value = 0.5936
alternative hypothesis: true location shift is not equal to 0

This (V=18) is different from the 9 value in the Wikipedia post.
What am I missing?
Comment: It seem relevant in that the fact that one particular test in your cited article had one result but that another test also described in that article is used by the R wilcox.test. YOU SHOULD INVESTIGATE THE CAUSE OF A WARNING.
Comment: You didn't report the warnings: `"Warning messages:
1: In wilcox.test.default(d$before, d$after, paired = T, alternative = "two.sided",  :
  cannot compute exact p-value with ties"` AND `2: In wilcox.test.default(d$before, d$after, paired = T, alternative = "two.sided",  :
  cannot compute exact p-value with zeroes`
Comment: @42- I didn't think it was relevant in the way that it wouldn't affect the calculation of the test statistic. But I may be wrong. Feel free to add it as an edit, if you think it could help.
Answer: R reports the V-statistic, which is the sum of the positive ranks. The Wikipedia example computes it slightly differently, as the sum of all ranks, regardless of sign. In other words, both versions are correct (and equivalent). This CrossValidated post might be helpful.
Answer: Stumbled upon this and found it incredibly useful as well as the other CrossValidated post mentioned by @jdobres.
Just to expand a little on the answer above which is correct but in hopes that it will help someone in the future because it was very confusing at least to me initially.
Note that in R if you reverse the entry order of the paired variables you will get different V values but the same p value.  That's what brought me here.  If they reported the W statistic you would expect to see a sign change not a different magnitude as you get with V.
wilcox.test(d$before, d$after, paired = T)
wilcox.test(d$after, d$before, paired = T)

But it all comes back together, since as the Wikipedia article notes S is equal to the total rank sum (having removed the zero difference entries) so our S is:
sum(rank(1:9))

So the two possible V statistics are bound to add to 45 (18 & 27).  And the difference between them is the W statistic (9).  Finally back to the Wikipedia example we can now easily divine Siegel's T statistic, it is the smaller of the two sums of ranks of given sign; therefore, T would equal 3+4+5+6=18 (or the smaller of the two V's we could compute).

Wilcoxon signed-rank test in R


Qual fazer para chamar uma função de outro controller no Laravel? Gostaria de implementar a melhor prática

Question: Tenho um controller boletosController necessito chamar a function create na negociacaoController;
boletosController.php;
<code> namespace App\Http\Controllers;

    use App\Repositorios\Boletos;
    use Illuminate\Support\Facades\Request;

    class BoletosController extends Controller
    {
        protected $boletos;

        public function __construct(Boletos $boletos)
        {

            $this->boletos = $boletos;
        }

        public function create($data)
        {

            $create = $this->boletos->create($data);
            return $create;
        }

    }
</code>
Qual a melhor forma para chamar a função create no controller negociacaoController:
negociacaoController.php

<code>namespace App\Http\Controllers;

    use App\Models\Boletos;
    use App\Models\Negotiation;

    class NegociacaoController extends Controller
    {

        public function index()
        {

         }

       public function gerarBoletosNegociacao()
        {

         //chamar aqui uma função de outro controller

         }
</code>
Comment: A melhor forma é não chamar. Se o seu controller possui uma responsabilidade maior do que apenas tratar a requisição http, então tem coisa errada. A lógica deveria estar implementada em outra estrutura, geralmente chamada de service.
Comment: Por exemplo, por que não chama o método `create` do seu repositório ao invez de chamar do controller?
Comment: Então nesse caso eu teria que inverter, chamar a model de Negociacao e tratar dentro do controller que gera os boletos?
Comment: Como já foi falado aqui nos comentários, aparentemente tem coisa errada ai, o correto é você criar um `Service` e colocar essa função nele, e depois você "injeta" como dependência o serviço nos 2 controllers.
Answer: Eu concordo com o posicionamento do @AndersonCarlosWoss. Você deve implementar usando outra estrutura. Vou estender o argumento dele; os controllers no MVC podem ser uma espécie de service ou façade.. porque eles podem orquestram chamadas a outras lógicas e estruturas, como acesso a banco de dados e regras de negócio em si.
O que acontece é que muitas pessoas fazem regras de negócio diretamente no controller. Mas ai você me pergunta, o controller não é o lugar das regras? Sim, regras de resposta a interface. Não necessariamente são regras de negócio ou regras de acesso a dados. Pode ser que em estruturas simples, você chame o banco de dados diretamente dali... mas em softwares mais robustos ou melhor elaborados, mais complexos, você vai chamar suas classes e suas regras de negócio dali e não criá-las ali dentro do controller.
Isso server para o Larvel e qualquer outra tecnologia, estamos falando de arquitetura de componentes.
Recomendo:

Coesão e Acoplamento, pra você entender princípios de responsabilidade  https://www.devmedia.com.br/entendendo-coesao-e-acoplamento/18538
Um pattern estrutural: Facade. pra tentar compartilhar a visão que o controller do mvc pode ser um método que não necessariamente concentra regras de negócio. https://www.dofactory.com/net/facade-design-pattern
Um pouco de arquitetura orientada a componentes, pra você usar os princípios de responsabilidade criando componentes que podem ser invocados em diferentes momentos e até arquiteturas: https://en.wikipedia.org/wiki/Component-based_software_engineering

Observação sobre a model:
Complementando, o rapaz aí pediu para você fazer diretamente na Model. Isso não é legal, pois a model no MVC pode ser uma representação da sua estrutura do banco de dados. Isso é o comum de aprender por aí, mas não é uma verdade absoluta, pois ela está mais para ser uma representação da estrutura de dados que será apresentada do que ser a estrutura de dados que é armazenada. Muitas vezes as interfaces mostram informações que tem origem de dados diferentes, com suas estruturas diferentes.


Listview only showing 1 result from query

Question: So I finally got my listview to display result(s) from my db query, but for some reason its only showing 1, the last.
public class PastGames extends ListActivity {

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.pastgames);

    DBAdapter db = new DBAdapter(this);

    db.open();
    Cursor c = db.getAllFinalscores();
    if (c.moveToFirst())
    {
        do {
            String[] listData = new String [] {"Date: " + c.getString(1) + "\n" +
                    "Strokes: " + c.getString(2) + "\n" + "Holes: " + c.getString(3)};
            this.setListAdapter(new ArrayAdapter<String>(this,
                    R.layout.pastgames, listData));
        }
        while (c.moveToNext());
    }
    db.close();

}
}

dbadapter
//***RETRIEVES ALL THE FINALSCORES***//
public Cursor getAllFinalscores()
{
    return db.query(DATABASE_TABLE, new String[] {
            KEY_ROWID,
            KEY_DATE,
            KEY_FINALSCORE,
            KEY_HOLESPLAYED},
            null, null, null, null, null);
}

Could someone let me know what I am doing wrong?  Why is it not displaying each row in the db?
EDIT:  Here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/android:list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="10dp"/>

NEW (Correct way):
public class PastGames extends ListActivity {

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.pastgames);

    db.open();
    Cursor c = db.getAllFinalscores();
    String[] listData = new String[c.getCount()];
    if (c.moveToFirst())
    {
    do {

        listData[c.getPosition()] = "Date: " + c.getString(1) + "\n" +
            "Strokes: " + c.getString(2) + "\n" + "Holes: " + c.getString(3);
    }
        while (c.moveToNext());
        this.setListAdapter(new ArrayAdapter<String>(this,
            R.layout.pastgames, listData));
    }
    db.close()
}

}

Answer: For each row in your array your are setting ListAdapter in the loop. This why you only display the last one...
String[] listData;
do {
     listData[i] = "Date: " + c.getString(1) + "\n" +
                        "Strokes: " + c.getString(2) + "\n" + "Holes: " + c.getString(3);
   }
while (c.moveToNext());
this.setListAdapter(new ArrayAdapter<String>(this,
                        R.layout.pastgames, listData));

Fill your array in a while loop. And then call your this.setListAdapter() only one time. This will solve the problem
Comment: "create an array of size"

its currently X amount of rows... it all depends on how many times the user has saved, so it will always be growing.
Comment: Could you please help me understand a better method of going about doing this? I think i see what you are saying... it sets "listData" goes to next and sets it all over again, etc. What would be a good way of avoiding overwriting it each time, and gathering all the information and then displaying it?
Comment: Fill your array in a while loop. And then call your this.setListAdapter() only one time. This will solve the problem
Comment: I gave you how it should be higher. Just create array of appropriate size and increment i yourself.
Comment: so it would look as follows??  Posted above @ end
Comment: Yes, just create an array of size equal to number of rows you have. And increment i every loop
Comment: Sorry to sound like an absolute idiot, but do you know of a good tutorial or explanation on how to do that?  I am really sorry - just very new to this all still. (i think i bit off more than i can chew!)
Comment: How it will get bigger? You made a query, you know that cursor has 10 rows. So you create 10 element array for this. Got it?
Comment: each time the user saves data, it creates a new row in the database.
right now for instance i have 3 rows and 4 columns. once i save again I will have 4 rows and 4 columns... 5 rows and 4 columns.. etc.

so im guessing i will need to make the array = x

and then array++; each time it runs through? or something like that?
Comment: If you will query DB each time, then you will just create array each time and set it using setListAdapter()
Comment: I guess I just need to know, how to "resolve i" to a variable

i cannot be resolved to a variable

then at the end ill "i++"
Comment: I'm sorry, I know you probably want to smack me right now lol
Comment: 1) String[] listData = new String[c.getCount()]; 2) listData[c.getPosition()] = "Date: " + c.getString(1) + "\n" + .......
Comment: so instead it would look like that up top? (bottom area, i just edited it)
Comment: Sorry - I am trying very hard to stick with you but I dont think I know enough to say I am able to follow along correctly.
Comment: oh wait i think i missed the second part let me try that
Comment: It is working!!!! Thank you sooooo much!

I am so sorry to have put you through that.  I will make sure I take something away from this though.. Seriously, thanks a million for sticking with me!  Its perfect!
Comment: Welcome. Just try to make a progress and help others after that
Comment: Hi guys, please refrain from using the commenting system as an ad-hoc chat. Instead, use the chat system (link at the top of the page.)
Answer: You're reinitilizing ListData on evey loop execution
Comment: Could you please help me understand a better method of going about doing this?  I think i see what you are saying... it sets "listData" goes to next and sets it all over again, etc.  What would be a good way of avoiding overwriting it each time, and gathering all the information and then displaying it?


Let $f \in L(\mathbb{R}), \ f(0)=0$ and $f'(0)$ exists. Show $\frac{f(x)}{x}\in L(\mathbb{R})$

Question: This is what I try:
\begin{align}
f'(0) = \frac{f(0+x)-f(0)}{x}=\frac{f(x)-f(0)}{x}=\frac{f(x)}{x}
\end{align}
But it still not enough to say $\frac{f(x)}{x} $ is integrable
Anyone has any idea?
Answer: Since $f$ is differentiable at the origin, then there exists $\delta>0$ such that
\begin{align}
\left|\frac{f(x)-f(0)}{x}-f'(0)\right| \leq 1 \ \ \Rightarrow \ \ \frac{|f(x)-f(0)|}{|x|} \leq 1 +|f'(0)|
\end{align}
whenever $|x|<\delta$.
Observe
\begin{align}
\int^\infty_{-\infty} \frac{|f(x)|}{|x|}\ dx = \int_{|x|\leq \delta}\frac{|f(x)|}{|x|}\ dx+\int_{|x|\geq \delta} \frac{|f(x)|}{|x|}\ dx = I_1+I_2.
\end{align}
For $I_2$, we have
\begin{align}
I_2 \leq \frac{1}{\delta}\int_{|x|\geq \delta}|f(x)|\ dx<\infty.
\end{align}
For $I_1$, we have
\begin{align}
\int_{|x|\leq \delta} \frac{|f(x)|}{|x|}\ dx = \int_{|x|\leq \delta}  \frac{|f(x)-f(0)|}{|x|}\ dx \leq \ 2\delta(1+|f'(0)|).
\end{align}
Hence $\frac{f(x)}{x}$ is integrable.
Comment: Thank you ! It's very clear!
But I still have a little problem
Comment: Why can we prove integrable by proving I1 and I2 are finite? I thought we have to prove $\intf^+$ and$ \intf^-$ are finite?
Comment: Why can we prove integrable by proving I1 and I2 are finite? I thought we have to prove $ \intf+\int{f^+} $and$\int{f^−}$ are finite?
Comment: I already took the absolute value.
Comment: I got it!  Thanks a lot


Prove the equation has no root in the circle $|z| < 1$

Question: Suppose that $0 < a_0 \le a_1 \le \dots \le a_n$. Prove that the equation $$P(z) = a_0z^n + a_1z^{n-1} + \dots + a_{n-1}z + a_n = 0$$ has no root in the circle $|z| < 1$.
Comment: See also: http://math.stackexchange.com/q/188039/5363 for a related result.
Comment: $|z|<1$ is not a circle
Answer: We want to show that $a_0z^n+\cdots+a_{n-1}z\neq -a_n$ for $|z|<1$. In fact, by induction we can prove something stronger: that $|a_0z^n+\cdots+a_{n-1}z|<a_n$. The base case $n=1$ is easy, since $|a_0z|=a_0|z|<a_0\leq a_1$. If we have the $n-1$ case, then
$$|a_0z^n+\cdots+a_{n-1}z|=|a_0z^{n-1}+\cdots+a_{n-1}||z|<|a_0z^{n-1}+\cdots+a_{n-1}|<a_{n-1}\leq a_n$$
and so the theorem follows by induction.
Comment: I think $| a_0z^{n-1} + \cdots + a_{n-1} | < a_{n-1}$ might be wrong


isometry preserve dense property

Question: Let $A$ and $B$ are two metric spaces. let $f:A\to B$ be an isometry. If $C \subset A$ is dense in $A$, is it true that $f(C)$ is dense in $B$?
Thanks for your help in advance.
Comment: What about $A\subset B$ such that $A$ is not dense in $B$, and $f$ being the inclusion? Then $C=A$ provides a counterexample.
Comment: Ok. But I was thinking this. Say $U_B$ be any open set in $Y$. If $U_B \cap f(C)$ is non-empty then it is dense. $U_A=f^{-1}(U_B)$ is open in $A$. since $C$ is dense in $A$, $U_A \cap C \neq \phi$, say $t \in U_A \cap C$. Then clearly $f(t) \in f(U_A) \cap f(C)=U_B \cap f(C)$. Where am I making mistake?
Comment: I understand, $U_A$ can be empty.
Answer: It depends how you define isometry. If you just define it as a distance-preserving map, then no. But if you define it as a bijection that preserves distance (like some textbooks do, like mine- I use Pugh's Real Analysis)- yes.
Proof
Suppose $A$ and $B$ are equipped with the metrics $m$ and $M$ respectively.
If $C$ is dense in $A$, then $\overline C = A$. To prove that $f(C)$ is dense in $B$, we need to show $\overline{f(C)} = B$.
It's clear that $\overline{f(C)} \subseteq B$, so it suffices to show $B \subseteq \overline{f(C)}$.
Suppose $y \in B$. If $f$ is surjective, $\exists$ $x \in A$ st $f(x) = y$.
Since $\overline C = A$, $x \in \overline C$. Then every open ball centered at $x$ contains a point in $C$, or, more formally, $\exists$ $x' \in C$ st $m(x, x') < r$, for every $r > 0$. Since $f$ is an isometry (a distance-preserving map), we have that $r > m(x, x') = M(y, f(x'))$. Then for each $y \in B$ and $r > 0$, $\exists$ $f(x') \in f(C)$ st $f(x') \in B_M(y, r)$, so $ \overline{f(C)} = B$.
Of course, if $f$ is not surjective, there are many counterexamples. drhab already provided an example in the comments, but another one is the map $f: \mathbb{R} \rightarrow \mathbb{R}^2, x \mapsto (x, 0)$. Take a dense subset of $\mathbb{R}$, say $\mathbb{Q}$, and note that $f(\mathbb{Q}$) is not dense in $\mathbb{R}^2$.
Comment: +1 According to the definition in your textbook an isometry is automatically an isomorphism between topological spaces that are induced by the metrics.

isometry preserve dense property


How does angular eagerly loading a component without registering into the declarations array

Question: Here is my feature component
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-polling',
  templateUrl: './polling.component.html',
  styleUrls: ['./polling.component.scss']
})
export class PollingComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

Here is the Routing module
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PollingComponent } from './polling/polling.component';

const routes: Routes = [
      {
        path: '',
        component: PollingComponent,
        pathMatch: 'full'
      },

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Here is the Root module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {}
}

In the above code you can see that the PollingComponent is never added into the declarations array, but the component is loading in the browser without having any errors. So, I wondered how does the component is loading without registering it? I am using Angular CLI 12.2.3.
Comment: I've seen more questions about this. It seems there was a change in ng12.x that would allow this.
Comment: Quriosity, has you check if still work when you build in prod: `ng build`?
Answer: In the above code means you are saying PollingComponent has not added in Root Module but component is loading fine without issue.
See try to understand what Root module is doing there, its a root or main module of the application so here root module contains default main component that is AppComponent and to use routing module is importing AppRoutingModule. In AppRoutingModule routs is declared as PollingComponent so it is expected logic, no need to register PollingComponent in Root Module because PollingComponent has registered in AppRoutingModule. It will work without any issue. Thanks
Comment: @Rajesh You are confusing typescript imports with Angular module imports/declarations. Having a typescript import has nothing to do with Angular loading components.
Comment: `PolllingComponent` is NOT declared/registered in `AppRoutingModule`, it is only present in the routes.
Comment: but router modules are added into the imports array of App module. Also the component is not lazy loaded, so it should be added into the declaration section right?
Comment: Hi Gael J ,To present that PollingComponent in AppRoutingModule  see the code AppRoutingModule he has used this import { PollingComponent } from './polling/polling.component'; Here import saying if you want to use some properties of a componet then you have to register first as import way.
Comment: @Pranab PollingComponent is used in AppRoutingModule  for routing. So here in this code " imports: [RouterModule.forRoot(routes)] " you are asking Angular to instantiate an instance of the Router class globally so PoolingComponent will load no need to use this component in declaration.
Comment: @GaëlJ Component will load if you are using that component in router, this code "imports: [RouterModule.forRoot(routes)]" will help to load that component, you do not need to write in module declaration section.
Comment: @RajeshKumarSwain did u find any reference/documents that tells about how to load components without declarations. If yes, please share it here.
Comment: @Pranab I just tried on your above code, I have no specific document now. You can also try this. In one way Create a new component but don't add that in routes and in declaration section. See what happening, this time you will get exception. And another way you have already faced that is your current pooling component used in routing. Hope you are clear my clarification.
Answer: I noticed this:
if you do not declare the component it cannot access the elements of the imported modules
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Google Analytics with jQuery - show pathname in label

Question: I've got as far as creating the tracking and it works great like so:
  $('a.external').click(function(){
    _gaq.push(['_trackEvent', 'Exit Links', 'Click', $(this).attr('href')]);
  });

example

This comes through to analytics correctly with the href as the label. What I'm wanting to do is be able to tag the current page they are on as well. So we can work out which page they were on when they clicked the link to go to an external page.
Something like this?
  $('a.external').click(function(){
    var pathName = window.location.pathname + document.location.hash;
    alert(pathName);
    _gaq.push(['_trackEvent', 'Exit Links', 'Click', $(this).attr('href')] pathName);
  });

That alerts the correct location but could anyone help me clean it up so that the pathName is added to the label within the gaq.push?
Thanks!
Sean
Answer: Something will have to give if you want to pass the pathName as the ga event only allows three parameters that allow text.
 $('a.external').click(function () {
 var pathName = window.location.pathname + document.location.hash
 var externalLink = $(this).attr('href');
 alert(['_trackEvent', 'Exit Links', pathName, externalLink]);

});
Comment: For reference I managed to get it working like so: `$('a.external').click(function(){
    var pathName = 'Location: ' + window.location.pathname + ' ' + document.location.hash + 'URL: ' + $(this).attr('href');
    _gaq.push(['_trackEvent', 'Exit Links','Click', pathName]);
  });` That then shows the page they are currently, and which URL they went too! Works quite nicely too with just tag any link with the .external class!


Save dynamic result from stored procedure into a dynamic table

Question: I am facing some issues in saving the execution of stored procedure / scalar function into a table variable.
The function / stored procedure returns dynamic columns and I need to create a dynamic table to save the result of that function into it so that I can use the table.
Example: the stored procedure spGetEmployeeInfo could return employee name, employee id, etc. on such criteria they return only employee name,.
Is there a way to create a dynamic table and save the result into it after execute the stored procedure, or any suggestion.
Thanks
Comment: *"is there a way to create a dynamic table"* Use a `SELECT...INTO`? You'll need to do it *inside* the dynamic statement though, not outside of it.
Answer: I don't like to get into this situation too often, but when I do, what I do is have the stored proc output into a global temp table.  The name of the table is passed in as a parameter by the user.  For instance:
create procedure dynamicBeCareful
    @toggle bit,
    @globalTempTableName varchar(50)
as

-- initializations

    if left(@globalTempTableName,2) <> '##'
      throw 50000, '@globalTempTableName must start with ##', 1;

    declare @sql varchar(max);

-- build dynamic sql

    if @toggle = 1
        set @sql = 'select * into @tempTable from table1';
    else
        set @sql = 'select * into @tempTable from table2';

    set @sql = replace(@sql, '@tempTable', @globalTempTableName);

-- terminations

    exec (@sql);

    declare @msg = 'Your results are in ' + @globalTempTableName;
    print (@msg);

Then use it like this:
exec dynamicBeCareful 1, '##temp';

select * from ##temp;

Beyond just being dynamic in output, it also can get you out of nested insert-exec limitations.


How do I play two notes high and low together with a plectrum on guitar?

Question: In the second bar, there is a high E and low C to be played together. If you need to play this on a guitar with a plectrum, how do you do it?
Comment: I like problems and puzzles but ... sorry, this is the first question here in my time on SE I'm going to down-vote. You don't  need to play it with a plectrum, that's all.
Answer: First of all, this is not intended to be played with a plectrum. But if you really want to use a plectrum here, you would use hybrid picking, i.e., pick the low C with the plectrum and use your middle finger or ring finger to pick the high e string.
Comment: @ggcg: My intention was to answer the question, and I do think that I did that. Note that hybrid picking does use a pick, and that's what I suggested because it's in my opinion the only practical way to approach that piece using a pick.
Comment: I concur, but since the OP specifically asked how to do it with a pick, I answered that with the caveat that it wouldn't be my judgement to so ;-)
Comment: I agree, this actually does not answer the question.  Should be a comment.
Answer: Being really smartass, the simple way is to fret the A string on 3rd fret, making the C, and use another finger on the bottom string over the 5th fret, to make the high E as a harmonic. Then you use the pick to pluck the two bottom strings.
Would I (or anyone) do it like that? Most likely not! But the question was asked, and that's a simple answer!
Most players would use thumb and finger, pick and finger, or two fingers, or mute the strings in between. But purely using a pick, that's the way to do it!!!
Comment: I like that, although if that were the intent the sheet music would have a symbol for the harmonic.
Comment: Haha! This idea makes me very happy...
Comment: @mistercoffee66 - but not enough to upvote it?!
Comment: Sorry, I got called away for a few minutes :)
Comment: By the way, I am suprissed that no one suggested alternate tuning!
Comment: @ggcg - that would be a fair bit out from standard! yes I realise the harmonic isn't noted, but there you go. right note though.
Comment: The whole thing is far out.
Comment: @ggcg I thought about suggesting an alternate tuning in the comments but was afraid it would be taken seriously! I also thought about a Coral electric sitar with the extra array of strings...
Answer: To play this solely with a pick, you have limited options:

Finger the 3rd fret of the A string (middle C) with your first finger and the 5th fret of the B string (E) with your third or fourth finger (depends on hand size). You need to use the rest of your index finger and/or the in-between finger(s) to lay more or less flat on the D and G strings to mute them. Whether you do this with one or multiple fingers is a matter of preference and comfort.

My hands are smallish so I would use first and fourth finger to fret the notes with the remainder of my first finger laying on the D and G strings.

Same as above but fret the 8th fret of the low E and the 9th fret of the G. Mute the A and D strings as above.

In both examples, you'll have to use an abbreviated and controlled strum motion that starts on the lower of the two fretted strings and ends on the higher. The first example above is possibly a more desirable voicing in the context of the rest of the piece (judging only by the previous measure). The second example is possibly easier to play because the beginning of the strum is on the lowest string and can be more forgiving of your precision.
(As an aside, for a melodic line like this I would personally use the pick for the lower note and my third finger to pluck the higher note without needing to mute anything. Both techniques are worthwhile to learn.)
Answer: In addition to all the suggestions so far, applying an alternate  tuning is another option.  Though I would not provide a tuning in the answer without seeing the entire sheet as a tuning that makes this one pair easy to play might ruin the play-ability of the rest of the tune.
The best Plectrum only approach would be (as has been suggested) to play this as a bar chord in 3rd position with the D and G strings muted with the left hand fingers.
By the way, the solution to this one pair should make the other parts too difficult to play.  The bar before it has a C-G-e and this is 1-5-3(8va) of the C chord.  The A-form in 3rd position would allow you to play both of these bars without shifting position.  If you are not completely restricted to a plectrum only solution then grabbing that part with "hybrid picking" works (as has been suggested in an other answer).


Cannot add task 'wrapper' as a task with that name already exists

Question: When installing 'react-native init AwesomeProject' I get this error when I run react-native run-android:
Could not determine java version from '11.0.1'.

A quick google suggests I need to update the distributionUrl in the Gradle-wrapper. Having done this I am faced with a new error:
Cannot add task 'wrapper' as a task with that name already exists.

It suggests the issue is in the file:
/AwesomeProject/android/build.gradle' line: 36

which looks like this
task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

I've been back and forth trying to figure out what this does. It seems odd that something wouldn't work straight out of the box. Is anybody facing a similar issue?
Comment: is there any update or which is a correct-worked answer? If not then how did you solved it? else tick-right icon on an answer.>> :-)
Answer: You can also update
task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

to
wrapper {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

As

Overriding built-in tasks deprecated in 4.8 now produces an error.
Attempting to replace a built-in task will produce an error similar to the following:

Cannot add task 'wrapper' as a task with that name already exists.

see the last paragraph of Tasks & properties:
https://docs.gradle.org/5.2.1/userguide/upgrading_version_4.html
and Customizing the Wrapper task:
https://docs.gradle.org/5.2.1/userguide/gradle_wrapper.html#customizing_wrapper
Comment: This answer doesn't answer OP's actual question, but it's very helpful to Googlers like me, so I upvoted.
Comment: It does solve the OP's problem. He was using an ancient Gradle version and then tied to update using an outdated solution, and this answer provides the correct solution. (Of course, @FranklinYu, if you take "is anybody facing a similar issue?" as the OP's question, then a simple "yes" would suffice.)
Answer: which version of gradle do you use in your environment?
If you use gradle version 5.x you have to modify 「task wrapper」 as below.
task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
wrapper {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

Comment: Then this error came. Can't figure out what to do.
ERROR: Could not find method wrapper() for arguments [{type=class org.gradle.api.tasks.wrapper.Wrapper}, build_81gq92nveejavsi3t9efznmk8$_run_closure2@55f5bac8] on root project 'myproject' of type org.gradle.api.Project.
Answer: if "gradle-wrapper.properties" file already have these codes
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

then you can remove
task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

from build.gradle
Comment: but in this case you can't use `./gradle task` from terminal
Answer: As mentioned in the comments follow - https://stackoverflow.com/a/46867575/4982729:

Open and edit the file app-folder/android/gradle/wrapper/gradle-wrapper.properties; update the line
distributionUrl=https\://services.gradle.org/distributions/gradle-5.0-all.zip

In file AwesomeProject/android/build.gradle try commenting out
task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

Answer: I have the same issue. the problem in my code was a double declaration on another Gradle file in build.gradle
build.gradle
apply from: otherFile.gradle
... build. gradle code...
apply from: otherFile.gradle //Again

Answer: There's a high chance you have a "task" to run in your build.gradle file, go and remove
the line related to wrapper (including its bracket and so on).
Then, if you are using IntelliJ, it will automatically bring the new one to your working directory.
Answer: I ran into the issue because I was running my task using the global gradle, and not my local gradle wrapper.
i.e. in my current directory I had a gradlew executable.
But I was running this command:
gradle <task>

When I should have been running:
./gradlew <task>

Presumably because running the global gradle tries to create a local wrapper -- and one already existed.


Finding the minimum value of an expression

Question: Where $n = 5$, $a = 1$, $b = 2$ and $x + y = n$ i.e. $x + (n- x) = n$,what is the minimum number that can be had from $ax^2 + by^2$ by using differentiation?

I know the answer is 17 from doing it manually:

$ 1 \times 0^2+ 2 \times 5^2= 50 $

$ 1 \times 1^2+ 2 \times 4^2= 33 $

$ 1 \times 2^2+ 2 \times 3^2= 22 $

$ 1 \times 3^2+ 2 \times 2^2= 17 $

$ 1 \times 4^2+ 2 \times 1^2= 18 $

$ 1 \times 5^2+ 2 \times 0^2= 25 $
Comment: Your arithmetic is mostly wrong.  $1\times 2^2+2\times 3^2=4+18=22$.   and $1\times 3^2+2\times 2^2=9+8=17$, for example.
Comment: If $x,y$ are constrained to be integers then differentiation just gets you near to the solution.  Here you can use Lagrange Multipliers to see that $y=\frac ab x$, so in this case the true min would occur at $(\frac {10}3, \frac 53)$.  You then have to test the nearby integers to see which is the integer min.
Answer: Since $y = n-x$,
$ax^2+by^2
=ax^2+b(n-x)^2
=(a+b)x^2-2bnx+bn^2
=f(x)
$.
$f'(x)
=2(a+b)x-2bn
=0$
when
$x
=\dfrac{bn}{a+b}
$.
For this,
$n-x
=n-\dfrac{bn}{a+b}
=\dfrac{an}{a+b}
$
so
$f(x)
=ax^2+b(n-x)^2
=a\dfrac{b^2n^2}{(a+b)^2}+b\dfrac{a^2n^2}{(a+b)^2}
=\dfrac{ab^2n^2+ba^2n^2}{(a+b)^2}
=\dfrac{abn^2(b+a)}{(a+b)^2}
=\dfrac{abn^2}{a+b}
$.
Since
$f''(x)
=2(a+b)
\gt 0$,
this is a minimum.
Nothing fancy.
For your case,
$x
= \dfrac{1\ 2\ 5^2}{1+2}
= \dfrac{50}{3}
=16\frac23
$.
To find an integer min,
which is not stated in your question,
look at
the integers
surrounding this value
if it is not an integer.
It is probably the integer
closest to this,
but I have not tried to prove this.
In your case,
these are 16 and 17.,
with 17 being closer.
Answer: Are you asking for the minimum value of $f(x,y) = x^2+2y^2$ subject to the constraint, $g(x,y)=x+y-5=0$ with $x$ and $y$ real? The minimum occurs at the point $x=10/3, y=5/3$ and at this point $f$ takes value $f(10/3,5/3)=50/3<17$. One way this "critical point" can be found is by setting the gradient of $F(x,y,\mu) = f+\mu g$ equal to zero, i.e. $\nabla F= 0$.


Criar vetor de forma automática em Python

Question: Sou novato em Python e preciso da ajuda com o seguinte:

Tenho uma variável (x) que recebe um valor inteiro.
Desejo que essa variável seja utilizada para criar um vetor com 1 linha e (x) colunas.
Esse vetor deve possuir valores aleatórios e inteiros de 0 à 100.

Exemplo:
Para x = 4
Minha saída deve ser:

[50,40,60,70]
Answer: Podes usar o modulo random para gerar os valores aleatórios:
Caso não queiras valores repetidos:
import random

x = 5
saida = []
for _ in range(x):
    saida.append(random.choice(range(100)))
print saida # [5, 75, 9, 38, 33]

Ou melhor ainda:
import random

x = 5
saida = random.sample(range(100),  x)
print(saida) # [69, 47, 43, 64, 16]

Se puderem existir valores repetidos:
import random

x = 5
saida = []
for _ in range(x):
    saida.append(random.randint(0, 100))
print saida # [74, 12, 15, 32, 74]

Nota que podes usar uma compreensão de lista para qualquer uma das soluções acima:
import random

x = 5
saida = [random.randint(0, 100) for _ in range(x)]
print saida # [88, 37, 17, 27, 58]

DEMONSTRAÇÃO dos três exemplos acima
Comment: Dei uma vacilada e você foi mais rápido :p Boa resposta +1
Comment: Muito Obrigado! Funcionou perfeitamente!
Comment: De nada @Danilo
Answer: É simples. Seria legal dar uma olhada no módulo random, lá tem várias formas de trabalhar com números aleatórios.
randint retorna um número inteiro entre os dois que foram passados por parâmetro.
from random import randint

x = int(raw_input('entre com o valor desejado: '))
vec = []

for i in range (x):
    vec.append(randint(0, 100))

print(vec)

Veja funcionando no repl.it.
Comment: Muito Obrigado! Me ajudou muito.


Showing that this is a measure

Question: Let $f:{X}\rightarrow\ [0, {\infty}]$ a function and let $M=\mathcal{P}(X)$ be a $\sigma$-algebra, with $X$ not empty.
Define $$
  l(A)=\begin{cases}
    \sup \left\{ \sum_{x \in F} f(x) \;\middle|\; F \subset A,\: F\text{ finite}  \right\}
    &\text{if $F \neq \emptyset$,}\\
    0 &\text{otherwise.}
  \end{cases}
$$
Show that $l$ is a measure.
I have problems in the part of separating the supremum of a set into a series of numerable supremes.
Another question, the conditions for $l(A)$ be finite are that the direct image of $A$ under $f$ is finite and that the set of $x$ in $A$ such that $f(x)>0$ need to be numerable? I think that the sum of all the values of $f$ in this set needs to be finite too, for the finiteless of $l(A)$.
Comment: Please work on your formatting.
Comment: Sorry, now i´m taking a course on Linux and Latex, i´ll  fix that.
Answer: First off, you are correct that for $A$ to have finite measure, i.e. for $l(A) < \infty$ to hold, $f(x) = 0$ must hold for all but countable many $x \in A$. You need a bit of set theory to show this though - the general idea is to show that whenever uncountably many $x$ with $f(x) \neq 0$ exists in $A$, you also find enough "large" ones to constructs finite sets with arbitrarily large sums.

The following shows that $l$ is $\sigma$-additive. I assume that you have already shown that $l$ is finitely additive, i.e. that $l(A \cup B) = l(A) + l(B)$ if $A$ and $B$ are disjoint (this is easy!).
Assume that $A = \bigcup_{i=1}^\infty A_i$, and that all the $A_i$ are disjoint. Your goal is to show that $$
  l(A) = \sum_{i=1}^\infty l(A_i).
$$
For and arbitrary finite $F \subset A$ $F$, let $F_i := A_i \cap F$. Note that then $\bigcup_{i=1}^\infty F_i = F$, and since infinite summations of non-negative summans can be reordered freely, it follows that $$
  l(F) = \sum_{x \in F} f(x) = \sum_{i=1}^\infty \sum_{x \in F_i} f(x) = \sum_{i=1}^\infty l(F_i) \leq \sum_{i=1}^\infty l(A_i).
$$
Since this is true for every finite $F \subset A$, you get that $$
  l(A) = \sup_{\substack{F \subset A,\\F\text{ finite}}} l(F) \leq \sum_{i=1}^\infty l(A_i).
$$
For the converse, pick an $\varepsilon > 0$, and chose finite $F_i \subset A_i$ such that $$
  l(A_i) - l(F_i) \leq \varepsilon 2^{-i}
  \quad
  \text{and set}
  \quad
  G_i := \bigcup_{j=1}^i F_j \subset A.
  \quad
  \text{(the $G_i$ are all finite!)}
$$
Then, since $l(A_i)-\varepsilon 2^{-i} \leq l(F_i)$, you get (assuming that $\sum_{i=1}^\infty l(A_i)$ converges - I leave the non-converging case, i.e. the case of $A$ having measure $\infty$ to you)
$$\begin{eqnarray}
  l(A) \geq \lim_{i\to\infty} l(G_i)
  &= \lim_{i\to\infty} \sum_{j=1}^i l(F_j)
  \geq \lim_{i\to\infty} \sum_{j=1}^i l(A_j) - \underbrace{\varepsilon\sum_{j=1}^i 2^{-j}}_{=\varepsilon(1 - 2^{-i})} \\
  &= \sum_{j=1}^\infty l(A_j) - \lim_{i\to\infty} \left(\sum_{j=i+1}^\infty l(A_j) + \varepsilon(1 - 2^{-i})\right) \\
  &= \sum_{j=1}^\infty l(A_j) - \varepsilon .
\end{eqnarray}$$
Since $\varepsilon$ was arbitrary, that implies that $$
  l(A) \geq \sum_{j=1}^\infty l(A_j) .
$$

Showing that this is a measure


Heavy GUI application with Python?

Question: Is it possible to create high GUI apps or graphics intensive games using python? I am a beginner at programming I want to make GUI apps along with web applications and also I'm interested in Machine Learning. Many resources says python is best for ML and Web apps and not for GUI Is there any ways to create it.
Answer: If you'd like to create 2D games with Python, there are several libraries you can use:

PyGame or PyGame Zero
Pyglet

I have also heard good things about Panda3D for 3D games. There is an openGL wrapper as well, but that one sounds like it has quite the learning curve.
Machine Learning is a different ballgame entirely. You would want to look up pandas, matplotlib, dask and several other libraries to get started with that discipline.

Heavy GUI application with Python?


8va or clef change?

Question: I've been transcribing music on and off for a few years now as a hobby and noticed while reading someone else's sheets that they have heaps of clef changes midway through the piece. It sort of blew my mind a little that you could even do that.
My question is when and why use a clef change over an 8va? Is there some sort of convention I haven't heard about? Some sort of debate or war ongoing between Octavians and Clefians because of this question?
My understanding was that clef changes should only be used if the octave change spans like a third of the piece.
Comment: The answer depends largely on the instrument; some are more used to working in multiple clefs. Piano uses two of them every day, but violin and flute have no use for bass clef. The poor viola switches between alto and treble regularly, and cello gets into all three.
Comment: To add to "depends on the instrument": on a piano, it's very easy to see a note and instantly play an octave higher - same fingering pattern and all that, just move your hand to the right. As a violist, it's really hard to do that - I don't consciously think about the name of the note I'm playing, I translate directly from dot on page to place to stop a string, and there's no easy relationship between sensible fingerings for the same passage an octave apart.
Comment: @Jim In that case:  A clef change would be fine (but only necessary if the notes are high enough).  An 8va would not be right.
Comment: One thing to keep in mind is that clef changes were in use for at least a couple of centuries before anyone thought of using _8va_.
Comment: @AndyBonner I feel like my heads going to explode from taking in all this information. So assuming this was for a piano and the notes on the bass clef enter the treble range for a single measure, would I be justified using a clef change, an octave change or not changing anything, or does it not really matter that much and I should just stop overthinking things.
Comment: see some of these related answers: [ledger-lines-vs-8va-notation](https://music.stackexchange.com/questions/62984/ledger-lines-vs-8va-notation)
Answer: As AndyB commented, this depends heavily on the instrument in question.  Us cellists get quite used to jumping amongst bass, tenor, and treble, with stacks of ledger line  anyway .
By comparison,  you never ever use any clef other than treble for clarinets and saxophones, no matter how many ledger lines.  The lower-pitched members of these families read the treble clef as-is, so you the composer must recognize both the Bb or Eb offset as well as an octave or three difference between written and produced pitches.
Comment: @ElementsinSpace  that's just one more headache we get used to.  There's even some cello music written in treble clef **but** we're supposed to know it's to be played sub8va
Comment: Not to mention the concert flute, which easily reads the high D, six ledger lines up. (See Prokofjev's Classical Symphony. Did the guy never hear of a piccolo?)
Comment: And then you're sightreading Dvorak, you turn the page, and suddenly you're expected to take something up an octave with no advance notice (shudder).
Comment: The question asks:
"why use a clef change over an 8va?"
but you haven't mentioned 8va in your answer.
Comment: @CarlWitthoft That seems kind of rude, why would anyone write cello music that way?
Comment: @ElementsinSpace  it was simply the "style" back a couple (or more) centuries ago.
Answer: If it's piano music, you can use 8va for notes high above treble clef in the upper staff, and 8vb for notes far below bass clef in the lower staff.
But, use a clef change instead for notes in the upper staff that are below the treble clef, and for notes in the lower staff that are above bass clef.
Three or fewer ledger lines usually doesn't warrant either.
Non keyboard type instruments usually don't ever want to see an 8va or 8vb.
Comment: This makes perfect sense for piano, +1. Using 8vb in the upper staff or 8va in the lower staff is messy, it clutters the center of the grand staff. Better to use clef changes in those situations and va/vb on the top and bottom.
Comment: Music which is intended for multiple instruments playing in unison may sometimes contain 8va or 8vb brackets with a notation that they apply only to certain instruments (presumably those which would otherwise not have the range to play the parts as written).  Having an instrument jump octaves at a place that makes musical sense may be better than simply playing to the top or bottom of their range.
Comment: It's worth noting that although Britten used ottava clefs (e.g. clefs that signify an octave transposition) in his piano music, it's generally frowned upon.

8va or clef change?


Probability question: Statistics: What is the probability of B given A has occurred?

Question: Question: 20% of gumballs in a machine are red. The other 80% are blue. 20% of the gumballs in the machine have dents in them. What is the probability of getting a dented gumball that is red?
My Approach:
We can call the probability of a red gumball P(r), the probability of a blue gumball P(b) and the probability of a dented gumball P(d).
We know P(r) and P(b) are independent as you can't have gumballs that are both red and blue.
The equation I want to use is P(r|d): (Join probability of r & d)/P(d)
So given that the gumball is dented, what is the likelihood it is red.
P(d) = .2
P(r) = .2
Where I am stuck is how to find the joint probability (or overlap) of dented red gumballs... (Since I am assuming we cannot say that blue and red gumballs are dented equally).
I feel like I should be factoring in P(b) somewhere to find that overlap of r & d, but I'm not sure how...
Any advice on how to find the joint probability of r & d is much appreciated!
(Additionally, the equation to find P(joint r & d)=P(d)*P(r|d)
Answer: Let's let $B, R, \text{and } D$ denote the events that we draw a blue, red, and dented gum ball, respectively.

We know $\mathsf P(R)$ and $\mathsf P(B)$ are independent as you can't have gum balls that are both red and blue.

Two events $A$ and $B$ are said to be independent if $\mathsf P(A\cap B)=\mathsf P(A)\cdot\mathsf P(B)$
But $\mathsf P(R\cap B)=0$ and $\mathsf P(R)\cdot\mathsf P(B)=0.2\cdot0.8=0.16$ so $R$ and $B$ are not independent.
In any case, the question asks for the probability of the gum ball being dented and red so we have
$$\mathsf P(D\cap R)=0.2\cdot 0.2=0.04$$
Comment: Indeed; the fact that the events cannot both occur means that they are *mutually exclusive* (aka *disjoint*); so the probability of the intersection is zero.  That is a rather different concept from *independence*; do not confuse them. @SadieL
Comment: Thank you! That is a great point and I completely had them mixed up in my head.
Comment: So a gumball being dented and a gumball being red are independent, but a gumball being red and a gumball being blue are mutually exclusive (aka disjoint)? (Just to confirm I have that correct in my head)


How can I rewrite this a generic?

Question: I have the following piece of code:
 public Component GetComponent(Type type)
    {
        return Components.FirstOrDefault(component => component.GetType() == type);
    }

The caller has to do a nasty cast to get the component it passed in - how can I rewrite this to a cast-less generic?
Answer: If I read your question correctly, you can move the cast inside the function and do it this way.
public T GetComponent<T>() where T : Component
{
    return (T)Components.FirstOrDefault(c => c.GetType() == typeof(T));
}

If the type is not known at compile time going in to the function (like, say GetComponet() is called in a loop where the type is passed in as a argument) there is no way to get a strongly typed object back.
Comment: The type is indeed known at compile-time.
Comment: Just as a programmers note: The `where` clause is not necessary for the code to function, but it does help you from accidentally passing in a type that is not derived from Component and would never be held inside the components collection.
Answer: public Component GetComponent<T>() where T : Component{
    var type = typeof(T);
    return Components.FirstOrDefault(c => c.GetType() == type);
}

How can I rewrite this a generic?


Rewrite rule for a url conatining space in its end in web.config?

Question: I am working on a rewriting process. I have been stuck on a point that.
<rule name="Uk3" stopProcessing="true">
      <match url="^activities/exploring/tours/tabid/3422/id/5205/k/([a-z0-9A-Z-\s]+)/p/1/nickis-beach-rides.aspx$" ignoreCase="true" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^(www.)?abc.co.uk$" />
      </conditions>
      <action type="Redirect" url="/activities/exploring/tours.aspx" />
    </rule>

what does the above rule is doing:
It matches "activities/exploring/tours/tabid/3422/id/5205/k/" as it is and the it may contain anything after this upto "/p/1/nickis-beach-rides.aspx". It is working fine for all URLs except the following :
http://www.abc.co.uk/activities/exploring/tours/tabid/3422/id/5205/k/enjoy%20your%20morning%20cofee%20and%20evening%20cocktails%20on%20/p/1/nickis-beach-rides.aspx

which contains "enjoy%20your%20morning%20cofee%20and%20evening%20cocktails%20on%20" space as the last character that cause to stop this rule to work,
Anyone has any idea how can i add the above URL to work accordingly?
Answer: I may be wrong, but i suspect that the culprit is more the % sign than the trailing space.
This % sign is not handled by your actual regex.
You could try : ([%a-z0-9A-Z-\s]+)
Comment: @raman Does it help ?


How can I fit images of different orientations into the same container with equal padding?

Question: I have a container of images scrolling horizontally in a single row with equal spacing between them. Most of the images are in landscape and look fine but there are a few portraits and they have extra spacing in between them. I've been trying to make them fit with equal spacing and be responsive to changing screen sizes/mobile views but have been having trouble with the portrait images.

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      margin-left: .3em;
    }

    h1 {
      margin-top: 1rem;
      margin-left: .5em;
      margin-bottom: -.3em;
      font-family: 'Ubuntu', sans-serif;
      font-size: 2.5em;
    }

    img {
      display: block;
      width: 100%;

    }

    .gallery__thumb ~ .gallery__thumb {
      margin-left: 10px;
    }

    .sub-container {
      display: flex;
      overflow-x: auto;
      align-items: center;
      height: 100vh;
    }

    .gallery__thumb {
      min-width: 55%;
      height: 85vh;
    }

    figure#test.gallery__thumb {
      max-width: 30%;
      height: 85vh;
    }

    img.lazy {
      opacity: 0;
    }

    img:not(.initial) {
      transition: opacity 1s;
    }
    img.initial,
    img.loaded,
    img.error {
      opacity: 1;
    }

    img:not([src]) {
      visibility: hidden;
    }

Answer: I'd suggest changing your structure a bit so your container has de fixed height and the images adapt accordingly keeping their ratio, that way you can set the gap between images in the container itself.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  margin-left: .3em;
}

h1 {
  margin-top: 1rem;
  margin-left: .5em;
  margin-bottom: -.3em;
  font-family: 'Ubuntu', sans-serif;
  font-size: 2.5em;
}

img {
  display: block;
  width: auto;
  height: 100%;

}

.sub-container {
  display: flex;
  overflow-x: auto;
  align-items: center;
  height: 100vh;
  /*Here's the space between them*/
  column-gap: 20px;
}

img.lazy {
  opacity: 0;
}

img:not(.initial) {
  transition: opacity 1s;
}

img.initial,
img.loaded,
img.error {
  opacity: 1;
}

img:not([src]) {
  visibility: hidden;
}

Comment: Happy to help, I'd suggest you check more about `flexbox`


Creating an email newsletter using simplenews

Question: I need to create an email newsletter template using simplenews. Can anyone point me to a simple, clear tutorial on how to do so?
Comment: What's wrong with the [Simplenews handbook page](http://drupal.org/node/197057)?
Comment: Personally I found it to be rather incomplete and not as helpful as I would have hoped. Perhaps more advanced Drupal users may find it more useful.
Answer: I found this links useful
Designing a HTML newsletter for Drupal
http://drupalsteve.com/node/30

Drupal & Simplenews
http://www.slideshare.net/desk02/dug-simplenews-6192093

Email Newsletters and the Simplenews Module
http://www.group42.ca/email_newsletters_and_the_simplenews_module

and probably
Newsletter subscription management in Drupal with E-mail Marketing Framework
http://www.drupalcoder.com/blog/newsletter-subscription-management-in-drupal-with-e-mail-marketing-framework
Answer: I had posted a similar question for D7 here How to theme simplenews newsletters in D7?
and ran across the D6 version here:
http://drupal.org/node/197057


How to avoid Duplicate values for INSERT in SQL?

Question: I have one table named:
Delegates

This table has four fields:
ID(Auto increment, Primary)
MemberNo, FromYr, ToYr

I am inserting with this query:
INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)

The values comes from user input. One member can be a Delegate for any year that's why I allow them to input as they want. But now problem is they can insert mistakenly one member for the same year more than 2 times.
Please help me what can I do now here?
Comment: What is the natural unique key then? Not the IDENTITY value
Comment: no unique key is there actually.
Comment: @barsan: well, can't be done then.
Answer: Use MERGE
MERGE INTO Delegates D
USING (values(@MemNo, @FromYr,@ToYr)) X ([MemNo],[FromYr],[ToYr])
ON (insert unique key join)
WHEN NOT MATCHED BY TARGET THEN
INSERT ([MemNo],[FromYr],[ToYr]))
VALUES (X.[MemNo],X.[FromYr],X.[ToYr]);

Comment: I think you have an extra close parentheses on Insert line?
Answer: Before inserting check if there is a record with the same values:
if not exists (select * from Delegates d where d.FromYr = @FromYr and d.MemNo = @MemNo)
    INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)

Comment: This will fail under high load
Comment: @gzaxx: no it won't unless you use a performance killing lock strategy
Comment: I have been using this approach for years. However now i'm experiencing duplicate inserts several times a day. So I can confirm that this fails under high load.
Comment: Didn't know that, putting it inside of transaction would fix that?
Answer: Just add a unique index on that column, then inserting duplicates will cause an error. You can then error handle it if it needs to fail gracefully
Answer: Try this, (I have not verified)
INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
where @MemNo not in
(
    SELECT MemNo FROM words WHERE FromYr = @FromYr
)

Comment: I get an error when using the WHERE clause with INSERT INTO... VALUES. The consensus seems to be that you must use an INSERT SELECT.
Answer: make a stored procedure that will first make a check on the whether the values are already contained in the DB. if they arent you will do your insert. If they simply ignore it
Answer: You can avoid inserting duplicates with this simple, one line of code:
INSERT INTO Delegates (MemNo, FromYr, ToYr) SELECT @MemNo, @FromYr, @ToYr WHERE NOT EXISTS (SELECT 1 FROM Delegates d WHERE d.MemNo=@MemNo AND d.FromYr=@FromYr)
If it's a high load environment where another command could insert the duplicate while this command is executing, you can use the WITH(HOLDLOCK) hint.


What is "modal minor"?

Question: What is "modal minor"?
Context: Ralph Vaughan Williams' "Six Studies in English Folk Song" has a part called "1.Adagio ('Lovely on the Water') in E modal minor" (emphasis mine).
Reference in Classical Archives
What is "modal minor"? Is it distinct from Aeolian?
I understand there are minor scales distinct from Aeolian, such phyrgian, dorian, melodic, minor pentatonic, etc. But which scale did Williams have in mind? Is it possible to tell from the sheet music?
Answer: Definition of "modal minor"
Modal minor is a synonym for aeolian. It means that the piece does not make alternations to the minor scale such as raising the seventh degree to form a leading tone.
"In modal minor" has a different meaning than "in a minor mode", which is a broader term that could refer to any music whose mode (i.e., scale) contains a minor third above the root.
Can one tell from the score?
Yes, one can tell from the score, at least in the Vaughn Williams case, by noting several features:

The key signature, containing only F#, suggests the possibility of E minor.
The piece ends on a sustained E, and the final E in each instrument is not approached by a leading tone. In particular, the piano's final arpeggio clearly outlines E minor but pointedly includes D natural rather than D#.
The cello part contains no accidentals, excepting a single C# in m. 16, which is insufficient to affect the perceived mode of the piece.

The accidentals in the piano part
The accidentals in the piano part of worthy of attention. Bb and C# appear with some consistency in the part and one might argue the piece is based on a scale that includes those pitches. However, a careful look at the context of these accidentals suggests otherwise.
The Bbs occurs in the piano part always as part of a G minor or Bb major arpeggio. The C#s are always used to intensify an arrival on D. This consistency of context — and especially their near absence from the cell part, which contains the melody — argues against an alteration of the minor minor.
Comment: Do you know what the "modal" in "modal minor" might mean? Is this an old form of terminology?
Comment: I found it really helpful that this answer includes an analysis of the score (thanks).

What is "modal minor"?