How to print the following Multi-Dimensional array in Java Script?

Question: I have the following array (the code is written in Java) :
String[][] a = new String[3][2];
a[0][0] = "1";
a[0][1] = "2";

a[1][0] = "1";
a[1][1] = "2";

a[2][0] = "1";
a[2][1] = "2";

and what I want to do is to print 111222 and I accomplished that in Java by doing this:
for (int i=0;i < a[i].length;i++){
    for(int j=0;j <a.length;j++){
        System.out.print(a[j][i]);
    }
}

What is the equivalent of this in JavaScript?
Answer: Here is the equivalent code in Javascript (no space its not a script version of java)
! edit missed the particulars of the loops, fixed now
var a = [];
a.push(["1", "2"]);
a.push(["1", "2"]);
a.push(["1", "2"]);

for(var i = 0; i < a[i].length; i++) {
  for(var z = 0; z < a.length; z++) {
    console.log(a[z][i]);
  }
}

Comment: this is not right, it will print the array like this (121212) what i want is to print something like the following 111222
Comment: the for loop bit is the same as java write it as you whant
Comment: i didn't se that you had nested it strangely is that really the behavior you want?
Comment: Yes, i want to use it for a special purpose function.
Comment: wow, can some one elaborate on this code.  Beautiful as it is, I dont understand how `a[z][i]` is printing what its printing.  Thanks
Comment: If you're going to correct the OP, then note that it's "JavaScript," not "Javascript."
Answer: var arr =[
        [1,2,3],
        [4,5,6],
        [7,8,9]
        ],arrText='';

        for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < arr[i].length; j++) {
                arrText+=arr[i][j]+' ';
            }
            console.log(arrText);
            arrText='';
        }

Output:
Answer: js is very powerfull ; just use spread operator

mat = [[1,2,3],[3,4,5]]

mat.forEach(v=>console.log(...v));

// output
run the code see the output.

1 2 3

3 4 5
Answer: for (i=0; i < a.length; i++) {
   for (j = 0; j < a[i].length; j++) { document.write(a[i][j]); }
}

Though it would be smarter to add all the strings together and the print them out as one (could add to an element or alert it out.)
Comment: again this will print the array like this (121212) what i want is to print something like the following 111222
Answer:
In javascript you can create multi dimensional array using single
dimensional arrays.
For every element in an array assign another array to make it multi
dimensional.

    // first array equivalent to rows
    let a = new Array(3);

    // inner array equivalent to columns
    for(i=0; i<a.length; i++) {
      a[i] = new Array(2);
    }

    // now assign values
    a[0][0] = "1";
    a[0][1] = "2";

    a[1][0] = "1";
    a[1][1] = "2";

    a[2][0] = "1";
    a[2][1] = "2";

    /* console.log appends new line at end. So concatenate before     printing */

    let out="";
    for(let i=0; i<a.length; i++) {
      for(let j=0; j<a[i].length; j++) {
        out = out + a[i][j];
      }
    }
    console.log(out);
Answer: var a = [];

a[0] = [];
a[0][0] = "1";
a[0][1] = "2";

a[1] = [];
a[1][0] = "1";
a[1][1] = "2";

a[2] = [];
a[2][0] = "1";
a[2][1] = "2";

for (i = 0; i < a[i].length; i++) {
    for (j = 0; j < a.length; j++) {
        document.write(a[j][i]);
    }
}


why do we have to use ServerName for our websites in apache?

Question: I would like to understand the need for ServerName in apache.
Lets say that I have a web site with IP 22.214.171.124.
In DNS zone I call it example.com and refer the Ip to it with an A record.
Why isn't this enough? It tells the www that whenever anyone writes example.com, it needs to go to 18.104.22.168 ip.
So why do I need to set it also in apache with NameServer attribute?
Answer: You don't need to use it, but it allows you to have multiple virtual hosts with different server names to listen on the same IP address.
In the early days of the web, before HTTP/1.1 was introduced, you only could host one domain on any IP address, as there was no way to differentiate the domains. HTTP/1.1 added the Host header that told the server which domain the client wants to talk to and the ServerName tells Apache for which domains the current virtual host should answer.
http://httpd.apache.org/docs/2.2/en/vhosts/name-based.html


Using jQuery 1.4.4 This simple method fails for some reason

Question: $.get($(this).attr('rel'), function(response){}, 'script')
.error(function(){ alert('this failed')});

I get. .error is not a method . But it was added in version 1.4.3
http://api.jquery.com/error/
Is there some kind of type I have ?
Comment: Oh now I'm embaressed. It's a legacy app. That is convoluted and huge.
Comment: Any particular reason you're still using such an old version of jQuery?
Comment: I don't think an answer that is not listing the alternatives is a correct answer. There are workarounds around this. You *need to* "bind it to something else" indeed.
Answer: The return value of $.get in jQuery 1.4.3 does not have a .error method.  I am actually not sure what the return value is, but you should be able to check it .. whatever it is, it doesn't have .error.  You will have to bind it to something else.
At some point, jQuery started returning jqxhr objects from $.get, $.post, $.ajax, etc.  I believe this is after 1.5 when they introduced Deferred, but I'm not 100% sure.  The jqxhr object has .done, .fail and .always (implementing Deferred), so you would be able to do $.get().fail() at some point after jQuery 1.5.  You definitely can in jQuery 1.7.
Either upgrade jQuery or use $.ajax instead with error as a setting.
Comment: Ah. I figured this would happen. I think this is the way out of the jungle. Many thanks Tandu~


Dynamic deep access of javascript object values

Question: I have a Java script object and I am trying to dynamically access a specific value from it and change it to something
My object:
myJson =  {
            "id" : "http://**********",
            "$schema": "http://json-schema.org/draft-04/schema",
            "type" : "object",
            "properties":{
            "AddressLine1" :{"type":"string" , "maxLength":62},
            "AddressLine2" :{"type":"string" , "maxLength":62},
            "city" :{"type":"string" , "maxLength":62},
            "state" :{"type":"string" , "maxLength":5}
        },
        "required": ["AddressLine1", "city"]
        }

for example if I need to access maxLength in state object dynamically based on the given "path"
path = "$.properties.state.maxLength";

So based on the variable "path" that I get I have to access the value based on the path and edit it.
Full code:
var sample = function (){

    var myJson = {
        "id" : "http://application.nw.com/address",
        "$schema": "http://json-schema.org/draft-04/schema",
        "type" : "object",
        "properties":{
        "AddressLine1" :{"type":"string" , "maxLength":62},
        "AddressLine2" :{"type":"string" , "maxLength":62},
        "city" :{"type":"string" , "maxLength":62},
        "state" :{"type":"string" , "maxLength":5}
    },
    "required": ["AddressLine1", "city"]
    }

    // I get the path from an external source.
    path = "$.properties.state.maxLength";

    path = path.substring('$.'.length);
    console.log(path);          // log = properties.state.maxLength
    console.log(myJson.properties.state.maxLength);        // log 5
    console.log(myJson.path);                      // log undefined

}

I am a newbie pls help and try to encourage, if I did something really silly.
Thanks
please feel free to edit it if any mistakes
Comment: That's not JSON, that's a JavaScript object.
Comment: have you tried `path = myJson.properties.state.maxLength;`?
Comment: Please, show us your entire code.
Comment: If you need to dynamically access the properties of a javascript object then you need to use the bracket notation. For example `myJson["properties"]` vs `myJson.properties`
Comment: @FelippeDuarte has the right answer. You need to point to the appropriate object first as `properties` does not exist on its own
Comment: Felippe Duarte I have tried path = myJson.properties.state.maxLength; and i get the answer, but i get a path , where path = $.properties.state.maxLength and then I operate on it and set path = properties.state.maxLength.
Comment: related: http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets
Comment: @MattBurland it is similar to the one you suggested but this has more layers and i think this is a deep access.
Comment: @FelippeDuarte I have updated he question.
Comment: @FelippeDuarte , I have tried that, gives me undefined.
Comment: What are you trying to do with `path`? It does not exist on `myJson`, so logging it will be undefined.
Comment: @whipdancer I have changed the question so it adds more meaning. I am trying to dynamically access values from the javascript object. For example let us say I have to find the value of maxLength in state object in properties, how do i do it. The value to be accessed keeps changing for every instance and I should be able to edit the maxLength as well.
Answer: You need to parse the path in order to access the properties.
Because path is a variable, myJson.path doesn't make sense.  The dot notation indicates a property.
Because you need to dynamically access a property based on the content of the variable, you need to use bracket notation.  Each level of depth you go down in the object needs its own bracket.
console.log(myJson) --> the object
console.log(myJson["properties"]  --> the properties property of the object
console.log(myJson["properties"]["state"] --> the state property of the properties property

Using the bracket notation, you can parse the path variable into its component parts:
var p1 = "properties";
var p2 = "states";
var p3 = "maxLength";
console.log(myJson[p1][p2][p3]);

Here is a fiddle demo.


Constructor of parameter in generic method ( java )

Question: I want to make a general function which will fill a HashMap<String,TYPE extends GameObject> based on contend of a text file. It should work for any TYPE which implements methods getName() and fromString(). Currently, I found obstacle, that I cannot call constructor of TYPE.
The code:
public static <TYPE extends GameObject> void loadHashMap( Map<String,TYPE> mp, String filename ){
    BufferedReader reader = FileSystem.getReader( filename );
    String line;
    try{
        while( null != ( line = reader.readLine() )  ){
            TYPE item = new TYPE(); item.fromString( line ); // alternative 1
            // TYPE item = new TYPE( line );                 // alternative 2
            mp.put( item.getName(), item );
        };
    } catch (Exception e) { e.printStackTrace(); };
}

where GameObject is defined as:
public class GameObject {
    String name;
    public String getName(){ return name; };
    public void fromString( String s ){ name = s;   }
    public GameObject ( ){  }
    public GameObject ( String s ){ name=name; }
}

Answer: In Java all template types are erased when compiling, so you are not supposed to do something like new TYPE(). You need to find another way to create an instance.
see Create instance of generic type in Java?


Why can't we sample without replacement for each tree in a random forest if the subsample size is large enough?

Question: Usually if we have $n$ observations, for each tree with form a bootstrapped subsample of size $n$ with replacement. On googling it one common explanation I've seen is that with replacement sampling is necessary for independence of individual trees.
But why can't we just resample as follows: for tree 1, randomly sample $m$ observations without replacement out of the $n$, where $m$ is still large enough (of course, provided that $n$ is large enough in the first place). Then replenish all observations and repeat the resampling for tree 2, and so on.
Even in this case, I'd imagine that the individual subsamples would be independent. So is there an additional reason for resampling with replacement in bagging?
Answer: Independent is the wrong word, but yes, this is sometimes done like this.
Sampling without replacement is supported by many implementations of random forests.
Comment: Thanks for the answer! What would be the correct term instead of independent? I thought correlated but that implies a linear relationship, so I think "correlated" would also be a wrong term
Comment: The tree predictions of a random forest are extremely strongly correlated across trees. Still, they are not perfectly correlated, so that the variance of the ensemble is still lower than the one from a single tree.


Slow internet connection for no reason

Question: We have a cable internet connection. I've called the company when this happens and they say there's been no downtime on the modem and the signal is strong and there's no fixing or outages in the area. I mostly trust them on that.
Cable modem -> 4 port gigabit Netgear switch -> Sonicwall -> Cisco 2960S -> Dell T410 DC running Server 2008R2 with basic settings
Currently have about 50-75 connected computers or servers.
Internet is great for a week or two, but then (at random) it gets really slow for about half an hour. Then back to normal speed.
What would cause this out of the gear listed? Is there a tool for figuring this out?
Comment: Why do you have a switch between the cable modem and the firewall?
Comment: So we can have a computer hooked up on it to be completely unconnected to the rest of our LAN and get a public IP.
Answer: The problem source is likely in one of two places:

The modem - someone is doing a large upload to a well-connected server and is saturating the upload link of the circuit, thereby slowing down all other traffic. Put in place some traffic shaping on the upload side of things to clear this up.
The Sonicwall - perhaps you're exhausting the state tracking tables? Perhaps you're pushing through more bandwidth than it is intended to deal with. 50-75 active users is quite a few to be pushing through what is essentially a residential-quality internet connection.
Comment: Seconded, +1.  I'd definitely look into thee Sonicwall, and look for time of day patterns.  Had a similar problem at a former employer, and correlated it to break times when a couple hundred shift workers jumped on their iFruits and other devices and brutalized our poor pipe.  We quickly rate-limited the guest wireless, but it was a user issue, not a technical one.
Comment: What settings/logs am I looking for specifically on the sonicwall?
Comment: @Matt - no idea. Using anything other than pfSense or real Cisco enterprise-grade equipment (e.g. not the gear formerly made by Linksys) for routing drives me nuts, so I can't help you.

Slow internet connection for no reason


Context menu for List in Windows phone

Question: First of all, I know about this topic: How to make context menu work for windows phone?
But this way is SOO complicated...
So I have this XAML code:
 <StackPanel Name="friendsGrid" Margin="0,0,0,0" Background="Transparent">
   <ListBox Name="friendsListBox" FontSize="32" Tap="friendsListBox_Tap">
     <toolkit:ContextMenuService.ContextMenu>
     <toolkit:ContextMenu Name="MyContextMenu" Opened="MyContextMenu_Opened">
     <toolkit:MenuItem Header="action" Click="contextMenuAction_Click"/>
     </toolkit:ContextMenu>
     </toolkit:ContextMenuService.ContextMenu>
   </ListBox>
 </StackPanel>

And I'm filling the list like this:
this.friendsListBox.Items.Add(friend.serviceName);

But, of course, when I do longtap, the context menu appears and selects the whole List, not only one item.
Is there some easy way to recognize the item was tapped?
Thanks
BTW, I found this method, but contextMenuListItem doesn't recieve anything, it's still null:
ListBoxItem contextMenuListItem = friendsListBox.ItemContainerGenerator.ContainerFromItem((sender as ContextMenu).DataContext) as ListBoxItem;

Comment: can you show us your listbox itemtemplate
Answer: You should put ContextMenu block into your ItemTemplate (not ListBox block).
Here short sample.
XAML:
            <ListBox Name="TestList" Margin="26,0,26,0" Height="380" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}">
                        <toolkit:ContextMenuService.ContextMenu>
                            <toolkit:ContextMenu Name="ContextMenu" >
                                <toolkit:MenuItem Name="Edit" Header="Edit" Click="Edit_Click"/>
                                <toolkit:MenuItem Name="Delete"  Header="Delete" Click="Delete_Click"/>
                            </toolkit:ContextMenu>
                        </toolkit:ContextMenuService.ContextMenu>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Code:
    public List<string> Items = new List<string>
    {
        "Item1",
        "Item2",
        "Item3",
        "Item4",
        "Item5",
    };

    // Constructor
    public MainPage()
    {
        InitializeComponent();
        TestList.ItemsSource = Items;
    }

    private void Edit_Click(object sender, RoutedEventArgs e)
    {
        if (TestList.ItemContainerGenerator == null) return;
        var selectedListBoxItem = TestList.ItemContainerGenerator.ContainerFromItem(((MenuItem) sender).DataContext) as ListBoxItem;
        if (selectedListBoxItem == null) return;
        var selectedIndex = TestList.ItemContainerGenerator.IndexFromContainer(selectedListBoxItem);
        MessageBox.Show(Items[selectedIndex]);
    }

Hope this helps.
Comment: The questioner hasn't even upvoted the solution to his problem... lame.

Context menu for List in Windows phone


Universal probability for k number of containers

Question: We have k containers, in each of them a number of white and b number of black balls. We select one random ball from the first, throw it into the second. Then we pick a random ball from it (i.e. from the second container), throw it into the third, etc. What is the probability that we will draw a white ball from the last container?
I tried first for only 2 containers:
We have four possible outcomes: $(A_1A_2),(A_1B_2)(B_1A_2),(B_1B_2)$
Where $A_1A_2$ means we have drawn a white ball to the second basket and we have pulled a white ball from the second basket.
So for two baskets the probability would be $\frac b {a+b}$
But I don't know how to extend it to k containers. Any help?
Answer: Let there be $w_i$ white and $t_i$ total balls in container $i$ – initially. Label only the white balls by their initial container. Now ask "what is the probability of pulling a white ball from the last container that originated from the first?" Multiply the following factors:

That ball must have been picked from the first container and thrown into the second: $\frac{w_1}{t_1}$
It is the only ball from the first container in the second now, and yet it was picked and thrown into the third: $\frac1{t_2+1}$
It is the only ball from the first container in the third now, and yet it was picked and thrown into the fourth: $\frac1{t_3+1}$
etc. etc. until it is picked from the final container with probability $\frac1{t_k+1}$.

We can repeat this reasoning for balls starting in any container (but note that the first fraction for a ball starting in container $i>1$ has denominator $t_i+1$, since some ball has already been thrown into it). Since the events of picking up white balls from the last container that started from different containers are mutually exclusive and exhaustive, we add the probabilities to get the final result:
$$\sum_{i=1}^k\frac{w_i}{\prod_{j=i}^k(t_j+[j>1])}$$
Here $[\cdot]$ is the Iverson bracket, which is $1$ if whatever inside is true and $0$ otherwise.


Correct scrolling with ScrollViewer in landscape and portrait modes

Question: I have a simple Pivot with a PivotItem as below.
<StackPanel>
   <controls:Pivot x:Name="TopPivot" Title="Daily Comics" ItemsSource="{Binding ComicsListModel}" SelectionChanged="TopPivot_SelectionChanged" Height="762">
            <controls:Pivot.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding ComicName}"/>
                </DataTemplate>
            </controls:Pivot.HeaderTemplate>
            <controls:Pivot.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding PubDate}" HorizontalAlignment="Center" VerticalAlignment="Top" />
                        <ScrollViewer VerticalScrollBarVisibility="Auto">
                            <Image x:Name="ComicStrip" Source="{Binding ComicImage}" Stretch="UniformToFill" />
                        </ScrollViewer>
                    </StackPanel>
                </DataTemplate>
            </controls:Pivot.ItemTemplate>
   </controls:Pivot>
</StackPanel>

The problem is that I want the Image (named "ComicStrip") to scroll vertically if it's not entirely visible. This works in portrait mode, but not in lanscape. In lanscape the image can be scrolled only partly and bottom part of the image will not be visible.
I think I have to tell the ScrollViewer it's height when I am in lanscape mode, but I don't know how and what would be the best practice to deal with this kind of use case. Seems like a basic use case, though.
Any advice what I should do?
Comment: What happens if you set VerticalScrollBarVisibility to Visible rather than Auto?
Comment: Hmm - no difference in behaviour. And more strangely, I don't see a scrollbar either when panning the image.
Answer: I think the problem here is using a StackPanel for the Pivot item template! If you use a Grid, you shouldn't have any issue there.
Replace your Pivot item template with this:
<controls:Pivot.ItemTemplate>
    <DataTemplate>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>
            <TextBlock Text="{Binding PubDate}" />
            <ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="1">
                <Image x:Name="ComicStrip" Source="{Binding ComicImage}" Stretch="UniformToFill" />
            </ScrollViewer>
        </Grid>
    </DataTemplate>
</controls:Pivot.ItemTemplate>

Comment: Thanks! The StackPanel was definitely the issue here. I had another StackPanel in the XAML too which was not included in my original paste so I replaced that as well with a Grid and now scrolling works! Final version can be seen here: [link](https://github.com/kypeli/WPDailyComic/blob/master/ComicBrowser/MainPage.xaml)
Comment: I this this is the root cause. http://stackoverflow.com/questions/802821/how-can-i-get-scrollviewer-to-work-inside-a-stackpanel


making square axes plot with log2 scales in matplotlib

Question: I'd like to make a square axis scatter plot with matplotlib. Normally using set_scale("log") works great, but it limits me to log10. I'd like to make the plot in log2. I saw the solution here: How to produce an exponentially scaled axis?
but it is quite complicated and does not work if you have 0 values in your arrays, which I do. I'd like to simply ignore those like other numpy functions do.
For example:
log2scatter(data1, data2)

where data1 and data2 contain 0s should have a logarithmic scale on the x and y axis, with logarithmic spaced ticks. Just like log10, except log2...
Comment: Logs are only defined for positive arguments. This holds irrespective of the base, i.e. it holds for natural logs, log base 10, log base 2 etc. Hence you just can't plot something which has zeros in a logscale, unless you do something to these zero values.
Comment: Use the answer from that question but filter out the y-values that are 0 and their corresponding x values first (that's how numpy ignores them anyway).
Comment: What's an elegant way to do that in numpy? The filtering complicates the code since now I have to have a copy of the array unfiltered, and a copy filtered...
Answer: Matplotlib >= 3.3:
Specify base=2:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xscale('log', base=2)
ax.set_yscale('log', base=2)

ax.plot(range(1024))
plt.show()

Matplotlib < 3.3:
Specify basex=2 and/or basey=2 for the x- and y-axis.
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xscale('log', basex=2)
ax.set_yscale('log', basey=2)

ax.plot(range(1024))
plt.show()

For the zero-crossing behavior, what you're referring to is a "Symmetric Log" plot (a.k.a. "symlog").  For whatever it's worth, data isn't filtered out, it's just a linear plot near 0 and a log plot everywhere else.  It's the scale that changes, not the data.
Normally you'd just do ax.set_xscale('symlog', basex=2) but using a non-10 base appears to be buggy at the moment for symlog plots.
Edit:
Heh! The bug appears to be due to a classic mistake: using a mutable default argument.
I've filed a bug report, but if you feel like fixing it, you'll need to make a minor edit to lib/matplotlib/ticker.py, around line 1376, in the __init__ method of SymmetricalLogLocator.
Instead of
def __init__(self, transform, subs=[1.0]):
    self._transform = transform
    self._subs = subs
    ...

Change it to something similar to:
def __init__(self, transform, subs=None):
    self._transform = transform
    if subs is None:
        self._subs = [1.0]
    else:
        self._subs = subs
    ....

With that change made, it behaves as expected...
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_xscale('symlog', basex=2)
ax.set_yscale('symlog', basey=2)

x = np.arange(-1024, 1024)
ax.plot(x, x)

plt.show()

Comment: Use `base=2` in `matplotlib >= 3.3` instead of `basex=2` and `basey=2`.
Comment: Shouldn't have to override/hack a class in matplotlib to make a freakin' scatter plot in log2 versus log2... it's so sad and frustrating. :(
Comment: I get really strange default x and y limits using base=2 (and actually even without it). It doesn't set it to be the smallest values in either dimension. It picks really strange limits that hide most of the data. How can this be fixed aside from manually setting x/y limits?
Comment: The symlog part is a bug.  The limits you're referring to are just the way that limits behave for a log plot.  They "snap" to the nearest power of the base.  If you want the limits to strictly end at the min and max of the data, then specify `ax.axis('tight')`.
Answer: If you are using plt.xscale, you still need to specify basex, not base:
plt.figure()
plt.plot(x, y)
plt.xscale('log', basex=2)
plt.show()

Comment: plt.xscale('log', base=2) worked for me
Comment: Just like [this comment](https://stackoverflow.com/questions/8887544/making-square-axes-plot-with-log2-scales-in-matplotlib#comment119551375_8888110) suggested. This depends on the matplotlib version. Right now the code above will produce `TypeError: LogScale.__init__() got an unexpected keyword argument 'basex'`


Invalid converstion from void* to char**

Question: It has been a while since I messed with C code.
I am getting the following error when compiling C code under Ubuntu using gcc.
The command I am using to compile code is (if these errors are because of compiler I am using, please let me know how to make that go away):
gcc -o runnable mycode.C

error: invalid conversion from 'void*' to 'char**'

Line 39 is :
sequence=malloc(sizeof(char *)*seqNum);

sequence is declared as:
char **sequence;

seqNum is declared as:
int seqNum

Comment: Rename your file so the extension is a lowercase "c". GCC decides the language you're using from the extension, and for some reason capital "C" means C++.
Comment: Ah. Credit here should go to sgm. This is exactly right.
Comment: In order to use the C math library you have to link it in. Add -lm to your compiler flags.
Answer: Added: The fasted solution to Arron's actual problem is provided by sgm in a comment. The text below is all accurate, and hopefully helpful, but a second rate solution to the problem at hand.

Your compiler is being very stiffnecked about pointer casts (are you using a c++ compiler?), adding an explicit cast like
sequence=(char**)malloc(sizeof(char *)*seqNum);

should make the error go away. Alternately you might be able to convince the compiler to go easy on you with some kind of option like
$(CC) --lighten-up-baby code.c

which might be preferable if this is in some third party code that you don't really want to hack. Read your compiler documentation to find the option you want. Since all the gccs I have on hand (versions 4.0 and 4.2) are happy with that code, I'm not in a good place to offer advice on switches to turn this behavior off.
Comment: +1 exactly. C compilers don't complain but C++ compilers should.
Comment: C99 compilers are more picky about typing than C89 compilers ever were, and gcc can be made extra-picky with switches like -pedantic
Comment: I am using gcc -o to compile the code on ubuntu. what you mentioned made that error go away. But now i am getting the same error on this line for(i=0;i<seqNum;i++) sequence[i]=malloc(sizeof(char)*seqLength); and doing same thing on this line is not helping...also, what do you suggest is the best way to compile c code on linux
Comment: The cast on the later line would be to a (char*), because that is the type of sequence[i]...
Comment: If you're just creating a fixed-size two-dimensional array then you can do it in one malloc and assign it to the char **.  Or if it's going to be a temporary then just declare it as char sequence[dim1][dim2]  (as long as it's not too big to be on the stack :)
Answer: You need to cast the result of malloc to be the type you want.
So:

 char **sequence;
 ...
 sequence = (char **)malloc(sizeof(char *) * seqNum);

Also remember that if you're going to use sequence you'll need to allocate a list of "char *"s as you have done but then you don't have the pointed-to memory allocated, it's only allocated the space for the list of pointers themselves.
Part of the reason for this being an error is that assigning between different pointer types can change the alignment required.  Malloc is guaranteed to return a pointer to space with alignment suitable for any type.
Comment: That only applies to C++. The poster believes he is writing a C application, which is less strict.
Comment: Best practices for C and C++ differ with respect to malloc(); in C, it's best *not* to cast the result, since doing so will mask a warning if there isn't a prototype for malloc() in scope (which happens more often than you think).
Comment: Ah yes, just saw that in the comment on the answer.  It's still good practice to cast the result of malloc in C, mind  :)


Trig Substitution Integral Question

Question: My class is going over trig substitution, but I can't figure this one out, mostly because it's not in the correct form. Could someone help explain how to set up this problem?
$$ \int \frac {1}{x^2-25} dx $$
Comment: You want the $25$ to be a $1$, so factor $25$ from the denominator to start.
Comment: Let $x=5\tan t$, and use the fact that $\tan't=1+\tan^2t$.
Comment: Sorry, it's x^2-25, not x^2+25.
Comment: But shouldn't I have to put the denominator under a radical to get the proper form in order to do a substitution?
Comment: "But shouldn't I...?" - nope!
Answer: You don't need trig here: use partial fractions.
Comment: Wow, I didn't even think about that. Thank you
Answer: If you insist on using trigonometric substitution, the correct one would be $x=5\sec\theta$.
\begin{align*}
\int \frac{dx}{x^2-25} &= \int\frac{\color{red}{5}\sec\theta\color{red}{\tan\theta}\,d\theta}{\color{red}{25\tan^2\theta}} = \frac{1}{5}\int\frac{\sec\theta}{\tan\theta}\,d\theta \\
&= \frac{1}{5}\int \csc\theta\,d\theta \\
&= -\frac{1}{5}\ln\left|\csc\theta + \cot\theta\right| + C \\
\end{align*}
Drawing a right triangle with base angle $\theta$, hypotenuse $x$ and adjacent side $5$ (so that $\sec\theta = \frac{x}{5})$, we see that the opposite side must have length $\sqrt{x^2-25}$, so $\csc\theta = \frac{x}{\sqrt{x^2-25}}$ and $\cot\theta = \frac{5}{\sqrt{x^2-25}}$
Therefore
\begin{align*}
-\frac{1}{5}\ln\left|\csc\theta + \cot\theta\right| + C
&= -\frac{1}{5}\ln\left|\frac{x}{\sqrt{x^2-25}} + \frac{5}{\sqrt{x^2-25}}\right| + C \\
&= -\frac{1}{5}\ln\left|\frac{x+5}{\sqrt{x^2-25}}\right| + C \\
&= -\frac{1}{5}\left(\ln\left|{x+5}\right|-\ln\left|{\sqrt{x^2-25}}\right|\right) + C \\
\\
&= -\frac{1}{5}\left(\ln\left|x+5\right|-\ln\left|\sqrt{x-5}\sqrt{x+5}\right|\right) + C \\
\\
&= -\frac{1}{5}\left(\ln\left|x+5\right|-\ln\left|\sqrt{x-5}\right|-\ln\left|\sqrt{x+5}\right|\right) + C \\
\\
&= -\frac{1}{5}\left(\ln\left|x+5\right|-\frac{1}{2}\ln\left|{x-5}\right|-\frac{1}{2}\ln\left|{x+5}\right|\right) + C \\
\\
&= -\frac{1}{5}\left(\frac{1}{2}\ln\left|x+5\right|-\frac{1}{2}\ln\left|{x-5}\right|\right) + C \\
\\
&= \frac{1}{10}\left(\ln|x-5| - \ln|x+5|\right) +C
\end{align*}
This is definitely not the most straightforward solution but it's nice to know there's so inconsistency with the choice.
Comment: Or $x = 5 \csc \theta$
Comment: @GFauxPas: yes, but I usually only use sin, tan, or sec.
Answer: The integral
$$ \int \frac {1}{x^2-25} dx $$
isn't in the correct form yet, but you can manipulate it easily
$$ \int \frac {1}{x^2-25} dx =  \int \frac {1}{25((\frac{x}{5})^2-1)} dx = \frac{1}{25}\int \frac {1}{(\frac{x}{5})^2-1} dx$$
now, just substitute $u=\frac{x}{5}, du=\frac{dx}{5}$
$$ \frac{1}{5}\int \frac {1}{u^2-1} du$$
continuing to manipulate...
$$ \frac{1}{5}\int \frac {1}{u^2-1} du = \frac{1}{5}\int \frac {1}{\sec^2(\sec^{-1}u)-1} du=\frac{1}{5}\int \frac {1}{\tan^2(\sec^{-1}u)} du$$
From here on, it's just an inverse trigonometric substitution (albeit a messy one because it involves $\mid u \mid$). It would be far better to use inverse hyperbolic trigonometric substitution in this case, or as Robert Israel has already pointed out, partial fractions.
Comment: -1 There is no need for these manipulations.
Comment: A good reason to use manipulations like these is to show that the expression already is in the correct form. Another reason is to show that what the inexperienced student may believe to be a trigonometric substitution is actually an inverse trigonometric substitution. I believe that looking at concepts from multiple angles facilitates deeper understanding for the student.

Trig Substitution Integral Question


Variant of Holder's inequality: $\|x\|_p \le n^{\frac1p- \frac1r} \|x\|_r$

Question: So far I believed that only the reverse Holder inequality holds for $0<p<r<1,$ but then a student pointed out to me that
$$\|x\|_p \le n^{\frac{1}{p}- \frac{1}{r}} \|x\|_r.$$ A few numerical examples suggest that this holds. And for $r,p>1$ this is just Holder, but where does this inequality come from then?
Comment: Are the $\|\cdot\|_p$ the $\ell_p$ norms on $\mathbb{R}^n$?
Comment: @WillieWong yes, indeed.
Comment: Very similar question (which was shown in the sidebar among related questions): http://math.stackexchange.com/questions/1837282/tricky-norm-inequality-x-p-le-n-frac1p-frac1r-x-r-for
Answer: The standard Holder's inequality (for points in $\mathbb{R}^n$) can be written as
$$ \|fg\|_p \leq \|f\|_q \|g\|_r $$
where $p^{-1} = q^{-1} + r^{-1}$; note that this requires $q, r \geq p$.
The inequality you wrote above follows by taking $r^{-1} = p^{-1} - q^{-1}$ and $g = \mathbf{1}$.

The version above can be proved by taking $\tilde{f} = |f|^p$ and $\tilde{g} = |g|^p$ and applying the standard version quoted in Wikipedia.

In arbitrary measure spaces, what you have is the estimate
$$ \|x\|_p \leq |\mathrm{supp}(x)|^{\frac1p -\frac1q} \|x\|_q $$
for every $q \geq p$, provided the support of the function $x$ has finite measure. This is sometimes useful in probability theory.


monitoring nginx-plus vhost trafic with munin

Question: I am using nginx-plus (the version you have to pay for) and I would like to monitor acces by vhost.
When I used nginx free version, I could easily monitor accesses with the byprojects munin plugin:

I migrated to nginx plus and I have no data. When I log vith netcat to munin node :
$ nc localhost 4949

# munin node at servername.com
fetch byprojects_access
controlcenter.value 0
static.value 0
ccapi.value 0
tracking.value 0
reco.value 0

The main difference is I am logging via syslog when I was logging to file. Each vhost logs with a tag, here the tag nginxreco :
access_log syslog:server=localhost,facility=local7,tag=nginxreco,severity=info;

Where I had the following log to file configuration under free nginx:
access_log /var/log/nginx/reco-access.log;

So, for the reco vhost for instance, I had to adapt plugin configuration from :
'reco' => [
            {'path' => '/var/log/nginx/reco-access.log'}
          ],

to
'reco' => [
            {'path' => '/var/log/local7.log', 'regex' => 'nginxreco'}
          ],

Since I use syslog, log format changed a little bit: it adds a date, a hostname and a tag (which is the syslog way to log)
Old format (from direct file):
xx.xx.xx.xx - - [18/Mar/2014:06:25:20 +0100] "GET /HTTP/1.1" 200 52 "-" "Python-urllib/2.7"

New format (from syslog):
Mar 18 06:25:20 myhostname nginxreco: xx.xx.xx.xx - - [18/Mar/2014:06:25:20 +0100] "GET /HTTP/1.1" 200 52 "-" "Python-urllib/2.7"

What am I doing wrong ?
Answer: local7.log was not readable by munin


Why is this output waiting for something after it?

Question: void Wait(double Duration)
{
    clock_t End;
    End = clock() + (Duration*CLOCKS_PER_SEC);

    while (clock() < End)
    {
        // This loop just stalls the program.
    }
}

My function works perfectly half the time, but it occasionally stalls the program before it's even called.  For example, take the following snippet:
cout << "This is\n";
Wait(2.5)
cout << "a test!";

You'd expect the first line to appear immediately and the second line to appear after 2.5 seconds, but it sometimes ALL appears after 2.5 seconds.  What's the deal?
Comment: Be carefull with the information you are giving away. They will first ask for the platform/compiler, then your address. Finally you may end up with a bunch of programmers in your kitchen trying help you with your beer.
Comment: There is almost certainly a better way to do what you really want to do.  Let us know your platform/compiler, and we can give better advice.
Comment: Does this only happen for you with a cout? Keep in mind that it's buffered. So if you don't flush, I think you might get the behavior you're experiencing.
Comment: I'm not sure if this is correct, but is it possible the compiler is optimizing away the loop as it doesn't appear to do anything?  See this question: http://stackoverflow.com/questions/3592557/optimizing-away-a-while1-in-c0x
Answer: try
cout.flush();

before your Wait
Answer: That might be because of I/O buffering.
You should flush the output buffer (either try << endl instead of '\n' or writing cout.flush) manually.
Answer: Try cout << "This is" << endl;
It looks like a buffering, not clock issue.
Answer: The flush()/std::endl has already been mentioned - but is your intention to really consume 100% of one core while you wait? This is what the while() loop is doing! If you want a nicer approach to "waiting", consider one of the following:

boost::thread::sleep() - millisecond granularity
alarms (1 second granularity)
select()
pthread_cond_timedwait()

etc.


Python: How do I select multiples that contain a specific number only?

Question: For example, from all the multiples of the factor digit, I'd like to find the number of integers that have the digit "d" in one of the 2 digits of the integers. n is the limit to the number of multiples I'd like to search through.
def find_integers():
Factor=int(input("Enter Factor-digit:"))
d=int(input("Enter must-have-digit:"))
n=int(input("Enter the total number of integers:"))

for i in range(0,n):
    Multiples=(Factor*i)

How do I carry on to take out the multiples that have the digit "d" in them?
Comment: Please can you add the code you've already tried  ? and an example of what you expect exactly, there is *a lot* of multiples of 2
Comment: Ive added the code ive already tried. I apologise for the lack of specificity in my question.
Answer: multiples=[x*2 for x in range(0,1000000)]
# get 1 million multiples of 2
print(list(filter(lambda x:"4" in str(x),multiples)))
# this only prints the values in multiples if the lambda function returns true
# it only returns true if the string "4" is in the string representation of the number

I hope this helps


Getting error in structure in c programing

Question: I don't know why , but my code runs properly only for once,
if i run it again it gives me this error.
Code and the error is given below :

struct date
{
    int month;
    int day;
    int year;
};
int main()
{
    struct date d;

    printf("E:");
    scanf("%d", &d.month);

    printf("E:");
    scanf("%d", &d.day);

    printf("E:");
    scanf("%d", &d.year);

    printf("The date is as\n");
    printf("%d/%d/%d", d.month, d.day, d.year);

    return 0;
}

error which i am getting after running it second time is :
Program 'structure.exe' failed to run: Access is deniedAt line:1
char:91
+ ...  ; if ($?) { gcc structure.c -o structure } ; if ($?) {
.\structure }
+
At line:1 char:91
+ ...  ; if ($?) { gcc structure.c -o structure } ; if ($?) {
.\structure }
+
    + CategoryInfo          : ResourceUnavailable: (:) [], Applicatio
   nFailedException
    + FullyQualifiedErrorId : NativeCommandFailed

Comment: [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551)
Comment: But I'd start from checking your antivirus log.
Comment: where's the code?
Comment: @Raj now i have added the code .
Comment: @bereal also why i am getting antivirus notification whenever i run this program.
Answer: This isn't issue with C, but rather with your OS. Bereal has good point with checking antivirus.
I have no problems with this code myself:
https://onlinegdb.com/C-rjGTWuT
Next time, please make sure there aren't simmilar topics already:
Access is denied while running a C program file


How to Create a Slicer that uses dates and that only contains YTD Months dynamically by current date in PowerBI

Question: Trying to create a slicer that when clicked only the months YTD, specifically up the the last month of current.
Such as slicer box clicked: (Say current month is August) then Months "Jan","Feb",..."July" would only display to click.
I've tried several things, my last attempt was to create a Dax table with dates and try to do a switch:
Dates =
var CurrentMonthInt = month(TODAY())
var monthis8 = "Jan" + "Feb" + "March" + "April" + "May" + "June" + "July"
VAR BaseTable =
CALENDAR(
    DATE( YEAR ( MIN(Reporting[InvoiceDate])),01,01),
    DATE( YEAR ( MAX(Reporting[InvoiceDate])),12,31)
)
RETURN
 ADDCOLUMNS(
     BaseTable,
     "Year", YEAR([Date]),
     "Month", FORMAT([Date],"mm"),
     "Year Month", FORMAT([Date],"YYYY MM"),
     "Month YTD",   SWITCH(TRUE(),
    CurrentMonthInt = 1, "Jan",
    CurrentMonthInt = 8,  monthis8,
    "testing"
    )
 )

this returns a variant data type and will not work. I am thinking this is trying to add them all up on the same row.

Answer: Hello Please test this and let me know if It solves your problem.
Dates =
VAR CurrentMonthInt =
    MONTH ( TODAY () )
VAR BaseTable =
    CALENDAR (
        DATE ( YEAR ( MIN ( Reporting[InvoiceDate] ) ), 01, 01 ),
        DATE ( YEAR ( MAX ( Reporting[InvoiceDate] ) ), 12, 31 )
    )
RETURN
    FILTER (
        ADDCOLUMNS (
            BaseTable,
            "Year", YEAR ( [Date] ),
            "Month", MONTH ( [Date] ),
            "Year Month", FORMAT ( [Date], "YYYY MM" )
        ),
        [Month] <= CurrentMonthInt - 1
    )

Note: I haven't tested it.
Comment: Now please test it. I updated the code.
Comment: Wow! I Great news. I am happy to hear it. Stay safe!
Comment: it says "DAX comparison operations do not support comparing values of type Text with values of type Integer. Consider using the VALUE or FORMAT function to convert one of the values."
Comment: Please check your InvoiceDate column on Reporting table. It must be date data type, not text/string. If It is text/string, Change it to date or date time data type.
Comment: it is a date time data type
Comment: okay, I found it. It is the [Month] column. We used format function, and it returns text. I am updating the code now. Please test it after update.
Comment: Boom, you are the man!


Question regarding absolute values in limits

Question: I would like to ask a question regarding the absolute values in limits, since it seems that sometimes the absolute value is omitted, which I don't completely understand.
We are given the following limit:
$$\lim_{h \to 0} \frac{h^2 \cdot \sin(\frac{1}{\sqrt{h^2}})}{h} = \lim_{h \to 0} h \cdot \sin(\frac{1}{h})$$
By squeeze theorem, we then have
$$-\lvert h \rvert \leq h \cdot \sin(\frac{1}{h}) \leq \lvert h \rvert $$
$$\lim_{h \to 0} h\cdot \sin(\frac{1}{h}) = 0$$
However, why can you equate the following two limits in the first place:
$$\lim_{h \to 0} \frac{h^2 \cdot \sin(\frac{1}{\sqrt{h^2}})}{h} = \lim_{h \to 0} h \cdot \sin(\frac{1}{h})$$
The two limits aren't exactly equal to each other right? Since
$$\lim_{h \to 0} \frac{h^2 \cdot \sin(\frac{1}{\sqrt{h^2}})}{h} = \lim_{h \to 0} h \cdot \sin(\frac{1}{\lvert h \rvert})$$
So why can you simply omit the absolute value? Doesn't that change the solution (with the squeeze theorem)?
Comment: You should add the absolute sign but you've essentially proved that $|h\sin(1/h)|\leq|h|$ whatever the argument of sine you still have $|\sin(a)|\leq 1$
Comment: This is probably a typo in your textbook. The correct solution should use the absolute value signs or just leave it as $\sqrt{h^2}$.
Answer: We have $ \sqrt{h^2}=|h|,$ hence
$$\frac{h^2 \cdot \sin(\frac{1}{\sqrt{h^2}})}{h} =  h \cdot \sin(\frac{1}{\lvert h \rvert})$$
for $h \ne 0.$
From
$$ \lvert h \sin(\frac{1}{\lvert h \rvert}) \rvert \le |h|$$
we get
$$\lim_{h \to 0} \frac{h^2 \cdot \sin(\frac{1}{\sqrt{h^2}})}{h} = 0.$$


Stabilisers of maximal ideals over an integral domain

Question:
Suppose that $R = \mathbb{C}[x_1, \dots, x_n]/I$ is a finitely generated commutative $\mathbb{C}$-algebra which is an integral domain, and suppose that $G \leqslant \text{GL}(n, \mathbb{C})$ is a finite group acting faithfully on $R$. Is it possible for every maximal ideal of $R$ to have a nontrivial stabiliser?

Obviously, by the Nullstellensatz, every maximal ideal has the form $( x_1- \alpha_1, \dots, x_n - \alpha_n)/I$, where $I \subseteq ( x_1- \alpha_1, \dots, x_n - \alpha_n)$. I feel like there's some easy density argument that I'm missing, along the lines of the $\alpha_i$ having to satisfy a polynomial equation.
I originally thought that $S_2$ acting naturally on $\mathbb{C}[x,y]/(x-y)$ gave a counterexample, but here $S_2$ is actually acting trivially! The integral domain hypothesis might not even be necessary, but I thought that I had a counterexample when $R$ wasn't a domain.
Comment: Better add that $G$ acts faithfully on $R$ (i.e., the action map $G \to \operatorname{Aut}(R)$ has zero kernel; no element other than the identity acts trivially). Otherwise the kernel of the action is in every stabilizer (or stabiliser :-) ) and the question becomes trivial.
Comment: Thanks for pointing that out. I've updated the question accordingly.
Answer: Let $G$ be a finite group acting faithfully by regular maps on an irreducible complex algebraic affine variety $X$. Then some closed point in $X$ has trivial stabilizer.
Proof: For $g \in G$ other than the identity, the subvariety $\{x \in X \mid g.x=x\}$ is a proper subvariety (a priori, not necessarily irreducible) in $X$, so it has strictly smaller dimension than $X$. An irreducible complex variety cannot be a finite union of smaller dimension subvarieties. So some point in $X$ is outside the union of these fixed point subvarieties.


A Riemann Sum clarification

Question: I have to find the area under the curve $f(x) = x^2$ in the segment $[-2, 1]$ using Riemann Sum. So here is what I did, but it's wrong and I need some clarification about (see the questions in the end).
So I chose $\Delta x_k = \frac{3}{n}$ and $\xi_k = x_k = k \Delta x_k = \frac{3k}{n}$
So
$$S_n = \sum_{k = 0}^{n-1} f(\xi_k)\Delta x_k = \sum_{k = 0}^{n-1} \left(\frac{3k}{n}\right)^2 \frac{3}{n} = \sum_{k = 0}^{n-1} \frac{27k^2}{n^3} = \frac{27}{n^3} \sum_{k = 0}^{n-1}  k^2 = \frac{27}{n^3}\frac{1}{6}(2n^3-3n^2+n)$$
Now $$\lim_{n\to +\infty} S_n = \frac{27}{3}$$
Whereas $$\int_{-2}^1 x^2\text{d}x = \frac{7}{3}$$

Where am I wrong?

Also: here I chose $\xi_k = x_k = k\Delta x_k$ but what would it be if I chose $\xi_k = x_{k+1}$. How would I use this? What would $\xi_k$ be?

I have some confusions about
Comment: The integral of $x^2$ between $-2$ to $1$ equals $3$, not $7/3$.
Comment: In your sum, you have $\xi_k$ going from $0$ to $3$, not from $-2 $ to $1;\;$ $\int_0^3 x^2 dx=\dfrac{27}3$
Answer:
Where am I wrong?

In your sum, you have $\xi_k$ going from $0$ to $3$, not from $-2$ to $1$, so you computed $\displaystyle\int_0^3x^2dx=\dfrac{27}3.$
Try instead $\; \displaystyle\sum_{k = 0}^{n-1} \left(-2+\dfrac{3k}{n}\right)^2\; \dfrac{3}{n} $, and you should get $\displaystyle\int_{-2}^1x^2dx=\color{red}3$.
Comment: Ahh my bad, thank you!!

A Riemann Sum clarification


Hiding button after collapse is toggled using Javascript

Question: I'm trying to hide the "collapsible" button after it is being pressed.
activities.html:
<button class="collapsible"> </button>

Controller.js:
    var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var gallery1 = this.nextElementSibling;
    if (gallery1.style.maxHeight){
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    }
});
}

I would highly appreciate if someone could help me out of this!
Comment: Please write the code correctly, you didn't forget to add an opening ``?
Answer: To hide your button and remove the space occupied by the button on the page, use .style.display = 'none' on the button element in the event handler:

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");

    var gallery1 = this.nextElementSibling;

    if (gallery1.style.maxHeight) {
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    }

    this.style.display = 'none';
  });
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<button class="collapsible"></button>

To keep the space occupied by the button on the page and make it  invisible, use .style.visibility = 'hidden':

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");

    var gallery1 = this.nextElementSibling;

    if (gallery1.style.maxHeight) {
      gallery1.style.maxHeight = null;
    } else {
      gallery1.style.maxHeight = gallery1.scrollHeight + "px";
    }

    this.style.visibility = 'hidden';
  });
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<button class="collapsible"></button>
Answer: The shortest solution to your problem is
<button class="collapsible" onclick="this.style.display = 'none';">


Why did Bach call them "Inventions"?

Question: Wikipedia defines a musical invention as a short composition (usually for a keyboard instrument) with two-part counterpoint and goes on to say inventions are mainly associated with Bach.
OK.  So what, if any, relation does this have to the modern use of the word "invention" as in "The light bulb was an invention of Thomas Edison"?  Was there something particularly novel about Bach's inventions?
Answer: Bach did not call them inventions.  He first called the two-part ones "praambulum" and the three-part ones "fantasia", then switched to "inventio" and "sinfonia".  Those are Latin (or Italian) terms, not English ones.  "inventio" comes from "invenire", "going inside" and is basically used similarly to "introduction".  It has become a fixed expression in music for introducing and developing a short theme in contrapoint.
Independently, the term "invention" has become synonymous to, well, invention in English.
Comment: I suppose it should be "Präambulum."
Answer: Inventions is a title that Bach uses in his foreword to the collection of this work. It is adapted from the theory of rhetoric. The inventions used by Bach means clearly that he first shows an invented motif and develops of this simple figure an entire (but short) composition:
"Straightforward Instruction, in which amateurs of the keyboard, and especially the eager ones, are shown a clear way not only (1) of learning to play cleanly in two voices, but also, after further progress, (2) of dealing correctly and satisfactorily with three obbligato parts; at the same time not only getting good inventiones, but developing the same satisfactorily, and above all arriving at a cantabile manner in playing, all the while acquiring a strong foretaste of composition."
Title and historical background of inventiones:
http://www.music.qub.ac.uk/~tomita/essay/inventions.html#1
Traditionally, this concept of 'invention' denoted an important stage in composition; it originated from a famous Roman orator, Marcus T. Cicero's rhetoric, which was still widely studied in the 18th-century Germany:
In his De Inventione, Cicero listed five stages in creating an oration, namely invention (inventio), arrangement (dispositio), style (elocutio), memory (memoria) and delivery (pronuntiatio). He explains, 'one must first hit upon what to say; then manage and marshal his discoveries, not merely in orderly fashion, but with a discriminating eye for the exact weight, as it were, of each argument; next go on to array them in the adornments of style; after that keep them guarded in his memory; and in the end deliver them with effect and charm.'
Comment: That's a really good essay on this topic.  Thanks.
Answer: According to Honegger-Massenkeil reference the first musical piece called invention was by Claude Janequin and dates from 1555. This weakens the strong Bach connection.
There the title already described a piece not restricted by a specific scheme or formalism. From this kind of originality it is not far to the phrase that each piece is invented.
Comment: I think "destroy" is the wrong word here.
Comment: I noticed your edit.  I would say that it doesn't so much weaken the Bach connection as show that Bach didn't, uh, *invent* the term "invention."  But he's still strongly associated with it, isn't he?  I mean, Shakespeare didn't invent the sonnet: it was imported from Italy.  But he's still strongly associated with it.
Answer: There is a lot that is special about the work of Bach but the fact that some of it is called Invention has nothing to do with it.
Invention comes from latin and originally means 'discovery'. All the way through the Middle Ages, that was what it meant. Today still, the technical legal term for acquiring ownership of a lost treasure is 'invention'.

Why did Bach call them "Inventions"?


VBA Counting Shapes in Visio

Question: i want to count how many shapes of one type i have on my sheet and save it to a label.
Sub Counter()

Dim shp As Visio.Shape
Dim i As Integer

For Each shp In ActivePage.Shapes
    If shp.Master.Name Like "DV-ED.*" Then
       i = i + 1
        End If
        ActivePage.Shapes("SheetED").Characters.Text = CStr(i)
Next shp
End Sub

Problem is, that after the last shape of that type i get an error

"Run Time Error '91' : Object Variable or With Block not Set"

im not very familiar with VBA
Comment: Check out this question and my answer to it:
http://stackoverflow.com/questions/28603953/identifying-a-shape-parent-in-visio/28605637#28605637 Does that help you?
Comment: i think it doesnt help me. i just need to solve that runtime error. after last shape it occurs at this line:   If shp.Master.Name Like "DV-ED.*" Then
Comment: How about adding another sanity check before `If shp.Master.Name Like "DV-ED.*" Then`, e.g. `If shp.Master<>Nothing Then`
Answer: Before accessing properties like Name of an object, make sure the object is set:
Sub Counter()

Dim shp As Visio.Shape
Dim i As Integer

For Each shp In ActivePage.Shapes
   If shp.Master<>Nothing Then
      If shp.Master.Name Like "DV-ED.*" Then
        i = i + 1
      End If
      ActivePage.Shapes("SheetED").Characters.Text = CStr(i)
   End If
Next shp
End Sub

VBA Counting Shapes in Visio


Faster way to slice a (raw) vector?

Question: Problem
I am looking for a fast (ideally constant-time) way to take a large slice a long raw vector in R. For example:
obj <- raw(2^32)
obj[seq_len(2^31 - 1)]

Even with ALTREP, base R takes too long.
system.time(obj[seq_len(2^31 - 1)])
#>    user  system elapsed
#>  19.470  38.853 148.288

Why?
Because I am trying to speed up storr in order speed up drake. I want storr to save long raw vectors more quickly. writeBin() is super fast, but it still cannot handle vectors more than 2^31 - 1 bytes long. So I want to save the data in manageable chunks as described here. This almost works, but creating the chunks is too slow, and it duplicates too much data in memory.
Ideas
Let's create a function
slice_raw <- function(obj, from, to) {
  # ???
}

which is essentially equivalent to
obj[seq(from, to, by = 1L)]

and which is O(1) in both time and memory. In theory, all we should need to do is

Pass obj to a C function.
Create a new pointer to the first byte of obj.
Increment the new pointer to the start of the slice.
Create a RAWSXP at the new pointer with the appropriate length (less than 2^31 bytes).
Return the RAWSXP.

I have a background in C, but I struggle to take full control of R's internals. I would like to access the C pointers inside SEXPs so I can do basic pointer arithmetic and create R vectors of known lengths from undecorated C pointers. The resources I found on R's C internals do not seem to explain how to wrap or unwrap pointers. Do we need Rcpp for this?
The following rough sketch gets at what I am trying to do.
library(inline)
sig <- c(
  x = "raw",         # Long raw vector with more than 2^31 - 1 bytes.
  start = "integer", # Should probably be R_xlen_t.
  bytes = "integer"  # <= 2^31 - 1. Ideally coercible to R_xlen_t.
)
body <- "
Rbyte* result;           // Just a reference. Want to avoid copying data.
result = RAW(x) + start; // Trying to do ordinary pointer arithmetic.
return asRaw(result);    // Want to return a raw vector of length `bytes`.
"
slice_raw <- cfunction(sig = sig, body = body)

EDIT: some more potential workarounds
Thanks to Dirk for spurring my thinking on this one. For small enough data, we can use fst to save a single-column data frame, where the column is the raw vector we actually care about. This use of fst is faster than writeBin()
library(fst)
wrapper <- data.frame(actual_data = raw(2^31 - 1))
system.time(write_fst(wrapper, tempfile()))
#>    user  system elapsed
#>   0.362   0.019   0.103
system.time(writeBin(wrapper$actual_data, tempfile()))
#>    user  system elapsed
#>   0.314   1.340   1.689

Created on 2019-06-16 by the reprex package (v0.3.0)
Unfortunately, it is difficult to create data frames with 2^31 or more rows. One hack is to convert the raw vector into a matrix first, and we avoid the usual integer overflow because (2^31 - 1)^2 bytes is several exabytes.
library(fst)
x <- raw(2^32)
m <- matrix(x, nrow = 2^16, ncol = 2^16)
system.time(write_fst(as.data.frame(m), tempfile()))
#>    user  system elapsed
#>   8.776   1.459   9.519

Created on 2019-06-16 by the reprex package (v0.3.0)
We still leave saveRDS() in the dust, but we no longer beat writeBin(). The conversion from a data frame to a matrix is slow, and I am not sure it would scale well.
library(fst)
x <- raw(2^30)
m <- matrix(x, nrow = 2^15, ncol = 2^15)
system.time(write_fst(as.data.frame(m), tempfile()))
#>    user  system elapsed
#>   1.998   0.408   2.409
system.time(writeBin(as.raw(m), tempfile()))
#>    user  system elapsed
#>   0.329   0.839   1.397

Created on 2019-06-16 by the reprex package (v0.3.0)
If, like Dirk suggested, we can use an R_xlen_t to index the rows of a data frame, we might be able to avoid converting anything.
Comment: Have you looked at [fst](https://www.fstpackage.org/) which already does multithreading and optimal chunking?  It is AFAIK the fastest way to/from disk.
Comment: Maybe do what R does and index with a double -- difference betweeb `R_len_t` and `R_xlen_t`.
Comment: You never "need" Rcpp because it is "merely" a layer on top of the _same_ C API provided by R which any C or C++ routine would face.  But Rcpp may make a few things easier. In particular, we have a number of `Rcpp::XPtr` examples.  As for your issue, why not just use `mmap` to read segments of a memory-mapped file?  No size constraints there.
Comment: Easier, absolutely. I just noticed that `Rcpp::RawVector`s understand ordinary pointer arithmetic, which is already half the solution. For that route, all that remains is a way to control the termination of each slice so `writeBin()` does not try to write the entire tail of the original data. (For raw vectors, we cannot use the `size` argument to tell `writeBin()` to stop early). Would `Rcpp::XPtr`s help? I do not yet see the connection to smart pointers. I would rather not free (or allocate) any dynamic memory here, automatically or otherwise.
Comment: Also, I had a look at the `mmap` R package. `mmap()` would be perfect if the data were already in storage. However, for `storr` and `drake`, I am looking for a way to store data that initially only exists in memory. In `mmap`, this happens through `as.mmap()`, which in turn calls `writeBin()` with no chunking. So it suffers from the same issues I am facing here.
Comment: Yes, and I do have plans for it: https://github.com/richfitz/storr/issues/103. But because `storr` needs to work on arbitrary data structures, I still think there is value in raising the efficiency to the level of `writeBin()` for non-`data.frame`s.
Comment: Wait... the solution was right in front of my nose: use `fst` to store a single-column data frame, where the column is the raw vector. Thanks for the nudge, Dirk!
Comment: Much better. I was thinking for a way to tell you to not look into optimising `writeBin` as Mark had done just that with `fst`.  But I ddn't quite connect the dots either....
Comment: Actually, I think I may have spoken too soon. `data.frame(x = raw(2^32))` fails due to integer overflow. There still may be a workaround, but I will need to do some more digging. The encouraging part is that `fst` is indeed faster than `writeBin()` for small enough data for both approaches to handle.
Comment: I like that idea. I am having trouble with `df <- list(raw_vector); class(df) <- "data.frame"` because then `read_fst()` segfaults, presumably because the dimensions are missing. Is there a way to assign an `R_xlen_t` number of rows post hoc? `dim<-` seems to reject doubles, and I am having trouble finding an equivalent function in `Rcpp`.
Answer: Although, currently, data.frame's with long vector columns are not supported very well, you can still use fst to serialize long raw vectors:
# method for writing a raw vector to disk
write_raw <- function(x, path, compress = 50) {

  # create a list and add required attributes
  y <- list(X = x)
  attributes(y) <- c(attributes(y), class = "data.frame")

  # serialize and compress to disk
  fst::write_fst(y, path, compress)
}

# create raw vector of length >2^31
x <- rep(as.raw(0:255), 2^23 + 10)

# write raw vector
write_raw(x, "raw_vector.fst", 100)

With this scheme there is no need to split the vector in multiple parts (which, as you already indicate, will slow down serialization significantly). The raw vector can be re-read without any copying or slicing:
# method for reading a raw vector from disk
read_raw <- function(path) {

  # read from disk
  z <- fst::read_fst(path)

  z$X
}

z <- read_raw("raw_vector.fst")

fst::hash_fst(x) == fst::hash_fst(z)
#> [1] TRUE TRUE

(note that at the moment you need the fst development version for reading with long vector support)
In your setup, you will always be serializing the complete raw vector to disk as a whole (just like saveRDS(). Because you do not need random access to the stored vector, the meta-data stored in the fst file is a bit of an overkill. You might also test a setup where you compress the raw vector using compress_fst() and then store the result using saveRDS(raw_vec, compress = FALSE).
The advantage of such a setup would be that the compressor can use bigger chunks for compression, increasing the compression ratio (effect can be significant). Using larger chunks can also speed up compression.
On the other hand, the disadvantage is that you are not compressing during the write to disk as with write_fst(), so that effect might slow down your serialization. And you don't have random access anymore, but you don't really need that anyway.
If you implement a two-step process (first compressing the data and then serializing it), you will be able to allow for different compressors if the user would opt for that (for example slower compressors with very high compression ratio for slow disks).
Answer: Had the same challenge. Here is small Rcpp function to accomplish the task
Rcpp::RawVector raw_slice(
  const Rcpp::RawVector &x,
  const R_xlen_t offset,
  const R_xlen_t size) {

  Rcpp::RawVector result = Rcpp::no_init(size);
  memcpy ( &result[0], &x[offset - 1], size );
  return result;
}

Faster way to slice a (raw) vector?


Is Emajor the dominant chord in the key of A minor?

Question: I read somewhere that Emajor is the dominant (V) chord in A minor. Is this correct? If so, why is it not Eminor, since the A minor scale has no sharps or flats in it?
Answer: Yes it is the dominant chord. The third is sharpened to G# to make a major chord, which gives a stronger cadence when moving V-i. This is why the Harmonic Minor has a sharpened seventh degree, to create the sharpened third in the dominant chord (or leading note in the scale, whichever way you want to think about it). In common-practice harmony, the strong, major dominant chord helps define the key, so the Harmonic Minor scale, with its sharpened seventh is used. (The major V chord of the Harmonic Minor helps the harmony to function, hence the name.)  However, if one is not using common-practice harmony, for instance in a lot of rock, pop, jazz and folk music, it is perfectly acceptable to use the Natural Minor, in which case chord V is minor, and the key is defined less strongly by any cadences moving from v-i.
Comment: being picky, like what I am sometimes - would you say it's THE dominant chord, or ONE OF THE dominant chords?
Comment: Personally I would say _the_ dominant chord.  E7 is usual.
Comment: I always thought you obtained the basic chords by building triads _from_ alternating notes in the scale. e.g in C-Major C+E+G => C, A+C+E => Am, etc. Is that trick only for major scales or is it just bunk?
Comment: @wim - E7 is usual, but if Em or Em7 are used, are they still dominant chords? Dominant and usual are not the same !
Comment: @Mr.Boy - the trick of using alternating notes works for most common scales - Blues perhaps being an exception. Which is my point. Taking notes 5,7 and 9 from a natural minor scale produces the minor V. Still a dominant chord, I think.
Comment: In classical usage, a chord built on the fifth scale degree is a dominant chord, since it's the fifth scale degree.  In jazz, a Mm7 chord (major chord, minor 7th) is generally called a dominant 7th, no matter what its relationship to the tonic.
Comment: In jazz, "the" dominant chord would be the fifth scale degree V7, e.g. in either keys A or A- it would be E7 (or some other "dominant" colouration, often a b9 or #9).  BobRodes is also correct that any chord with a major 3rd and minor 7th would also be called "a" dominant chord by jazz guys.  Calling E- a dominant chord here would almost always be misleading or just plain wrong.  Melodic minor is much more common than natural minor in jazz.  I can't speak for classical music.
Comment: @Mr.Boy that's more or less correct, but in minor keys the more tasty sounding melodic minor or harmonic minor is often the scale you should build those chords off, rather than the somewhat "bland" natural minor
Comment: @wim I've never seen the "A-" notation, is this the same as "Am" or A minor?
Comment: yes, common in jazz real books
Answer: It is correct to a certain extent. You are absolutely right that the 'natural' A minor scale has no sharps in it, and the v chord would be an E minor.
However, minor scales come in several 'flavors'. There is the natural minor, harmonic minor, and melodic minor. The harmonic minor is the same as the minor scale with the 7th raised by a semi-tone.
Ergo, the A minor harmonic scale is A,B,C,D,E,F,G#,A - which as you can see provides the G# that is present in the E major chord. The harmonic minor is quite common and thus it can be said that the dominant V (upper case is important here) chord for A minor is E major.
Answer: When people refer to a "minor scale", they don't always think of the natural minor scale. Quite often, they think of the harmonic minor scale, which is similar to the natural scale with the seventh degree raised by a semitone.
As the seventh degree is the third of the dominant chord, the dominant chord is major in harmonic minor scales.
For example, the A harmonic minor scale is A B C D E F G# and the dominant chord is E G# B, i.e. E major.
Answer: The point of any dominant chord is to lead back to the tonic chord. The best way to do this is by using the leading tone (Natural 7th in major, raised 7th in minor). Because of how the natural minor scale is formulated, the leading tone is omitted from the scale. This however does not change the fact that the leading tone gives a very strong pull to the tonic. This gave rise to the other two minor scales the other posts have alluded to.
Regardless of whether you are in major key or minor key dominant chords will contain the leading tone whether it is the 3rd of the chord (V) or the root of the chord (viio). To do this in minor the 7th must be altered and because of this alteration the parallel major and minor keys will share the same dominant chords because of how the chords are built.
So yes E major is a dominant chord of A minor.
Answer: It's probably more often the V because it has that G#. That comes from both the harmonic and the melodic minors. Sometimes Eminor is the V and it is used in lots of songs.Yes, it originates from the natural minor (or in some cases the melodic). It isn't so decisive, but still pushes towards I, which is the job of any V chord.
Answer: The notes of the dominant chord of a minor is E/G#/B. E - G# is a Major third while E - B is a perfect fifth. This makes the chord Major.
I think you are getting confused by what it means for a scale to minor / Major and what it means for a chord to minor / Major.
A Major Chord is one with a Major third and a perfect fifth. This can happen in both minor and Major keys and is not fixed to what key you are in.
Comment: not necessarily true. There's a minor dominant.E/G/B or m7th E/G/B/D.
Comment: Neil, you're using jazz semantics.  Classical semantics are more concerned with the idea that dominant is the fifth scale degree.  Any chord built on the fifth scale degree is called dominant, just as any chord built on the second is called supertonic.  So, no, Tim isn't getting confused.  He's just speaking a different dialect.  :)
Answer: E7 is the Dominant of A minor.
E major is almost correct but, you are missing the minor 7.
The major third and the minor 7 of every dominant chord make the interval of a tritone.
Comment: E7 would be the Dominant 7th.
Answer: The major key has two dominant chords: V (G) and vii (Bdim). Both of these are dominant to the Cmajor chord (tonic) and also have a dominant function to the A minor chord which is also a tonic chord and contains the same chord tones as a C6.
Additionally, there are secondary dominant chords, these are found outside the key. The secondary dominant for the A minor chord is Emajor.
Answer: A natural minor scale has these notes:
A, B, C, D, E, F, G
Therefore the A natural minor has this chord progression:
I -   Am
II -  Bdim
III - C
IV -  Dm
V -   Em
VI -  F
VII-  G

However for an A harmonic minor scale which has these notes:
A, B, C, D, E, F, G#
has this chord progression:
I   - Am
II  - Bdim
III - C#5
IV  - Dm
V   - E
VI  - F
VII - G#dim

Although in many cases they would prefer this chord progression:
I   - Am
II  - Bdim
III - C#5
IV  - Dm
V   - E7
VI  - F
VII - G#dim


How to find the exact and likelihood ratio p-value for a hypothesis test that a population sex ratio is 1:1?

Question:
Skulls were excavated from a dig. The sex of each skull was determined
  by anatomical appreciation.  For Sites A, the data was Male=162,
  Female=110.
a) Find the exact p-value for a hypothesis test about whether the sex
  ratio of the population buried at this sites was 1:1.
b) Instead use a likelihood ratio test.  Find the likelihood ratio
  test statistic, and resulting p-value.  Compare with (a).

Any help would be appreciated.
Comment: To me, the interesting part of this question concerns what assumptions would be needed to justify the binomial distribution in the first place!
Answer: This is a binomial test. The hypothesis is that if you choose a skull you have a 50% chance it is female. Kind of like a coin flip, except instead of testing heads and tails you're testing male and female.
$X = 110$
$N = 110 + 162 = 272$
$p = .5$
$\alpha = .05$
Formally stated the hypotheses are:
$H_0: p = .5$
$H_1: p \ne .5$
To find the test statistic assuming the above alpha value and given that we have a two tailed test we consult this z table: http://lilt.ilstu.edu/dasacke/eco148/ztable.htm
Because it's a two-tailed test we need to find the z-value of alpha/2 which is 1.96. So that's our test statistic.
Then we set up a binomial test and evaluate it like so (refer to http://www.elderlab.yorku.ca/~aaron/Stats2022/BinomialTest.htm):
$$z = \frac{\frac{X}{N} - p}{\sqrt{\frac{pq}{N}}}=\frac{\frac{110}{272} - .5}{\sqrt{\frac{.5*.5}{272}}} = -\frac{.0956}{.0303} = -3.1551$$
Since the absolute value of the statistic we calculated is greater than the test statistic of 1.96 we reject the null hypothesis that the proportion of female skulls is .5.
As far as likelihood goes, we can find the probability of heads given the number of female heads found in the population of 272 total heads found.
$$L(p | n, y) = {n \choose y}p^y{(1-p)}^{n-y}$$
Where n is the total number of heads found, y is the number of female heads found, p is the anticipated ratio that $y \over n$ may represent.
$$L(.5 | 272, 110) = {272 \choose 110}{.5}^{110}{(1-.5)}^{272-110}= 0.00033$$
I computed this in Wolfram Alpha here:
http://www.wolframalpha.com/input/?i=choose%28272%2C110%29*%28.5%5E110%29%281-.5%29%5E%28272-110%29
So both results agree! We can conclude it is very unlikely the ratio of male and female skulls is in fact 1:1.
Comment: Thanks for the feedback @whuber. Hmm. I think my point was that both methods provide evidence against the skulls having a true proportion of 50/50. Let me think some more and I'll try to update my response.
Comment: The *test statistic* is $z$. The value of $1.96$ is usually called a "critical value."  In what sense does a likelihood at $p=1/2$ of $0.00033$ "agree" with the hypothesis test? (The answer is that there is no meaningful way to compare these two calculations. This exposition includes some useful computation but otherwise looks rather mixed up.) Do you think you could straighten out your explanations?
Answer: You only know the number of the females and males in site A? Do you want to test all the sites have the same ratio or site A has ratio 1:1?
I guess this is a problem wrt to Contingency table, for example, you may write it down in the form:
\begin{align*}
  &  A\ B\ C\ sum\\
F\\
M\\
sum\\
\end{align*}
Then you may use some formulas to calculate p values,etc.
Comment: Welcome to our site, Julie! Could you please be more explicit about what the rows and columns of this contingency table would be and what "formulas" you would propose? The only attributes evident in the question are gender--male or female--so I'm having trouble seeing how you would make a two-way table out of this.
Comment: @whuber, I think we can formulate in this way if following the hint. Assume that the total number is fixed, which is $n=272$, then we take the hypothesis test: $H_0: p=0.5$ vs $H_1: p\ne 0.5$, where $p$ is the probability that one observation is female. Then we calculate the test statistics $T=C_n^{110}  (0.5)^{110}(1-0.5)^{162}$. So that you can compare this with the quantiles of the binomial distribution with parameter n and 0.5.


Oblique bracket, stochastic integral

Question: Let $X_t=\int_0^tsW_s^2dW_s$. How to set $<\int_0^tW_scos(s)dX_s>$? is it: $<\int_0^tW_scos(s)sW_s^2dW_s>=\int_0^ts^2W_s^6cos^2(s)ds$
Answer: $$dX_t=t\,W_t^2\,dW_t$$
we have
$$Y_t=\int_{0}^{t}\cos(s)\,W_s\,dX_T=\int_{0}^{t}s\cos(s)W_s^3\,dW_s$$
The quadratic variation of Ito integral  $Y_t$ is given by
$$\langle Y_t\rangle=\left[Y,Y\right](t)=\left[\int_{0}^{t}s\cos(s)W_s^3\,dW_s,\int_{0}^{t}s\cos(s)W_s^3\,dW_s\right](t)=\int_{0}^{t}s^2\cos^2(s)W_s^6ds$$
Comment: Thanks a lot @Behrouz Maleki!

Oblique bracket, stochastic integral


jQuery Dropdown Mouseout only when outside of the div

Question: Problem
The MouseOut should only go out when the user goes outside the DIV. So they can hover over the links etc. It just stays expanding it does not go back
JS Fiddle and DEMO (http://jsfiddle.net/GHaL7/3/)
jQuery
$(document).ready(function () {
    $("#hoverButton").mouseover(function () {
        $('div.hoverMenu').slideDown(2000)
    });
    $("div.hoverMenu").mouseout(function () {
        $('div.hoverMenu').slideUp(2000)
    });
});

CSS/HTML

SHOP

Sub Cat

Sub Cat

Sub Cat

Sub Cat

Sub Cat

Sub Cat

Sub Cat

Sub Sale Cat

Shop Cat

Shop Cat

Sale Cat

Comment: First you have two slideUp, but that will not work because there is a margin-top and margin-bottom to seperate those sub menus so it all does not look black.. I get what you are trying but I cant figure it
Comment: @TheBlackBenzkid check to this http://jsfiddle.net/GHaL7/3/
Comment: It does not work @RohitAzad Thanks for the post - it slides up before you can even click SUB CAT..
Answer: Why you dont use slideUp() in your script?
possible solution: http://jsfiddle.net/GHaL7/23/
Comment: or try to add it to the hovered li element, cause it will function as wrapper;-)
Comment: I think because he has a margin gap between the sub menus, so even if you move your mouse between those sub menus it still will slideup still does not stay fixed.
Comment: Can you show me the JSFiddle - also please do not delete your answer. Other people just post and delete because they cant solve.
Comment: can you please show me the sample? I am up http://jsfiddle.net/GHaL7/21/ different 21 tries! And no luck!


CMake cannot find static wxWidgets under msys2

Question: I'm trying to build a project with statically linked wxWidgets (I would just like to point out that it compiles&links just fine with shared libraries). This is relevant part of my CMakeLists.txt:
set(wxWidgets_USE_STATIC ON)
find_package(wxWidgets REQUIRED)

and this is error I get:
$ make
-- Boost version: 1.64.0
-- Found the following Boost libraries:
--   system
--   filesystem
--   program_options
CMake Error at C:/Dev/msys64/mingw64/share/cmake-3.9/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
  Could NOT find wxWidgets (missing: wxWidgets_LIBRARIES)
Call Stack (most recent call first):
  C:/Dev/msys64/mingw64/share/cmake-3.9/Modules/FindPackageHandleStandardArgs.cmake:377 (_FPHSA_FAILURE_MESSAGE)
  C:/Dev/msys64/mingw64/share/cmake-3.9/Modules/FindwxWidgets.cmake:953 (find_package_handle_standard_args)
  CMakeLists.txt:16 (find_package)

-- Configuring incomplete, errors occurred!

The static libraries are however installed
$ ls -l /mingw64/lib | grep libwx
-rw-r--r-- 1 tv185035 Domain Users 668K Sep 13 20:16 libwx_baseu_net-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 453K Sep 13 20:14 libwx_baseu_net-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users  84K Sep 13 20:16 libwx_baseu_xml-3.0.a
-rw-r--r-- 1 tv185035 Domain Users  68K Sep 13 20:14 libwx_baseu_xml-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 5.9M Sep 13 20:16 libwx_baseu-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 4.6M Sep 13 20:14 libwx_baseu-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 6.8M Sep 13 20:16 libwx_mswu_adv-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 3.2M Sep 13 20:14 libwx_mswu_adv-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 1.8M Sep 13 20:16 libwx_mswu_aui-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 1.1M Sep 13 20:14 libwx_mswu_aui-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users  28M Sep 13 20:16 libwx_mswu_core-3.0.a
-rw-r--r-- 1 tv185035 Domain Users  12M Sep 13 20:14 libwx_mswu_core-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 278K Sep 13 20:16 libwx_mswu_gl-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 175K Sep 13 20:14 libwx_mswu_gl-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 2.6M Sep 13 20:16 libwx_mswu_html-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 1.4M Sep 13 20:14 libwx_mswu_html-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 2.2M Sep 13 20:16 libwx_mswu_propgrid-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 1.6M Sep 13 20:14 libwx_mswu_propgrid-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 331K Sep 13 20:16 libwx_mswu_qa-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 193K Sep 13 20:14 libwx_mswu_qa-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 1.6M Sep 13 20:16 libwx_mswu_ribbon-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 646K Sep 13 20:14 libwx_mswu_ribbon-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 3.6M Sep 13 20:16 libwx_mswu_richtext-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 2.4M Sep 13 20:14 libwx_mswu_richtext-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 849K Sep 13 20:16 libwx_mswu_stc-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 2.1M Sep 13 20:14 libwx_mswu_stc-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 404K Sep 13 20:16 libwx_mswu_webview-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 634K Sep 13 20:14 libwx_mswu_webview-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users 4.4M Sep 13 20:16 libwx_mswu_xrc-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 1.1M Sep 13 20:14 libwx_mswu_xrc-3.0.dll.a
-rw-r--r-- 1 tv185035 Domain Users  90K Sep 13 20:16 libwxregexu-3.0.a
-rw-r--r-- 1 tv185035 Domain Users 2.7M Sep 13 20:16 libwxscintilla-3.0.a

I have no idea why it refuses to work. Will anyone please help?
Comment: Why are you running `make`? You should first generate the build files using `cmake` (although you should be using `ninja` anyways these days instead of `make`). You should point the CMake library search path towards the directory you listed, so it can search it for libraries.
Comment: `make` reruns `cmake` if needed no? But I tried to run `cmake` directly and result is the same.
Answer: Hm, so I didn't get it to work with wxWidgets_USE_STATIC, but following does work (and produce static executable in release version)
cmake_minimum_required(VERSION 3.9)

set(PROJECT_NAME "jibril")

project(${PROJECT_NAME})

set(BUILD_SHARED_LIBS OFF)
set(BUILD_STATIC_LIBS ON)

string(TOLOWER "${CMAKE_BUILD_TYPE}" build_type_lower)

if(NOT build_type_lower MATCHES debug)
    set(Boost_USE_STATIC_LIBS ON)
    set(Boost_USE_STATIC_RUNTIME ON)
endif()
find_package(
    Boost REQUIRED
        system
        filesystem
        program_options
)
find_package(wxWidgets REQUIRED)
string(
    REPLACE
        ";-Wl,--subsystem,windows;-mwindows"
        ""
        wxWidgets_LIBRARIES
        "${wxWidgets_LIBRARIES}"
)

add_executable(
    ${PROJECT_NAME}
        src/main.cpp
)
target_include_directories(
    ${PROJECT_NAME}
        PUBLIC ${Boost_INCLUDE_DIRS}
        PUBLIC ${wxWidgets_INCLUDE_DIRS}
)
target_compile_options(
    ${PROJECT_NAME}
        PRIVATE -Wall
        PRIVATE -Wextra
        PRIVATE -Werror
        PRIVATE -Wduplicated-cond
        PRIVATE -Wduplicated-branches
        PRIVATE -Wlogical-op
        PRIVATE -Wrestrict
        PRIVATE -Wnull-dereference
        #PRIVATE -Wold-style-cast
        #PRIVATE -Wuseless-cast
        #PRIVATE -Wdouble-promotion
        PRIVATE -Wshadow
        #PRIVATE -Wformat=2
)
target_link_libraries(
    ${PROJECT_NAME}
        ${Boost_LIBRARIES}
        ${wxWidgets_LIBRARIES}

        optimized -static
        optimized -luuid
        optimized -lcomctl32
        optimized -loleacc
        optimized -lpng
        optimized -lz
        optimized -s
)

Answer: I have made it works,
set(wxWidgets_USE_LIBS ON) <-- add this before find_package
find_package(wxWidgets REQUIRED)

And specify the wxWidgets_LIB_DIR in cmake explicitly, example,
wxWidgets_LIB_DIR=W:/wxWidgets-3.0.4/lib/vc_x64_lib


Proof explanation of Hall's Marriage Theorem?

Question: I don't understand the last paragraph of this proof.
Why the result of $j+t$ vertices of $W_1$ consisting of these $t$ vertices together with the $j$ vertices removed from $W_1$ has $\color{red}{\textrm{fewer than}}$ $j+t$ neighbors?
Answer: The set $W_1'$ has $j$ vertices and $|N(W_1')|=j$. For contradiction, we have assumed that there is a set $U \subseteq W_1 \setminus W_1'$ with $t$ vertices and whose neighborhood has size less than $t$. Thus the neighborhood of $W_1' \cup U$ has size less than $j+t$.
Comment: Since $W_1-W_1'\subset W_1,$ why do we need to construct the contradiction? Can I directly say "by inductive hypothesis $|N(A)|\ge |A|,$ for $A=W_1-W_1'$"?
Comment: That is because in the induction hypothesis our bipartition was $ H=(W,F) $ on which the Hall theorem's condition of $|N(A)| \geq |A| \forall A \subseteq W$ holds.

But in the last part of the proof our bipartion becomes $K(W_1-W'_1,W_2-W'_2)$ and on the neighborhood set $|N(W_2-W'_2)|$ we are not sure weather the Hall theorem's condition holds.


Why would loading nodes by UUID not work in a drush command?

Question: I have a simple bit of test code to load nodes by UUID:
$uuids = ['5e331255-adf6-423e-a355-dc02c621ffcd'];
$nids = \Drupal::entityTypeManager()->getStorage('node')
  ->getQuery()
  ->condition('uuid', $uuids, 'IN')
  ->execute();

When I execute this code in hook_page_attachments_alter(), or anywhere else in a rendered page build, $nids is populated as expected with the correct node ID.
When I execute exactly the same code, verbatim, in a drush command, $nids is empty.
Loading the node by ID works fine in both contexts:
$node = \Drupal::entityTypeManager()->getStorage('node')->load(12345);

This happens with the same code/database in multiple environments (Lando, ACSF, standard LAMP), and I've confirmed that drush is connecting to the correct database everywhere.
Are there any obvious properties of the node or storage system, or configuration of drush, which could be responsible for this?
Content moderation, revisions, and translations are all enabled for the node's content type, in case it matters.
Comment: Does it help to disable the query access check? `->accessCheck(FALSE)`
Comment: If I had a penny for every time I've forgotten that...thank you hugely @4uk4, that is indeed the problem and now I know which module I need to patch and file a bug report to. If you put an answer in I'll accept it
Answer: Disable the query access check
  ->accessCheck(FALSE)

or use this service
$node = \Drupal::service('entity.repository')->loadEntityByUuid('node', $uuid);


Create multiple custom node add pages

Question: I'm using Display Suite to create custom multiple layouts for content. Is it possible to do something similar to the node/add/mycontent page? I want to be do show/hide and organize fields on the edit and add pages.
Answer: You can check out Field group module. It allows you organize the fields with different transitions.
Comment: Does field group module support multiple different displays, or just adjust the default?
Comment: The module sits on the Manage Fields section section rather than the Manage Display section. So the changes made to the fields will be universal for the all the display modes under a specific content type.

Create multiple custom node add pages


Is it safe to package C++11 software on current Linux distributions?

Question: As a downstream maintainer in a Linux distribution, some of the packages that I usually maintain are starting to use the C++11 features in their code base. All of them depend on different libraries packaged by the Linux distributions.
Problems with the ABI could appear when mixing C++11 code with C++98 and AFAIK, most of the current major Linux Distributions are not enabling the C++11 flag by default when compiling software to generate packages.
The question is: How are the major Linux distributions handling the entry of C++11 code? Is there a decent way of checking or avoiding these problems with the ABI when using system libraries?
Thanks.
Comment: could you provide a reference about "most of the current major Linux Distributions are not enabling the C++11 flag" ?
Comment: @Puppy have you seen the example Yakk was referring to? Maybe you should ask for it, instead of calling it BS because "nothing necessitates it". Nothing necessitates it. Yet it is allowed to happen. (On a practical level there's reality. Whether the standard wants it or not)
Comment: are you mixing g++ versions? If not I believe this issue was fixed in GCC 4.8
Comment: That's assuming there's only that "accident". As there is no standards governing ABI and ABI interoperability, I'm not sure how a authoritative answer would come about. I'm pretty sure it needs more than "compiler devs would never do that, no?!"
Comment: @Mgetz 4.8.1 still has at least one mentioned issue, and 4.8.2 has a few really minor ones mentioned.
Comment: @Yakk any hope this was fixed in 4.9+ then? Or is this going to have to wait until 5.0?
Comment: @Mgetz I suspect it would get worse when `std::list` compliance occurs.  The issues remaining in 4.8.2 in the link look really minor (exporting `vector::data()`, `istreambuf_iterator::reference`, exporting the result of a subtracted reverse iterator with a broken underlying iterator).
Comment: @Yakk wouldn't C++98 code compiled with a C++11 compliant `std::list`, just use the C++11 list behavior? That would still be compliant with C++98 last I checked.
Comment: @Mgetz A problem is that a C++98 compiled library linking with a C++11 library compiled `std::list` will disagree about the size and layout of `std::list`, rendering them incompatible.
Comment: @Yakk: Bullshit. That would only occur if the maintainer of that specific library decided to change his binary layout, which is far from guaranteed. For example, `std::list` can offer O(1) time in C++98 too.
Comment: @Puppy That is exactly what happened in gcc 4.7.1.  The existing gcc `std` uses an O(n) `size()` and a `std::list` that lacks a size field, which means if they become C++11 compliant they will have to break binary compatibility.
Comment: @Yakk: Which they undid as fast as humanly possible.
Comment: There is no difference between compiling GCC 4.7.1's std::list with -std=c++11 and -std=c++98. You're just as broken. Unless they decided to only break if you're compiling in C++11 mode, which is still their decision. You only suffer increased breakage with C++11 if a library vendor made it that way.
Comment: I guess you've never heard of Itanium ABI? There is very definitely an ABI Standard. And it is definitely backwards compatible. It's no accident that GCC and Clang are almost completely binary compatible, nor that they are so across virtually every version (disregarding GCC's oops and non-Itanium platforms like Windows).
Comment: @DRC about the C++11 flag in major distros, I meant: the compiler flag is not enabled by default for all the software at the moment of generating packages. For references, I would say: do we have any documenting that C++11 flag is on when compiling software?
Answer: The issue has nothing to do with C++11 vs C++98 except that C++11 can motivate binary changes. There is nothing special about binary changes motivated by C++11. They are just as breaking or non-breaking as regular binary changes. Furthermore, they are only changed if the library maintainer specifically chooses to change his binary interface.
In other words, this has nothing to do with the Standard version and everything to do with the library, unless the library explicitly chooses to offer two different binary interfaces to different Standard versions (which is still a library choice). Excepting this case, you are just as broken in C++98 as you are in C++11. Itanium is backwards compatible between the C++11-supporting versions and the C++98-supporting versions, so the compiler ABIs are not broken.
From memory, unless you're using 4.7.0 which they broke for fun and then unbroke, you're pretty much safe with libstdc++- they are storing up ABI breakage for a future release when they can make one big break.
In other words, whilst the transition period to C++11 can introduce additional motivation to break ABI and therefore additional risk, actually using C++11 itself does not introduce any additional risk.