title: How to achieve Set+Part like behaviour in custom Set function?

text: So I've been toiling away on my DataFrame package. I've been trying to get `Set` to work with it, but it seems it either can't be done (ie via `UpValues`), or is ill advised. So I decided to bite the bullet and just roll my own custom `DFSet` function. But I can't figure out how the get the evaluation to work like it does when you `Set` the `Part` of something. This is my `DFSet` function:               DFSet[Part[DataFrame[DFMetadata[metastore_], DFData[store_]], name_String], data_List] :=         (             If[                 Length@data =!= metastore["Length"],                  Abort[]             ];             If[                 !MemberQ[metastore["Names"], name],                  metastore["Names"] = Append[metastore["Names"], name]             ];             store[name] = Developer`ToPackedArray@data;         )      The idea is that it would be called like this:               DFSet[frame[["a"]], {1, 2, 3}]      The problem is that if I run it as is the `Part` bit will try to evaluate and that won't do. But if I set the attribute `HoldFirst` on `DFSet` `frame` won't evaluate to its `OwnValue`. A test case with code:               (****Code needed for a working test case but not part of the problem****)     (*Helper functions*)     StringVectorQ[x_] := MatchQ[x,{__String}]     TopMatrixQ[x_] := Length[Union@(Length/@x)]==1     (*Constructor*)     DataFrame[names_?StringVectorQ, data_?TopMatrixQ] :=          Module[             {store, metastore, length},             If[Length@First@data =!= Length@names, Abort[]];             store = Unique[DFstore];             metastore = Unique[DFmetastore];             metastore["Length"] = Length@First@Transpose@data;             metastore["Names"] = names;             Thread[                 Set[#1,#2]&[store/@names, Developer`ToPackedArray/@Transpose@data]             ];             DataFrame[DFMetadata[metastore], DFData[store]]         ]      (*Pretty Formatting*)     Format[DataFrame[DFMetadata[metastore_], _DFData]] :=          "DataFrame"[Length[metastore["Names"]]]     (*UpValue for Part*)     DataFrame /: Part[DataFrame[DFMetadata[metastore_], DFData[store_]], name_String] :=          (             If[!MemberQ[metastore["Names"], name], Abort[]];             store[name]         )     (**************************)     (****The actual problem****)     (*DFSet function*)     DFSet[Part[DataFrame[DFMetadata[metastore_], DFData[store_]], name_String], data_List] :=         (             If[                 Length@data =!= metastore["Length"],                  Abort[]             ];             If[                 !MemberQ[metastore["Names"], name],                  metastore["Names"] = Append[metastore["Names"], name]             ];             store[name] = Developer`ToPackedArray@data;         )     (*******************)     (****A test case****)     (*Arrange*)     frame = DataFrame[{"a","b"},{{1,2},{1,2},{1,2}}]     (*Act*)     DFSet[frame[["c"]],{3,3,3}]     DFSet[frame[["b"]],{4,4,4}]     (*Assert*)     frame[["c"]]=={3,3,3}     frame[["b"]]=={4,4,4}     (****Output from successful test should be:     Out=DataFrame[2]     Out=True     Out=True     *)


title: Using a MacBook's builtin sudden motion sensor with Manipulate

text: With the following code I can get the value of the "Sudden Motion Sensor", which is build into MacBooks:               Dynamic@ControllerState[{"X", "Y", "Z"}, ControllerPath -> {"Sudden Motion Sensor"}]      I want to use the values to control some variables in a `Manipulate` statement, however this doesn't seems to work:               Manipulate[x,"X" -> {x, -1, 1}, ControllerPath -> "Sudden Motion Sensor"]


title: BarChart FrameLabels with only partial Frame?

text: This test BarChart is generated by the code that follows it: ![enter image description here](http://i.stack.imgur.com/96Weu.png)               data = Table[RandomInteger[{1, 10}], {3}, {4}];          BarChart[MapThread[Labeled[#1, #2, Above] &, {data, {1, 2, 3}}],       ChartLayout -> "Stacked",       ChartStyle ->        Reverse@{Lighter@Blue, Blue, Darker@Blue, Darker@Darker@Blue},       ChartLabels -> {{"a", "b", "c"}, None},      Frame -> {False, True, False, False},      FrameLabel -> {"x axis", "y axis"},       BaseStyle -> {FontFamily -> "Helvetica", FontSize -> 14}]      Since only a y-axis component of Frame is rendered: `Frame -> {False, True, False, False}` the "x axis" label of `FrameLabel -> {"x axis", "y axis"}` is omitted - and that's consistent with documentation. Is it possible to display "x axis" at the location it would be if the bottom component of the Frame were there _and_ preserving the set `BaseStyle` values (eg `Font`, `FontSize`)? This can be done using `Inset` but positioning is ad-hoc and it does not preserve `BaseStyle` values. Wrapping `Labeled` around `Barchart` doesn't correctly center the text and moreover does not use the `BaseStyle` values, as the following screenshot shows. Here for comparison the bottom component of Frame is True - and note the disastrous clash of graphical elements. ![enter image description here](http://i.stack.imgur.com/jeAo7.png) Finally, using the bottom `Frame` component: `Frame -> {True, True, False, False}` but without ticks: `FrameTicks -> {None, Automatic, None, None}` results in an ugly double axis and overlap in labels: ![enter image description here](http://i.stack.imgur.com/28ntM.png) Any other options, eg using `LabelingFunction`?


title: Write a number as the product of its two largest divisors

text: For even `n >= 10 && n <= 98` I want to write `n` as the product of its two largest divisors (excluding `n` itself, i.e. `1 * 60 == 60` is not permitted). **EDIT** (to account for rasher's criticism) I have tried:               First@Reverse@Take[Transpose[{#, Reverse@#}], Length[#/2]/2] &[        Rest@Most@Divisors@#] & /@ {10, 12, 52, 60, 66, 70, 72, 98}      giving > {{2, 5}, {3, 4}, {4, 13}, {6, 10}, {6, 11}, {7, 10}, {8, 9}, {7, 14}} but this fails, f.e., on `16`, which should give `{4, 4}`


title: Formatting and inserting a parameter table into a plot

text: I'm fitting data, and I want to put the parameter table generated by `NoninearModelFit` into the plot. How can I do that in a reasonable way? I want to format the parameter table so that it only shows two decimal places and doesn't show the t-statistic and P-Values.


title: How to get the associated popup menu?

text: I have three`PopupMenu` and they work in such a way that second `PopupMenu` value depends on the value selected by the first `PopupMenu` and third `PopupMenu` value depends on the second `PopupMenu` value being selected. If first `PopupMenu` has two option a and b. Then second `PopupMenu` should have c,d,e if a is selected and f when b is selected. And if c is selected from second `PopupMenu` then third `PopupMenu` should have g,h and so on. These options are imported from Excel files. I wanted this to be dynamic; if someone makes any change to this file, then it should work accordingly. At the starting time, all three `PopupMenu` should show Popup1, Popup2, Popup3 as the name of `PopupMenu` and the selected value should be shown in its title name from White color and all `PopupMenu` background is black.


title: Computers running Wolfram lightweight grid manager won't fall asleep

text: I have a computing environment comprised of:   * 27" iMac with dual cores running Mac OS X 10.6.8 and   * 2 XServes each with 2 quad cores running Max OS X Server 10.6.8   * All networking by ethernet to a Time capsule. I now run Mathematica on the iMac and use the XServes for parallel processing. I have Wolfram lightweight grid manager running on the XServes. Since installing the grid manager the XServes won't fall asleep. Their energy use settings look like this: ![Energy Saver settings](http://i.stack.imgur.com/JiOIj.png) which should trigger them into sleep mode after 5 minutes of inactivity. The warm summer weather has made this a pressing issue. XServes run hot and power hungry. I don't need them running constantly and don't want to run air conditioning all the time to cool them. Also, I want to run some processing from a remote location while I escape NY's summer heat for a few days. Sleeping and waking the servers figure into my working vacation plan ;-) Does grid manager run some process which prevents the XServes falling asleep? If so, how can I start and stop the process?


title: Executing Maple Code Inside Mathematica

text: Is it possible to create a C++ program using MathLink that will invoke the Maple kernel and execute a very basic Maple command using OpenMaple? I'm envisioning the following:               Install["MapleLink"]      starts the external program MapleLink and installs the _Mathematica_ definition RunMaple.               ?RunMaple          RunMaple[expr] returns a string which is the output when Maple executes expression expr      A sample output:               RunMaple["seq(i, i=0..3);"]          "0, 1, 2, 3"      I'm also open to using J/Link.


title: How can I make a list animation of images that fade in and out?

text: I'm not sure how to get a "fade in" effect.


title: Transform Root objects into Trigonometric expressions

text: Consider the Root objects               roots = Table[Root[-1 + 27 #1^2 - 162 #1^4 + 243 #1^6 &, i],{i,1,6}]      These can be expressed in terms trigonometric functions as follows               trig =        {-2/3 Cos[Pi/18], -2/3 Cos[5 Pi/18], -2/3 Cos[7 Pi/18],          2/3 Cos[7 Pi/18], 2/3 Cos[5 Pi/18], 2/3 Cos[Pi/18]}      This can be checked Numerically, but also exactly using the following expression:               And @@        MapThread[         PossibleZeroQ[ToNumberField[#1 - #2], Method -> "ExactAlgebraics"] &,          {roots, trig}]      > True Is there a way to have Mathematica translate between these two things? I have not been able to make FullSimplify do it. Does anyone know of something like a RootToTrig function?


title: How to edit a HYPERLINK once created inside a notebook?

text: When a hyperlink is created in a notebook, there does not seem to be an easy way to actually edit the hyperlink (maybe to correct the URL). To make some text HYPERLINK, one selects the text using the mouse, then does a right-click and then selects `Make HyperLink ...`, then a popup menu comes up where one enters the actual URL. Then clicks ok and hyperlink is made. ![Mathematica graphics](http://i.stack.imgur.com/0aIEr.png) Now the text becomes a hyperlink. But how can one bring this menu back up in order to modify the link if needed? Right-clicking on the now hyperlink does not bring up the above menu used to create the hyperlink. Selecting the cell and typing `Ctrl+Shift+E` is not really practical, as the cell can be very large and contain many links. question is: How to bring up the original menu used to make the hyperlink in order to modify any specific link when needed?


title: Recursion on a moving window

text: I need to apply some computations to a moving window of $N$ items in a time series and I am struggling with doing recursion and shifting the considered window. To illustrate, please consider the simple function below.               myFunction[state_] := Append[state[[2 ;;]], RandomInteger[10]]     initialState = {1, 2, 3};     RandomInteger[10];     state1 = myFunction[initialState]     state2 = myFunction[state1]      In reality I am doing some time series analysis. I am predicting the `t4` based on `t1`, `t2` and `t3`. Then I want to predict `t5` based on `t2`, `t3` and my predicted `t4` and so on. So after 3 iterations, I will be predicting based on my 3 first predictions


title: Finding a percolation path

text: I would like to examine percolation on a random lattice. To be exact, I wish to find the minimum length of a 'bond' needed such that the leftmost site can be connected to the rightmost site. Here is an example of the lattice:               randPts = Table[RandomReal[{-10, 10}, 2], {200}];      randPlot = ListPlot[randPts,                      PlotStyle -> {PointSize[0.0125]},                      PlotRange -> {{-10, 10}, {-10, 10}},                      AspectRatio -> 1,                      Frame -> True]      ![random lattice](http://i.stack.imgur.com/Q5vMj.png) I have tried for a while to get this but have not had success. The basic plan was:   1. Define a bond length $R$   2. Look at each site one at a time. If another site(s) is within $R$ of a site, they will be in the same cluster. Each site will be in a cluster of 1 or more (obviously the larger $R$ chosen, the larger each cluster size)   3. Take a site. Does it bond with other sites? If so then combine the two clusters together.    4. Repeat step 3 for all sites.   5. At the end ask if the leftmost cite and the rightmost sites are included in the conglomerate cluster. If so, percolation has occurred.   6. Decrease $R$ and start over again until a threshold is found. I think I am stuck somewhere in the step 3,4 area. Here is some of what I've tried: I have defined a module to find the distance between a site, `j`, and its nearest neighbor. The table, `t`, gives distance between `j` and all other sites:               minD[j_] :=        Module[{},         t = Table[{randPts[[i]],                    Sqrt[(randPts[[j, 1]] - randPts[[i, 1]])^2 + (randPts[[j, 2]] -                       randPts[[i, 2]])^2]},                   {i, 1, Length[randPts]}];              For[i = 1, i < Length[t] + 1, i++,            If[t[[i, 2]] == RankedMin[t[[All, 2]], 2],              coord[j] = t[[i, 1]] ]];         Return[{coord[j]}];       ];      This module takes the table of distances and picks out ones that are within the chosen bonding radius (1.5 here. the `y>0` condition to so to not count the same site):                 cluster[k_] :=          Module[{},           minD[k];           Return[             Table[Cases[t, {x_, y_} /; y < 1.5 && y > 0][[i]][[1]],                    {i, 1, Length[Cases[t, {x_, y_} /; y < 1.5 && y > 0]]}]];         ]      So `cluster[k]` gives the sites within the cluster that is centered at site `k`. Now combining these clusters is what I am having a problem with. My idea was to start with a site and its cluster; find out what clusters that cluster intersects with and continue. I was not able to implement this correctly. Another way to visualize or maybe solve the problem is in terms of increasing the site radius at each site until a percolation network is achieved:                randMovie =         Manipulate[         ListPlot[randPts,              PlotStyle -> {PointSize[x]},              PlotRange -> {{-10, 10}, {-10, 10}}, AspectRatio -> 1,              Frame -> True],          {x, 0.00, 0.12, 0.002}]      ![enter image description here](http://i.stack.imgur.com/gMV87.png)


title: Trying to solve a trig identity

text: Given $\sin 2x+\sin x=1$, find the value of $\cos 2x+\cos 4x$. I know $\cos 2x+\cos 4x \implies 1-2\sin^2x+1-2\sin^22x$, but didn't get the answer.


title: Precision differences

text: I run this sum and get the symbolic answer below :               Sum[ (1/(k^2 - k) - 1/k^2), {k, 2, Infinity}]      > $2 - \frac{\pi^2}{6}$ I look up the sequence on OEIS and find these digits:               RealDigits[ N[ 2 - Pi^2/6, 105]]      > {{ **3, 5, 5, 0, 6, 5, 9, 3, 3, 1, 5, 1, 7, 7, 3, 5, 6, 3, 5, 2, 7, 5, 8, 4, > 8, 3** , 3, 3, 5, 3, 9, 7, 4, 8, 1, 0, 7, 8, 1, 0, 5, 0, 0, 9, 8, 7, 9, 3, > 2, 0, 1, 5, 6, 2, 2, 6, 4, 4, 4, 1, 7, 7, 0, 6, 2, 9, 9, 9, 2, 5, 2, 9, 5, > 9, 6, 7, 9, 9, 1, 2, 6, 1, 6, 6, 3, 7, 1, 0, 9, 9, 3, 8, 0, 2, 4, 1, 2, 9, > 4, 6, 9, 5, 9, 9, 5}, 0} When I try to replicate those digits, I get some differences at the 27th digit.               RealDigits[ NSum[ (1/(k^2 - k) - 1/k^2), {k, 2, Infinity},     WorkingPrecision -> 105]]      > {{ **3, 5, 5, 0, 6, 5, 9, 3, 3, 1, 5, 1, 7, 7, 3, 5, 6, 3, 5, 2, 7, 5, 8, 4, > 8, 3** , 2, 1, 5, 3, 5, 8, 4, 4, 8, 1, 8, 6, 0, 5, 0, 6, 9, 8, 9, 7, 9, 3, > 3, 4, 8, 2, 1, 4, 0, 3, 2, 9, 8, 8, 0, 8, 5, 6, 2, 7, 0, 3, 0, 0, 8, 1, 8, > 8, 4, 1, 0, 2, 5, 2, 8, 6, 3, 7, 0, 7, 4, 1, 8, 9, 3, 1, 3, 7, 3, 4, 0, 4, > 0, 3, 0, 3, 2, 3, 5}, 0} So, which is correct ? The symbolic sum or the NSum? **Edit** I tried with a plus between the two sums, which returns `Zeta[2]` and I get the same variances starting at the $28$-th digit.


title: Difficulties in creating strict and robust equivalence between two symbols using the Notation package

text: I am investigating the use of the `Notation` package facilities to create strict the equivalence between pretty-printed symbols such as `OverBar[SuperStar[af]]` that formats as $\overline{af^*}$, and easy to type (but hard to read) symbols such as `afstarbar`. My issue is that I fail at making two such symbols strictly equivalent. **I would like that** , after typing `Notation[ParsedBoxWrapper[\[Beta]]\[DoubleLongLeftRightArrow]ParsedBoxWrapper[beta]]`, I get the following behavior:                In[] beta = 3      Out[] 3           In[] \[Beta]      Out[] 3           In[] \[Beta] = 0      Out[] 0           In[] beta          Out[] 0           In[] beta = 4      Out[] 4          In[] Information[beta]      Out[] \[Beta]           \[Beta] = 4      It is to be noted that with Mathematica 8.0.0.0, the Notation behaves differently on Windows and Linux and on Mac, as I figured out by starting this reddit discussion, but on all platforms, I could not manage to get assignments to one symbol propagate to the other symetrically. **The behavior that I get instead** of the above is:                In[] beta = 3      Out[] 3           In[] \[Beta]      Out[] 3           In[] \[Beta] = 0      Out[] 0           In[] beta          Out[] 3           In[] beta = 4     Out[] 4          In[] Information[beta]      Out[] \[Beta]           \[Beta] = 4      Is there a way to get the scrict and robust equivalence between symbols instead of the assymetrical behavior shown above?


title: Continuous evaluation of complex calculations

text: When having a first look at some system, it's often very useful to just play with the parameters and see how it develops. Therefore, I would like to let a certain evaluation run "until I cancel it". Take a nonlinear differential equation for example, say the Duffing oscillator, $\ddot{x} + \delta \dot{x} + \alpha x + \beta x^3 = \gamma \cos (\omega t)$, and try to investigate when the solutions start to become different when you alter the initial condition of the one evaluation by 1/1000. ![Duffing oscillator with a very small bump at t=20.](http://i.stack.imgur.com/OIW5Y.png) I'd like to `NDSolve` this system, with the ability to look at the current state while doing so. Note that this was only an example, the answer does not necessarily have to be constrained to `NDSolve`. Another example would be a cellular automaton that one observes until a certain pattern emerges in some region.


title: Manipulate evaluation sequence

text: `Manipulate` doesn't always evaluate in the order I expect it to. What is the evaluation sequence for `Manipulate` and other functions involved with the front end? I have seen the evaluation sequence for kernel only functions, but that was for a reference for Mathematica 3, and doesn't deal with the front end.


title: The space in default output of `ExportString` to Latex

text: # Are there any reasons for converting subscriptbox to Tex with space? * * *               ExportString[Subscript[\[Alpha], 1], "TeX"]          (*         %% AMS-LaTeX Created by Wolfram Mathematica 9.0 : www.wolfram.com\documentclass{article}\u     sepackage{amsmath, amssymb, graphics, setspace}\newcommand{\mathsym}[1]{{}}\newcommand{\un     icode}[1]{{}}\newcounter{mathematicapage}\begin{document}\[\alpha _1\]\end{document}     *)      Of course, I can remove the space in via the option "BoxRules", and `$\alpha _1$` can also rendered well in SE. But many people would edit my `$\alpha _1$` into `$\alpha_1$`, do you know whether there are any reasons for the default space generated by `ExportString`? The same to other boxes.


title: Flatten command: matrix as second argument

text: One thing I could never wrap my head around is how `Flatten` works when provided with a matrix as the second argument, and the _Mathematica_ help isn't particularly good on this one. Taken from the `Flatten` _Mathematica_ documentation:               Flatten[list, {{s11, s12, ...}, {s21, s22, ...}, ...}]      > Flattens `list` by combining all levels $s_{ij}$ to make each level $i$ in > the result. Could someone elaborate on what this actually means/does?


title: Make fraction with selection in denominator

text: Using `ctrl``/` you can make a fraction. If you have selected something it will appear in the numerator. Does there exist a shortcut to make the selected text appear in the denominator instead? If not, is it possible to create a shortcut that does this?


title: Given two samples, how does LocationTest select its AutomaticTest?

text: How does `LocationTest` select its `"AutomaticTest"` when testing two samples? **Background** : A previous post poses a similar question but in that case the choice concerned a single sample. The question involving two samples is harder since the idiom apparently in use - using the significant level set for the overarching test to set significance levels for `"Normality"`, `"EqualVariances"` and `"Symmetry"` diagnostic tests - has more complex interactions and raises issues about the entire idiom (including for the family of hypothesis-testing functions - `VarianceTest`, `DistributionFitTest`, `IndependentTest` etc) while also suggesting certain usage guidelines. Note that the following applies two user-defined functions (both defined in the related post); `ShowSignificanceLevelThresholds` \- for showing those significant levels at which `LocationTest` changes its choice of `"AutomaticTest"` and the `"HighlightAutomaticTest"` option - for highlighting (in a the gray background) the selected `"AutomaticTest"`. First define two samples:               SampleA =        {17.375, 20.375, 20, 20, 18.375, 18.625, 18.625,         15.25, 16.5, 18, 16.25, 18, 12.75, 15.5, 18};          SampleB =        {23.5, 12, 21, 22, 19.125, 21.5, 22.125, 20.375,         18.25,21.625, 23.25, 21, 22.125, 23, 12};      Now find the significance level thresholds.               LocationTest[{SampleA, SampleB}, Automatic, {"TestDataTable", All},        "HighlightAutomaticTest" -> True] // ShowSignificanceLevelThresholds      ![enter image description here](http://i.stack.imgur.com/iz3yS.jpg) Similar to the single sample case, Normality of now both samples affects the test chosen and hints at the generation of the first threshold               Row[{       DistributionFitTest[SampleA, Automatic,          {"PValueTable", All},"HighlightAutomaticTest" -> True],       Spacer @ 50,       DistributionFitTest[SampleB, Automatic,         {"PValueTable", All},"HighlightAutomaticTest" -> True]     }]      ![enter image description here](http://i.stack.imgur.com/EfgLB.jpg) Perhaps, the normality of the second sample is being assumed for significance levels less than 0.016 as when the overarching significance level is passed down to the `PearsonChiSquare` normality test it is halved to correspond to the extra evidence required (the number of tests being effectively doubled due to the two samples)? As for the other transition point, 0.826, `"EqualVariance"` and `"Symmetry"` are likely to be involved. As far as `"EqualVariance"` is concerned, the same threshold analysis can be performed.               VarianceTest[{SampleA, SampleB}, Automatic, {"TestDataTable", All},        "HighlightAutomaticTest" -> True] // ShowSignificanceLevelThresholds      ![enter image description here](http://i.stack.imgur.com/UpDFb.jpg) Now disentangling becomes trickier - bear in mind that the `"EqualVariance"` test presumably used by `LocationTest` presumably uses the passed-down significance level to presumably both select the test assessing an assumption and to determine its outcome - by comparing this (adjusted) significance level with one of the tabled p-values above. Furthermore, `VarianceTest` presumably applies its own tests of normality so how this interacts with `LocationTest`'s own normality test and selected significant values rapidly renders rabbit- warren-like - and this is even before factoring in (undocumented?) tests of `"Symmetry"`. Furthermore, in the last transition significance value, 0.016, doesn't change `Conover` as the chosen `"AutomaticTest"` but rather those "appropriate" or "applicable" (plausible?) tests - but under exactly what criteria does a test become "appropriate" or "applicable"? According to the documentation `"LocationTest"` chooses all tests that apply ..." suggesting `"AutomaticTest"` as the most powerful, applicable test and implying the nub of the post's question a more general, "How does `LocationTest` select its _applicable_ tests?" In such a scenario the significance level further affects `"AutomaticTest"`'s selection since it impacts on relative powers between applicable tests (particularly for tests with large degrees of freedom and low significance levels such as, for example, with genome-wide association studies) further adding to the tangle. Apart from a lack of transparancy (surely impacting `LocationTest`'s prospects for use in published research?) there is something epistemologically suspect about this significance level inheritance that goes against the grain of NHST's logic. The point of a significance level is that it is sets a standard of evidence to be met in order to make a decision/accept an effect. The point of a p-value is that it constitutes this evidence - a measure (probability) of the "extremeness" of a given experimental outcome. They are separate. This is the basis of their subsequent comparison: If the outcome is "sufficiently extreme" this apriori-decided standard of evidence is reached. The notion that a different significance level can change an outcome's p-value subverts this relationship and completely alters the methodology's logic while setting up convoluted dependencies inimical to repeatability, intuitive understanding and natural invocation - all fundamental tenets of scientific practice. Ultimately however, this is not a function of Wolfram Language's design per se nor does it superficially follow from the specific decision to link the significance level of diagnostic tests` significance levels; it is instead, an inevitable consequence of the decision to adopt formal, diagnostic tests for assessing such assumptions (or, as some have argued, the inherent incoherence of the NHST paradigm itself). This changes the definition (and perception) of Type 1 and Type 2 errors including for example when a t-test is selected: ![enter image description here](http://i.stack.imgur.com/KSwca.jpg) This approach has long been regarded as highly problematic as far back as 19441 and with plenty of empirical evidence emerging since2-5 and yet ... for example, > Preliminary tests of equality of variances used before a test of location > are no longer widely recommended by statisticians, although they persist in > some textbooks and software packages.3 In particular, it is used in SPSS, SAS and Statistica although seemingly, studiously eschewed in R. The Wolfram Langugage apparently adopts this strategy of the former group and despite the above inherent complications and conventional criticism just outlined, the concerns can perhaps be ameliorated (albeit IMO not in "natural usage" of the current implementation) while retaining certain advantages. More specifically, balancing Type I/II errors in many ways represents a theoretician's mirage resting as it does on distributional assumptions requiring judgement in the real world. The problems flowing from replacing this judgement with automatic computation in diagnostic tests are well made by numerous researchers but what they also consistently fail to do is demonstrate the superiority of the alternative (or any hybrid thereof): > In practice we conclude that graphical diagnostics are better than a formal > pretest.2 How so? That the shortcomings of a formal pretest can be analyzed, quantified and demonstrated fails to imply bettter outcomes from a vaguely defined and never-measured alternative. Hence, `LocationTest` has scope for improvement and attempting to tap into its test-choosing machinations is, I'd argue, far from idle spelunking; it's directly related to reproducibility concerns plagueing NHST as a scientific methodology virtually since its inception. In its current incarnatation, `LocationTest` is already useful in terms of suggesting relevant and powerful tests and for providing overviews but IMO caveats are needed for its routine usage: 1) Caution is needed in using its defaults as currently implemented - instead it may currently be more prudent to manually set assumptions via `"VerifyTestAssumptions"` option (surely a more natural, and in the light of the above, emphasised distinction would include a dedicated `"SetTestAssumptions`" option?) 2) If manually setting assumptions, confirm the logic dovetails with the automatic test chosen as described in the literature. Improvements would therefore see the significant values of diagnostic tests demonstrably preserving both meaningful diagnostics and overarching Type 1 and Type 2 errors (at least to a point where feasible and in particular in a more refined way than `" ... using \[Alpha]/k where k is the number of datasets being tested."` or alternatively when not feasible having an option to set these levels separately) while having the logic used to select automatic and applicable tests made much more transparent. These changes would not only satisfy Frequentists in this NHST implementation but also lay the groundwork for a casting/translation more amenable to Baysians (in a way beyond this post's scope). This would require an extension of the language - in particular of the input types and generated `"HypothesisTestData"` object as part of resolving multiple design tensions: human judgment vs machine determinations; smallest possible functional unit vs increasing functional scope; command-line vs object-like input & output etc all of which, albeit in a different guise, similarly (and perhaps even more pervasively) arise in more general data science invocations ... but this post digresses. ![enter image description here](http://i.stack.imgur.com/GSTqC.jpg)


title: Is there a PrimeQ whose accuracy guarantee you can adjust?

text: Say I have a list of a million integers each with a million digits, and I want a crude sieve to see which have a chance at being prime. Mathematica has a PrimeQ function, which appears to be slow because it performs a large number of trials of Miller-Rabin's primality test and the Lucas primality test before giving a Yes/No answer. Now I could try looking at small factors first, but say this only removes a small fraction of my list. Is there a way to turn down the certainty of PrimeQ, or are there other, faster, tuneably-cruder ways to test for primality within _Mathematica_?


title: Is there a way to use pause in Manipulate?

text: Is there a way to do any similar to               Do[Print["Iteration...", j]; Pause[1], {j, 1, 6}]      with `Manipulate`? (to show the evolution of each iteration slowly) What I have viewed is all with `Table`, and all the data is showed without no pause. Using `Pause[1]` or wating for `"click a button or to press any key"`. I was trying               Manipulate[Do[Print["Iteration...", j];   Pause[1], {j, 1, 6}],                {{k, 5}, {2, 3, 4, 5, 6, 7, 8}}]      or similar things with `Row`, `Column`, `Style`,... but... no success!


title: Cluster integration: Problem connecting to Sun Grid Engine

text: I'm trying to launch some kernels in a cluster engine running _Sun Grid Engine_ using _Cluster integration_. But I'm getting the error "Cannot find components required for SGE".               Needs["ClusterIntegration`"]     kernels = LaunchKernels[SGE["server", 16]]      > SGE::load: Cannot find components required for SGE. >> I doubt this is an error in the cluster side, as I get the same error regardless if I point to the correct server host name or not, so I think it fails locally (Mathematica 9.0.1.0) Also the documented option "Timeout" doesn't seems to exist, and the option "NetworkInterface" does not explain how to specify the interface..               Options[SGE]      > {"EnginePath" -> "/usr/local/sge/sge_root", "KernelOptions" -> "-subkernel > -mathlink -LinkMode Connect -LinkProtocol TCPIP \ -LinkName `linkname`", > "KernelProgram" -> "/usr/local/Wolfram/Mathematica/7.0/Executables/math", > "NativeSpecification" -> "", "NetworkInterface" -> "", "ToQueue" -> False} Any help would be appreciated.


title: Dataset with no members

text: I am trying to plan a framework for relational algebra using the Dataset capability of Mathematica 10. In the work of Date and Darwen, there are two concepts known as TABLE_DEE and TABLE_DUM. TABLE_DEE is a relation with a (column) header but no rows, whereas TABLE_DUM is simply: Dataset[{}] How might I create a TABLE_DEE with Dataset--a table with headers, but no data? I feel this would allow a framework for performing orthodox relational database operations.


title: Badly conditioned matrix (General::luc)

text: With some matrices I am receiving the following message > >     Inverse::luc Result for Inverse of badly conditioned matrix (M) may > contain significant >     numerical errors. >   How can I tell to _Mathematica_ to isolate (or detect) that result (or badly conditioned matrix)? For instance, using the `If` statement, which _condition_ should I put into the argument of `If` statement when my matrix is badly conditioned? P.S. Some advice to tackle with these kind of matrices would be good.


title: Data structures sought for storing particular list information

text: I have a set of lists. These lists contain two dimensional coordinates of natural numbers. So a list can be                list1 = {{1, 1}, {1, 2}, {3, 4}}       list2 = {{3, 6}, {5, 5}}.        In each step of the calculation a list can disappear, can grow, can diminish, new lists can appear and so on. I want for some points, elements of the lists, say for example {3, 3} to do bookkeeping to see in which list it is contained in every step of the calculation. It can be contained in one and only one list or in no list at all. So I want to do bookkeeping for {3, 3} in the sense that I want to know exactly at every step in which list it is contained. For example               bookkeeping[ {3, 3}] = {list2, list5, list3, none}       which says that at the first step {3, 3} is in list2, at the second step {3, 3} is in list5, at the third step {3, 3} is in list3 an at the last step it is in none of the lists. I have not the faintest idea how to do it. Should I define a bookkeeping[] function with downvalues? Or what is an elegant way to deal with it? What is the most elegant data structure I can use for such kind of bookkeeping?


title: Resolving Error: Mathematica evaluation order on Lists

text: I have a table that is 27 x 27, each entry corresponds to an element from the periodic table. I use the replacement rules in element list to allow me to convert a list of elements into a list of coordinates, so that I can access values from the table. Here test is a list of elements whose values I want to access. The function getBigSeg returns {0,0} if the core == shell, and otherwise returns the value from the table.               bigSegTable = Table[i + j, {i, 27}, {j, 27}];     getBigSeg[core_, shell_] :=       If[core == shell, {0, 0}, {bigSegTable[[core, shell ]] ,         bigSegTable[[core, shell]]}]         elementList = {"Sc" -> 1, "Ti" -> 2, "V" -> 3, "Cr" -> 4, "Mn" -> 5,         "Fe" -> 6, "Co" -> 7, "Ni" -> 8, "Cu" -> 9, "Zn" -> 10, "Y" -> 11,         "Zr" -> 12, "Nb" -> 13, "Mo" -> 14, "Tc" -> 15, "Ru" -> 16,         "Rh" -> 17, "Pd" -> 18, "Ag" -> 19, "Hf" -> 20, "Ta" -> 21,         "W" -> 22, "Re" -> 23, "Os" -> 24, "Ir" -> 25, "Pt" -> 26,         "Au" -> 27};          test = {{"Ti", "Ag"}, {"Zr", "Ag"}, {"Nb", "Ag"}, {"Tc", "Ag"}, {"Ru",          "Ag"}, {"Ag", "Ag"}, {"Hf", "Ag"}, {"Ta", "Ag"}, {"Re",          "Ag"}, {"Os", "Ag"}, {"Ir", "Ag"}};      I want to know why if I do: getBigSeg[#1, #2] & @@@ test /. elementList I get an error. But I do not get an error if I do                   getBigSeg[#1, #2] & @@@ {{2, 19}, {12, 19}, {13, 19}, {15, 19}, {16,         19}, {19, 19}, {20, 19}, {21, 19}, {23, 19}, {24, 19}, {25, 19}}      This is strange to me because               test /. elementList      gives               {{2, 19}, {12, 19}, {13, 19}, {15, 19}, {16,         19}, {19, 19}, {20, 19}, {21, 19}, {23, 19}, {24, 19}, {25, 19}}      So I do not understand why I am getting an error, and what is different between the two expressions.


title: Make the y-axis of a plot be in terms of an arbitrary parameter instead of a number?

text: Sorry if the title is wordy. Basically what I am asking would probably be easier if I just use an example. Say I wanted to plot f(x) = Asin(x) and have the graph come up with the sine function, and then the tics on the y axis be like half integer multiples of A. What I have been doing for my homework assignments is just plotting f(x)=sin(x) and then turning off the ticks and manually adding my ticks. It would be really cool if mathematica could do this for me.


title: Equivalence under common permutations

text: I have lists which consists of sublists of equal length. The outer list is regarded as a multiset (that is, permutations of the sublists don't matter, but repetitions do), but the order in the sublists _does_ matter, except that if the _same_ permutation is applied to each of the sublists, it also doesn't matter. Now my problem is that I want to write a function that tests whether two lists are equivalent under those rules. An obvious solution would of course be to generate all "inner" permutations for one set and seek the other one in there (the outer permutations can then, of course, be gotten rid of through sorting), but I feel there should be a simpler (and more efficient) solution. But I don't seem to be able to figure it out. To make some concrete examples, I'd like to get e.g. the following results:               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{2,1,1,1},{2,1,2,1},{2,2,2,2}}] == True      because you get the second from the first by exchanging the first and the last element in each sublist. On the other hand,               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{2,1,1,1},{1,1,2,2},{2,2,2,2}}] == False      because there's no _common_ permutation which transforms the first to the second. Of course I also want               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{1,1,2,2},{2,2,2,2},{1,1,1,2}}] == True      because here only the sublists are permuted in the outer list. And also,               equiv[{{1,1,1,2},{1,1,2,2},{2,2,2,2}},           {{2,1,2,1},{2,1,1,1},{2,2,2,2}}] == True      because this just combines a permutation of the sublists with a _common_ permutation of the elements in each list. So what is the best way to write this `equiv` function above?


title: Can I read Chinese characters with ReadList correctly?

text: Just try this example:               Export["a.txt", "这乱码问题该怎么解决呢\n***\n怎么解决嘛"]     ReadList["a.txt", Record]      > >     {"è¿ä¹\[PlusMinus]ç é®é¢è¯¥æä¹è§£å\.b3å¢", "***", "æä¹è§£å\.b3å"} >   I know `Import` can handle it correctly:               StringSplit@Import["a.txt"]      > >     {"这乱码问题该怎么解决呢", "***", "怎么解决嘛"} >   But `ReadList` is generally much faster, right? Well, after scanning this post and the links inside it I noticed that _Mathematica_ may be just not good at this, but still want to make sure if it's not possible.


title: Generate array of every $n^{th}$ integer between two bounds

text: I want to generate the series `{1930, 1934, 1938, ..., 2014}` with _Mathematica_. I found that I can use `Sum[2014-m*4, {m, 20}]` to get the sum of these numbers, so I tried `Array[2014-m*4, {m, 20}]`, but no luck. How do I do this?


title: How to output Mathematica Lists as a Table to a file?

text: Given the following List:                 lis =  { {-2.8336, -1.1088, -0.1232, 1.23493}, {-2.8336, -1.1088, 0.1232,            1.08433}, {-2.8336, -0.8624, -0.616,            1.04417}, {-2.8336, -0.8624, -0.3696,            1.10441}, {-2.8336, -0.8624, -0.1232, 1.17469}, {-2.8336, -0.8624,            0.1232, 1.09437}, {-2.8336, -0.8624, 0.3696,            1.43574}, {-2.8336, -0.8624, 0.616,            1.07429}, {-2.8336, -0.616, -0.8624,            1.26506}, {-2.8336, -0.616, -0.616, 1.43574} }      One can convert it to a table as follows: `lis//TableForm` But that just works for displaying it in _Mathematica_. How can one easily save that list to a text file so that it appears as a table?


title: Function definition and delayed assignment

text: I need to define the following function               MyWavelet[n_]["PrimalLowpass", prec_ : MachinePrecision] :=         Table[(-1)^(j - 1) h[[2*n - j]], {j, 0, 2*n - 1}]      which depends on the following code               num = T;     precis = 32;     p[n_, x_] := Sum[ Binomial[n-1+j,j]*x^j, {j,0,n-1}]     pol[n_, z_] := Expand[z^(n-1) * p[n, (1 - (z + 1/z)/2)/2]]     roo[n_] := NSolve[pol[n, x] ==0, x, precis]     absgreater[x1_, x2_] := Abs[x1] < Abs[x2]     sroo[n_] := Sort[roo[n], absgreater]     insidehalf[n_] := Take[sroo[n], n-1]          rootlist = x /. insidehalf[num];     prod = Expand[Product[(w - rootlist[[j]]), {j, 1, num - 1}]];     normalizer = prod 2^(num - 1/2) /. w -> 1;     polyn = Expand[(1 + w)^num * prod/normalizer];     h = Reverse[N[CoefficientList[polyn, w], precis]];      where T is an integer. My problem is I need to replace `num` with the value of `n` when calling the `MyWavelet` function and then dynamically evaluate, so I can get the `h` table values assigned to the specific `MyWavelet[n]`. I tried couple o'times using `With, but with no success.


title: Variable substitution in sum's index

text: How cam I simplify               Sum[UnitStep[-1 + n]/Sqrt[n!], {n, 0, ∞}]      to $$\sum _{n=1}^{\infty } \frac{1}{\sqrt{n!}}$$ and then to $$\sum _{n=0}^{\infty } \frac{1}{\sqrt{(n+1)!}}$$ I tried `Simplify` and `FullSimplify`, but neither of them worked.


title: Capture an image by non-default device

text: Guys! I need capture video from certain webcam which isn't `$DefaultImagingDevice`. As I know there is one legal way: `ImageCapture["Device"->$ImagingDevices[[x]]]` where x is number of needed device. However ImageCapture doesn't allow to make a grid on the image like this:               grid = Graphics[{Gray,         Table[Line[{{(i - 1)*16, 0}, {(i - 1)*16, 240}}], {i, 1, 21}],         Table[Line[{{0, (i - 1)*16}, {320, (i - 1)*16}}], {i, 1, 16}]         }];          Dynamic[Show[       CurrentImage[],       grid,       ImageSize -> 800]]      ![http://s18.postimg.org/hek0gtp2h/Camera_small.jpg](http://i.stack.imgur.com/XDXDQ.jpg) May be somebody knows how to apply CurrentImage for certain non-default imaging device? Or how to take just image without any interface elements using ImageCapture?


title: Export command in Mathematica trial version

text: _Mathematica_ trial version does not support `Export[]` command. Is there a command equivalent to `Export[]` in order to export, say, a matrix?


title: How do I keep my Animate running at high resolution?

text: I'm building an Animate where I have a 3D plot with some of its parameters changing: `Animate[SphericalPlot3D[Sin[(3/z)*x], x, y, PlotStyle -> Opacity[0.7]], {z, 1, 5}]` Whilst it is running through the changes though, the entire plot goes very low-res. How can I ensure that the resolution stays high throughout the animation, and not just when it stops running?


title: Return a local variable from a Module containing a Manipulate

text: I would like to create a set of custom controls that call Manipulate[] and return the value(s) set during the Manipulate session. I can easily make a version that uses something like:               MyControl[] := Manipulate[...{a, -10,10}, {b,-1,1}]      This works but variables a, b and any additional variables set by Manipulate are global. Is it possible to do something like this (Return a Dataset with the selected values for a and b when a "Set" button is clicked and Return Null if "Forget" is clicked):               MyControl[]:= Module[ {a, b},                           Manipulate[...{a, -10, 10}, {b, -1, 1},                                      Button["Set", Return[Dataset[Association @ {aValue->a, bValue->b}]]],     Button["Forget", Return[]]]]


title: JLink Get ALL output from a mathematica command

text: I have the following code (Java code using JLink).               String arguments = "-linkmode launch -linkname 'math -mathlink'";     KernelLink link = MathLinkFactory.createKernelLink(arguments);     String mathCommand = "applyState[processLRV,{{Q000847$JV$9198831378,Q000847$JV$9198831378.state},{{Null,Null},Null,\"<math><mn>16</mn><mi>p</mi><mo>+</mo><mn>25</mn><mi>p</mi><mo>=</mo><mn>1792</mn></math>\"}}]";     String output = link.evaluateToOutputForm(mathCommand, 0);     System.out.println(output);      If I run the command in **math** client I get the following output:               In[3]:= applyState[processLRV,{{Q000847$JV$9198831378,Q000847$JV$9198831378.state},{{Null,Null},Null,"<math><mn>16</mn><mi>p</mi><mo>+</mo><mn>25</mn><mi>p</mi><mo>=</mo><mn>1792</mn></math>"}}]                                                   General::aofil: HoldForm["Q000847$JV$9198831378.response"] already open as HoldForm["Q000847$JV$9198831378.response"].          OpenAppend::noopen: Cannot open HoldForm["Q000847$JV$9198831378.response"].          WriteString::strml: HoldForm[$Failed] is not a string, stream, or list of strings and streams.          General::stream: HoldForm[$Failed] is not a string, InputStream[ ], or OutputStream[ ].          OpenRead::noopen: Cannot open HoldForm["Q000847$JV$9198831378.state"].          General::stream: HoldForm[$Failed] is not a string, InputStream[ ], or OutputStream[ ].          General::stream: HoldForm[$Failed] is not a string, InputStream[ ], or OutputStream[ ].          General::stop: Further output of HoldForm[General::stream] will be suppressed during this calculation.          ToExpression::notstrbox: HoldForm[Read[$Failed]] is not a string or a box. ToExpression can only interpret strings or boxes as Mathematica input.         {{Q000847$JV$9198831378 . state, "reProcessLRV"}, Null, {{Null, Null}, Null, Null}, FullForm["unrecognized syntax Q000847[(16Users`p) + (25Users`p) == 1792]\n"], Null}          General::aofil: HoldForm["Q000847$JV$9198831378.response"] already open as HoldForm["Q000847$JV$9198831378.response"].          OpenAppend::noopen: Cannot open HoldForm["Q000847$JV$9198831378.response"].          WriteString::strml: HoldForm[$Failed] is not a string, stream, or list of strings and streams.          Out[3]= {{Q000847$JV$9198831378 . state, reProcessLRV}, Null, {{Null, Null}, Null, Null}, "unrecognized syntax Q000847[(16Users`p) + (25Users`p) == 1792]\n", Null}      But from my app I just get Out[3] text:               {{Q000847$JV$9198831378 . state, reProcessLRV}, Null, {{Null, Null}, Null, Null}, "unrecognized syntax Q000847[(16Users`p) + (25Users`p) == 1792]\n", Null}      How can I get the text between In[3] and Out[3] using Java code? Hope it makes sense! :)


title: Selecting items in a list based on multiple tests

text: I have an array of strings that look like this:               list = {{valueA1, valueB1, valueC1, valueD1, valueE1, valueF1, valueG1, valueH1}, {valueA2, valueB2, valueC2, valueD2, valueE2, valueF2, valueG2, valueH2}, {valueA3, valueB3, valueC3, valueD3, valueE3, valueF3, valueG3, valueH3}, ...}      I'd like to prune the list so that I generate some `selectedItemsList` which contains only the entries where some select set of (`valueA...` through `valueH...`) pass some test. For example, `valueB...` and `valueH...` could be real numbered values, and I'd like to only put entries in list when its the case that, for some entry `k` we have `1 < valueBk < 3` && `-10 < valueHk... < 5` and so forth. If `list` has millions of entries, so maybe we don't want to go through the list in multiple passes, what is the most efficient way to perform this selection?


title: What can I do to eliminate the error FindFit::nrjnum:?

text: I am testing the "Power Law with finite-time singularity" hypothesis for world population growth for a project. The data I'm using (same behaviour should also be exhibited by the stock market, thats why I am trying this with financial data):               raw = FinancialData["GE", All];     fraw = Flatten[raw];     data = Table[fraw[[4*i]], {i, 1, Length[raw]}]; (*extracting just the prices*)      I was trying the following regression model:               model = A + B*(c - x)^z;      And then the following curve fit method:               FindFit[data, {model}, {A, B, c, z}, x]      But I always get the result: > Power::indet: "Indeterminate expression 0.^0. encountered." FindFit::nrjnum: > "The Jacobian is not a matrix of real numbers at {A, B, c, z} = {1., 1., 1., > 1.}. " > > {A -> 1., B -> 1., c -> 1., z -> 1.} If I do a normal Power law regression, `FindFit` works perfectly, but the title of the project being "Power Law with finite-time singularity" I need to have the singularity `c` in the model and the main aim is to find when this singularity occurs. Is there a way to use `FindFit` to get the correct answer? Or should I be using some other function? I have seen other articles on this site concerning issues with `FindFit`, but none of them has helped me resolve this problem. Remark: I have already tried the version belisarius has stated below, but the problem with that is that it gives me a `z > 0`. What I need is `z < 0` for `x = c` to be a singularity. So I also tried the following models: `A + B*Abs[c - x]^(-z)` and `A + B*(c - x)^(-z)` with `-z` instead of `z` but those just gave me like 15 other warnings.


title: How to make a smooth revolution surface plot

text: I'm trying to plot a 3d revolution plot from a set of 2d points. These data points form a 2d curve, then we rotate that curve around y axis and get a 3d surface. @J. M. has a well explained and very helpful post at here which deals exactly the problem I have. However, I tried to use the method, and get a 3d surface that is very rough and not smooth. Here is the 2d data points:               points=Uncompress["1:[encoded data, 13204 characters]"];      and this is how it looks like               Graphics[Line[points], Frame -> True]      ![enter image description here](http://i.stack.imgur.com/nscUw.png) and then I use J. M.'s method(code copied and modified from here) (it will take about 10 seconds to run)               parametrizeCurve[pts_List, a : (_?NumericQ) : 1/2] :=       FoldList[Plus, 0, Normalize[(Norm /@ Differences[pts])^a, Total]] /;        MatrixQ[pts, NumericQ]          tvals = parametrizeCurve[points];          m = 3;     knots = Join[ConstantArray[0, m + 1], MovingAverage[ArrayPad[tvals, -1], m], ConstantArray[1, m + 1]];     bas = Table[BSplineBasis[{m, knots}, j - 1, tvals[[i]]], {i, Length[points]}, {j, Length[points]}];     ctrlpts = LinearSolve[bas, points];          circPoints = {{1, 0}, {1, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {1, -1}, {1,0}};     circKnots = {0, 0, 0, 1/4, 1/2, 1/2, 3/4, 1, 1, 1};     circWts = {1, 1/2, 1/2, 1, 1/2, 1/2, 1};          wgpts = Map[Function[pt, Append[#1 pt, #2]], circPoints] & @@@ ctrlpts;     wgwts = ConstantArray[circWts, Length[ctrlpts]];      and then generate the 3d surface               Graphics3D[{Directive[EdgeForm[]],        BSplineSurface[wgpts, SplineClosed -> {False, True},         SplineDegree -> {3, 2}, SplineKnots -> {knots, circKnots},         SplineWeights -> wgwts]}, Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/Ds37G.png) We can see that the surface is not smooth. It looks like the surface is composed by flat rings. So how can we make the surface smooth? Edit: I think this unsmoothness may come from my data rather than the rotation process, so I tried to smooth my data using something like               pointsSmooth=ExponentialMovingAverage[points, 1/20];      then I get the a smoother surface, but `ExponentialMovingAverage` seems to have removed the end points and there is a hole on the surface, which I don't want. ![enter image description here](http://i.stack.imgur.com/oyGlp.png) Also smoothing using a smooth constant like 1/20 largely modified the original data:               Graphics[{Red, Line[ExponentialMovingAverage[points, 1/20]], Blue,        Line[points]}, Frame -> True, AspectRatio -> 1]      ![enter image description here](http://i.stack.imgur.com/kyf6Z.png) So is it possible to smooth the data while keep the general shape so that it will give a better smooth surface? Or there are other ways to contract a smooth surface from the data?


title: How can I "ORDER BY" using SQLSelect?

text: A pretty straightforward problem, you would think, but I cannot seem to find the answer in the documentation for SQLSelect. The query I want to run is the following:               SELECT id, measurement, timestamp FROM myTable WHERE id IN (1, 2) ORDER BY timestamp      The _Mathematica_ query I have so far is:               SQLSelect[dbConn,         "myTable",         {"id", "measurement", "timeStamp"},         SQLMemberQ[{1, 2}, SQLColumn["id"]]     ]      But I cannot seem to find an option to insert the `ORDER BY` requirement.


title: How to differentiate between formatted and unformatted strings?

text: StringQ returns True both for unformatted and internally formatted strings. To get True only for unformatted ones I have thought up the following function stringQ. Please, can you point out pitfalls, if any ? Thanks!               stringQ[str_] := Module[{ret, subStr},         subStr = "\!\(\*\nStyleBox[\"";         ret = Quiet[                 If[                 StringQ[str] && StringFreeQ[str, subStr]                 ,True, False, False                 ]             ];         Return[ret];     ];


title: Simplify DSolve solutions (all roots are known)

text: I have problem how to present the solution of the system of two differential equations in the form as in the case of one differential equation if I know the nature of roots. For example                DSolve[a y1''''[x] + b1 y1''[x] + k0 y1[x] == 0 ,y1[x], x]      gives the known and simple solution for the supposed                y1[x_] = A E^(s x);      with known roots                s11 = λ + I ω;      s12 = λ - I ω;           s13 = -λ + I ω;      s14 = -λ - I ω;      in this form generally (*)               y1[x] = E^(λ x) (C1 Cos[ω x] + C2 Sin[ω x]) +      E^(-λ x) (C3 Cos[ω x] + C4 Sin[ω x])      I want to simplify the solution in the above case for the system of two differential equations                DSolve[{a y1''''[x] + b1 y1''[x] + k0*(y1[x] - y2[x]) == 0,       a y2''''[x] + b2 y2''[x] + k0*(y2[x] - y1[x]) == 0}, {y1[x], y2[x]},      x]      supposing                y1[x_] = A E^(s x);      y2[x_] = B E^(s x);      Solution is long output with 8 unknown constants. Can I simplify the presentation of the solution as in example case (*) if I know that all roots are in the following form                s1 = 0;      s2 = 0;           s3 = I ω1;      s4 = -I ω1;           s5 = λ + I ω2;      s6 = λ - I ω2;           s7 = -λ + I ω2;      s8 = -λ - I ω2;


title: How to import a large (~50Mb) json file in mathematica

text: I am trying to import a 46Mb json file into mathematica (which by the way I exported using mathematica) but its failing with the following messages:               Java::pexcptn: A Java exception occurred after the result was returned to Mathematica: java.lang.OutOfMemoryError: Java heap space         at java.util.Arrays.copyOfRange(Arrays.java:3209)         at java.lang.String.<init>(String.java:216)         at java.lang.StringBuffer.toString(StringBuffer.java:585)         at org.json.JSONTokener.nextString(JSONTokener.java:250)         at org.json.JSONTokener.nextValue(JSONTokener.java:316)         at org.json.JSONObject.<init>(JSONObject.java:190)         at org.json.JSONTokener.nextValue(JSONTokener.java:319)         at org.json.JSONObject.<init>(JSONObject.java:205)         at org.json.JSONTokener.nextValue(JSONTokener.java:319)         at org.json.JSONArray.<init>(JSONArray.java:120)         at org.json.JSONTokener.nextValue(JSONTokener.java:322)         at org.json.JSONObject.<init>(JSONObject.java:205)         at org.json.JSONTokener.nextValue(JSONTokener.java:319)         at org.json.JSONArray.<init>(JSONArray.java:120)         at org.json.JSONTokener.nextValue(JSONTokener.java:322)         at System.Convert.JSONDump.jDecodeJSONString(JSONDump.java:79).      (full msg: http://i.imgur.com/RUx7ic9.png) How can I import the file? Is there another format I should use for large files in json? (I have tried .dat and other formats, but they seem to loose the json structure information) (or should I just not use json for large collections of data?)


title: Labeling points of intersection between plots

text: There are several answers where _Mathematica_ used mesh points to show graphically where curve intersections exist. For example: Marking points of intersection between two curves or Is there a better way to get the eight points of intersection? Is there a way to include the actual point values (maybe they are simply labeled as `a`, `b`, `c` ...) and then the actual value is displayed on the right of the graphic? Here is the specific example I am working.               Plot[{Cos[x],(1/2)^x},{x,-1,11},      PlotPoints->84,      MaxRecursion->9,      MeshFunctions->{Cos[#1]-(1/2)^#1&},      Mesh->{{0}},      MeshStyle->Directive[Red,PointSize[Large]]]


title: How can I generate this "domain coloring" plot?

text: I found this plot on Wikipedia: ![domain-colored plot of sine function](http://i.stack.imgur.com/GjMe4.jpg) > Domain coloring of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. > Brightness indicates absolute magnitude, saturation represents imaginary and > real magnitude. Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?


title: How to pick out terms in a linear equation with a positive coefficient?

text: Basically I have a really large output which looks like a long linear equation $AAA-BAA-CAA+DAA+...-ZZZ$ And I only am concerned about those terms that have a positive coefficient (i.e. a plus in front). The others I can ignore. How can I get mathematica to ignore those positive-coefficient terms, or at the very least order the list such that the negative coefficient terms are in the front (or back).


title: Can't Solve a system of differential equations, Solve takes too long

text: My question is probably not really interesting but I really need help on this because I won't have access to a more powerful computer. So my model contains 7 equations :               dM1dt = (1 - b1) gM M1 ((a11 p DC1/(h11 + p DC1)) + (a12 (1 - q) DC2/(h12 + (1 - q) DC2))) - dM M1;     dM2dt = (1 - b2) gM M2 ((a22 q DC2/(h22 + q DC2)) + (a21 (1 - p) DC1/(h21 + (1 - p) DC1))) - dM M2;     dZ1dt = b1 gZ M1 ((a11 p DC1/(h11 + p DC1)) + (a12 (1 - q) DC2/(h12 + (1 - q) DC2))) - dZ Z1;     dZ2dt = b2 gZ M2 ((a22 q DC2/(h22 + q DC2)) + (a21 (1 - p) DC1/(h21 + (1 - p) DC1))) - dZ Z2;     dDC1dt = 0.5 (ID + (1 - s) dM (M1 + M2) + dZ (Z1 + Z2)) + v1 SC Z1/(k1 + SC) - M1 (a11 p DC1/(h11 + p DC1)) - M2 (a21 (1 - p) DC1/(h21 + (1 - p) DC1));      dDC2dt = 0.5 (ID + (1 - s) dM (M1 + M2) + dZ (Z1 + Z2)) + v2 SC Z2/(k2 + SC) - M1 (a12 (1 - q) DC2/(h12 + (1 - q) DC2)) - M2 (a22 q DC2/(h22 + q DC2));      dSCdt = IS + s dM (M1 + M2) - v1 SC Z1/(k1 + SC) - v2 SC Z2/(k2 + SC);      And I just want Mathematica to give the equilibrium points of this system :               coex = Simplify[Solve[{dM1dt == 0, dM2dt == 0, dZ1dt == 0, dZ2dt == 0, dDC1dt == 0,dDC2dt == 0, dSCdt == 0}, {M1, M2, Z1, Z2, DC1, DC2, SC}]] // MatrixForm      It solved it almost instantaneously for a 4 equations system but it just keeps Running (I tried to leave it run for more than 1 hour) for my 7 equations system, so I can't get the results. Is there a way to simplify or divide the commands? Thanks a lot in advance.


title: Why the Block command does not forget the $ContextPath variable

text: I do not understand this behavior:               method[args_] :=         (* forget the context path *)         Block[{$ContextPath},                 (* should given nothing, right? *)              Print["cpath=", $ContextPath];                 ...      but when evaluated it gives the full context path (i.e. it does not forgets it). Why is that? This is against everything I (seem to) know about the `Block` function.


title: AbsoluteOptions prints error messages in V10

text: I am trying to use AbsoluteOptions in V10 but I am getting the Out with some errors as see in this picture: ![enter image description here](http://i.stack.imgur.com/K02jv.jpg) does anyone have same issue?


title: Can't find a fit for Erf

text: I have the following numbers               l={38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 37, 37, 37, 37, 37, 37,     37, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,     35, 34, 34, 34, 34, 34, 33, 33, 33, 33, 33, 32, 31, 29, 29, 29, 28,     28, 28, 28, 27, 26, 25, 23, 21, 21, 16, 15, 15, 15, 11, 10, 6, 5, 4,     4, 4, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0, 0}      which look like an error function. I'd like to automatically find a fit for these numbers. I tried two different approaches               Fit[l, {Erf[x], 1}, x]      and               FindFit[l, a Erf[b x - c] + d, {a, b, c, d}, x]      Both produce completely off results. As I have a lot of data lists, I'd very much appreciate to automatically find the fits for these data.


title: How to write series of Do[ ]'s with a single Table[ ]?

text: Edited to provide more information (sorry I don't know how to format matrices here) I would like to replace: m = 4;               mult[i_, j_] := mult[i, j] = (tstar[Abs[i - j]] + tstar[i + j - 2])/2     Do[pmult[j] = Sum[a[i - 1]*mult[i, j], {i, 1, m}], {j, 1, m}];      Do[pmult[j] = Expand[pmult[j]], {j, 1, m}];      Do[c[j] = {}, {j, 1, m}];      Do[Do[c[j] = Append[c[j], Coefficient[pmult[j], tstar[i], 1]], {i, 0,          m - 1}], {j, 1, m}];      q = Transpose[Table[c[i], {i, 1, m}]]      with a single `Table` function (I believe this is possible). I attempted               mult[i_, j_] := mult[i, j] = (tstar[Abs[i - j]] + tstar[i + j - 2])/2     pmult[j_] := pmult[j] = Sum[a[i - 1]*mult[i, j], {i, 1, m}];      q = Table[       Coefficient[Expand[pmult[j]], {j, 1, m}, tstar[i], 1], {j, 1, m}]      but I receive the error message               Coefficient::nonopt: Options expected (instead of 1) beyond position 3 in Coefficient[a(0) tstar(0)+a(1) tstar(1)+a(2) tstar(2)+a(3) tstar(3),1,tstar(i),1]. An option must be a rule or a list of rules. >>      The output should be               (a(0)   a(1)/2  a(2)/2  a(3)/2     a(1)    a(0)+a(2)/2 a(1)/2+a(3)/2   a(2)/2     a(2)    a(1)/2+a(3)/2   a(0)    a(1)/2     a(3)    a(2)/2  a(1)/2  a(0))      Can someone please shed some light on what I've done incorrectly? (i and j are indices) Thanks in advance!


title: ContourPlot or DensityPlot ColorFunction with x, y and z arguments

text: Is it possible to apply a color function to ContourPlot or DensityPlot that is function of x, y and z, and not simply of z? Example:               ContourPlot[Cos[x] + Cos[y], {x, 0, 4 Pi}, {y, 0, 4 Pi},       ColorFunction -> (If[#1 > 1/2, Red, White] &)]      but colored only for x > 2 Pi (obviously, there are alternative methods for this example, but typical cases are more complex)


title: Horizontal axis tick marks

text: I have a question about adjusting the number of horizontal tick marks on a 2D plot. Example: f[x_] := 4*Sin[4*x] Plot[{f[x]}, {x, -10, 10}, Ticks -> {Table[Pi n, {n, -5, 5}]}] Gives the following plot: ![enter image description here](http://i.stack.imgur.com/MTjQV.jpg) How would I go about adding more ticks so I could change the range (in terms of pi) to fractional values of pi? Say -pi/10 to pi/10 or...in increments of pi/2....or pi/4? The "Plot" command I am using is one I found from the _help_ because I couldn't figure out how to make the ticks in terms of pi. I'm still learning some of the basics, but I'm quite stuck on changing the # of ticks. Anyone have some ideas please? Thanks


title: Define PolyLog so that positive reals evaluate on upper edge of branch cut

text: Generalizing the previous question: Define Log so that negative reals evaluate on lower edge of branch For real positive values $x>1$, Mathematica's polylogarithm function `PolyLog[2,x]` yields a result whose imaginary part is negative (because it is defined to be evaluated just below the cut). for example:               In[1] := PolyLog[2, 1.6]     Out[1] = 2.41313 - 1.47656 I        In spirit of the previous question (linked above) what is the cleanest way to get Mathematica to evaluate the function just above the cut, so that I get a positive imaginary part, Desired output:               Out[1] = 2.41313 + 1.47656 I        **Edit** The `PolyLog` appears inside the definition of a larger function that I am using. I need to use this function for both analytic and numeric purposes. I should be able to evaluate it numerically, and also be able to differentiate it without giving a lot of non-analytic garbage associated with the deserved change. Is there anything I can do so that I get both properties?


title: Using Show to place a ParametricPlot on a LogLog scale

text: I wish to have a few plots on the same graph: ListLogLogPlot, LogLogPlot and a ParametricPlot drawing lines perpendicular to the x-axis. The problem is however that ParametricPlot doesn't seem to have the LogLog equivalent, as the other Plot functions do, and Show does not combine non-LogLog plots with LogLog plots, even when they coincide, eg.:               Show[LogLogPlot[x^4, {x,10^(-10),10^10}], Plot[x^5, {x,10^(-10),10^10}]]      should theoretically show two straight lines, but shows only one. Is there a way to combine such graphics without resolving to using non-LogLog plots?


title: Positions of a string in a list

text: Sorry for the bad title..Didn't know how to describe this, feel free to change it to be more specific. I have a list in this form:               list = {"a(0)", "a(1)", "a(2)"}      Now I want the positions of all a* in the list. At first I thought this is easily done with the Position-function, but then I had some difficulties:               Position[list, "a"]      Thought this would work, but somehow I'm missing something. So..how to implement the * to give me all a's regardless of the following characters?


title: How to plot an inequality?

text: I need some help in plotting the following inequality using Mathematica: $$\frac{1+(x/100+0.1)\times y/100}{1.15+1.15\times(x/100)\times(y/100)}\geq 1$$ assuming $x,y\in \mathbb{Q}$, the set of rational numbers and $5\leq x\leq 90,\ 50\leq y \leq 650$. Copyable code for the above inequality:               (1 + (x/100 + 0.1)(y/100))/(1.15 + 1.15 (x/100)(y/100)) >= 1      I've tried the following in Maple (because it's what we had available) but it only simplifies the term and does not plot it and enclosing the inequality with `plot()` in Maple only generates errors.               assume(x, rational);     assume(y, rational);     assume(x>=5 and x<=90);     assume(y>=50 and y<=650);     (1+1*(x/100+0.1)*(y/100))/(1.15+1.15*(x/100)*(y/100))>=1;      ### Optional theoretical problem: $x$ could theoretically (not in practice) be up to $100$, but $(x/100+0.1)$ on the left side would still always max out at $1$. Should the equation be changed to $x_1$ and $x_2$ with respective limits? But those limits would only apply for $x_1$ and $90< x_2 \leq 100$.


title: How do I toggle between the program snippet form of a displayformula and the human readable form of the equation?

text: I have a DisplayFormulaNumbered cell in my Mathematica notebook. If I use the Cell | Convert To menu item to convert the cell to Standard or Traditional Form, the formula is now rendered as a program snippet. For example:               TextCell[RawBoxes[Cell[BoxData[FormBox[RowBox[{RowBox[{RowBox[{RowBox[{"L","\[CenterDot]",RowBox[{RowBox[{"I","'"}],"'"}]}],RowBox[{"(","t",")"}]}],"+",RowBox[{RowBox[{"R","\[CenterDot]",RowBox[{"I","'"}]}],RowBox[{"(","t",")"}]}],"+",RowBox[{FractionBox["1","C"],"\[CenterDot]",RowBox[{"I","(","t",")"}]}]}],"=",RowBox[{RowBox[{"V","'"}],RowBox[{"(","t",")"}]}]}],TraditionalForm]],FormatType->"TraditionalForm"]]]      Is there a way to toggle this cell to the human readable form I started with?


title: How do you pattern match a DataDistribution

text: I have a function,               f[dist_, samp_]:=somework[dist, samp]      that I want to return `Null` or zero if passed a null distribution. I can't find a way to test for a difference between `Null` and Data distribution: none of `===`, `=!=`, `SameQ` and `==` can identify them. How can I tell if I'm being passed a `Null` value to handle it correctly?               f[dist_, samp_]:=something[dist, samp] /; TrueQ[dist==DataDistribution]      Seems to be close to what I want. EDIT: Edited for some clarity. Here's my function. If probKern is a Null, I want to return a Null, otherwise, I want to calculate the PDF for the sample, with the distribution. I can't quite get a handle on matching the types to make this work though.               calcPDF[probKern_, samp_] :=       Null /; TrueQ[probKern != DataDistribution]          calcPDF[probKern_Symbol, samp_] :=       PDF[probKern, samp] /; TrueQ[probKern == DataDistribution]      edit: Okay, I'm still having trouble with this. Here's what I have:               calcPDF[probKern_DataDistribution, samp_] := PDF[probKern, samp]       calcPDF[Except[_DataDistribution, probkern_?DistributionParameterQ], samp_] := -1      calcPDF[_] := $Failed      Given a data distribution and a value it works fine.               In[38]:= calcPDF[data, 3]          Out[38]= 0.007500611755      Given two numbers, it produces the symbolic value, rather than the -1 I was expect. (The -1 is just a placeholder)               In[39]:= calcPDF[3, 3]          Out[39]= calcPDF[3, 3]      EDIT dec 5th: Running calcPDF by hand seems to result in correct results, but now, when it is threaded over data, the result is a single result of whatever you return in the Except case. There's two sets of distributions I'm running over the sample data, so the final result is a list of two Nulls (or -1's). If you remove the Except case, you get closer to the expected result - two lists 205 elements long, containing PDF's for entries with matching Distributions, and PDF[Null, value] for those without. I'm confused. Clear[calcPDF] (*calcPDF[probKern_, samp_]:=PDF[probKern, samp]; *) calcPDF[probKern_DataDistribution, samp_] := PDF[probKern, samp]; calcPDF[Except[ _DataDistribution], samp_ ] := Null; (* Pass a list of samples, and a list of distributions's *) applyKernel[lsamples_, kernel_] := Thread[calcPDF[kernel, lsamples]]; (* Pass a list of samples, and a list of two lists of distribution's *) predClass[samples_, kernels_] := Map[applyKernel[samples, #] &, kernels]; predPDF = predClass[predictionSamples[[1]], kernels]


title: Find lengths of contours in a ContourPlot

text: I am trying to find the lengths of different contours in the following plot: ![ContourPlot of interest!!](http://i.stack.imgur.com/6qsD1.jpg) It is a complicated piecewise function evaluated on the unit disk. I am hoping there is an easy, generalized way to numerically approximate each of the contours' lengths. Essentially, I am looking for a way to solve for the length of a homogenous equation bound by a region. Given a function `f(x,y) - f* == 0` on a region `R`, where `f*` is the value of the contour of interest, is there a way to find the length of the curve that satisfies that equation? For concreteness, the above is the `ContourPlot` of               q[r_] := Piecewise[{{25/(0.1*1), r < 0.1}, {25/r, r >= 0.1}}]     phi[r_, t_] := (Pi/2) + q[r]*t     v[r_, t_] := q[r]*r*Cos[phi[r, t]]     s[x_] := Piecewise[{{x = -1, x < 0}, {x = 1, x >= 0}}]          f[x_,y_] := s[x]*v[Sqrt[x^2 + y^2],ArcTan[y/x]/q[Sqrt[x^2 + y^2]]]      How does one numerically find the lengths of each of those contours?


title: Small random disturbance of a flat surface

text: I am trying to create an initial condition which is: `1 + 0.05 rand(x,y)` Here rand is a pseudorandom function distributed in the interval (-1,1). This surface represents a random disturbance that I would like to use as an initial condition for PDEs in `NDSolve`. I assume I am being very silly when I try to use `RandomReal[]` as my random number generator for my random disturbance. How should I proceed with this.               L = 100;     Plot3D[      1 - 0.05 (Cos[2 \[Pi] x/L] + Sin[2 \[Pi] x/L]) Cos[         2 \[Pi] y/L] RandomReal[],      {x, 0, L},      {y, 0, L}      ]      Obviously this is wrong as this still retains the underlying Cos/Sin curve. How should I go about creating a random disturbance. ## Working example:               $HistoryLength = 0;     Needs["VectorAnalysis`"]     Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];     Clear[Eq0, EvapThickFilm, h, Bo, \[Epsilon], K1, \[Delta], Bi, m, r]     Eq0[h_, {Bo_, \[Epsilon]_, K1_, \[Delta]_, Bi_, m_, r_}] := \!\(     \*SubscriptBox[\(\[PartialD]\), \(t\)]h\) +          Div[-h^3 Bo Grad[h] +            h^3 Grad[Laplacian[h]] + (\[Delta] h^3)/(Bi h + K1)^3 Grad[h] +            m (h/(K1 + Bi h))^2 Grad[h]] + \[Epsilon]/(         Bi h + K1) + (r) D[D[(h^2/(K1 + Bi h)), x] h^3, x] == 0;     SetCoordinates[Cartesian[x, y, z]];     EvapThickFilm[Bo_, \[Epsilon]_, K1_, \[Delta]_, Bi_, m_, r_] :=        Eq0[h[x, y, t], {Bo, \[Epsilon], K1, \[Delta], Bi, m, r}];     TraditionalForm[       EvapThickFilm[Bo, \[Epsilon], K1, \[Delta], Bi, m, r]];                              L = 2*92.389; TMax = 3100*100;     Off[NDSolve::mxsst];     Clear[Kvar];     Kvar[t_] :=  Piecewise[{{1, t <= 1}, {2, t > 1}}]     (*Ktemp = Array[0.001+0.001#^2&,13]*)     hSol = h /. NDSolve[{          (*Bo,\[Epsilon],K1,\[Delta],Bi,m,r*)               EvapThickFilm[0.003, 0, 1, 0, 1, 0.025, 0],          h[0, y, t] == h[L, y, t],          h[x, 0, t] == h[x, L, t],          (*h[x,y,0] == 1.1+Cos[x] Sin[2y] *)               h[x, y, 0] == BSplineFunction[RandomReal[1, {30, 30, 1}]]          },         h,         {x, 0, L},         {y, 0, L},         {t, 0, TMax},         Method -> {"BDF", "MaxDifferenceOrder" -> 1},         MaxStepFraction -> 1/50         ][[1]]      With the BSpline as suggested by Vitaliy Kaurov in the answer below, I have the following error: > NDSolve::ndnum: Encountered non-numerical value for a derivative at t == > 0.`. >> > > ReplaceAll::reps: {(h^(0,0,1))[x,y,t]-0.009 h[x,y,t]^2 > (h^(0,1,0))[x,y,t]^2-(0.05 h[x,y,t]^2 > (h^(0,1,0))[x,y,t]^2)/(1+h[x,y,t])^3+<<13>>+h[x,y,t]^3 > ((h^(0,4,0))[x,y,t]+(h^(2,2,0))[x,y,t])+3 h[x,y,t]^2 (h^(1,0,0))[x,y,t] > ((h^(1,2,0))[x,y,t]+(h^(3,0,0))[x,y,t])+h[x,y,t]^3 > ((h^(2,2,0))[x,y,t]+(h^(4,0,0))[x,y,t])==0,h[0,y,t]==h[184.778,y,t],h[<<1>>]==<<1>>,h[x,y,0]==BSplineFunction[{{0.,1.},{0.,1.}},<>]} > is neither a list of replacement rules nor a valid dispatch table, and so > cannot be used for replacing. >>


title: How to get StreamPlot to draw many hundreds of streamlines?

text: For artistic reasons, I want to draw an extremely dense `StreamPlot` with something like a thousand streamlines. I tried setting `StreamPoints -> {Automatic, d}` where $d$ is a small value specifying the minimum distance between streamlines, but after a point reducing the value of $d$ stops having an effect.               GraphicsColumn[      StreamPlot[{-1 - x^2 + y, 1 + x - y^2}, {x, -3, 3}, {y, -3, 3},          StreamPoints -> {Automatic, #}, ImageSize -> Medium] & /@ {1, 0.3,         0.1, 0.03, 0.01}]      (click for image) The same thing happens when setting `StreamPoints -> n` for increasing values of $n$, or when manually seeding hundreds of seed points; Mathematica silently refuses to plot any more streamlines. How can I get around this? Is it possible to plot arbitrarily closely spaced streamlines using `StreamPlot`? **Update:** To clarify, I want to keep the style of the fully-automatic default `StreamPlot`, which attempts to maintain a uniform spacing between streamlines, and just make it denser. So I don't want to get rid of the minimum distance entirely; I just want to lower it. To save everyone some time, here is what I find unsatisfactory about all the documented settings for `StreamPoints`.   * `None`: Obviously no good.   * $n$: Stops having an effect somewhere between 50 and 100.   * `Automatic`, `Coarse`, and `Fine`: Not dense enough.   * `{p1, p2, ...}` and `{{p1, g1}, ...}`: See `n`.   * `{spec, d}`: `d` stops having an effect somewhere between 0.2 and 0.1.   * `{spec, {dStart, dEnd}}`: Strangely, increasing `dEnd` plots _more_ streamlines. Compare `{Automatic, {0.5, 10}}` with `{Automatic, 0.5}` and `{Automatic, {0.5, 0.5}}`. I don't understand this setting at all.   * `{spec, d, len}`: When `spec` is `Automatic`, `len` has no effect as far as I can tell. On the other hand, when `spec` is `{p1, p2, ...}`, `len` causes `d` to be ignored completely.


title: Embed a Microsoft RichEdit 8 control in a Mathematica notebook using .NETLink?

text: Does anyone know whether or not it's possible to embed a RichEdit 8 control within a Mathematica Notebook using .NETLink? The goal here would be able to both view and edit mathematical text typeset using Microsoft Word 2013 from within a Mathematica notebook. More background on the development of mathematical typesetting capabilities in Microsoft Office (and the RichEdit control) is available here: Murray Sargent's blog


title: solve an integral equation numerically

text: I am trying to find a numerical solution for an equation of the form: $$ f(t)=\int_{t_{min}}^{t} {\exp[2 (t^\prime - t)] E(t^\prime) f(t^\prime)} \+ \int_{t}^{0}{ \exp(t^\prime - t) E(t^\prime) f(t^\prime)} $$ where $E$ is the complete elliptic integral of the first kind and $t_{min}$ can be in principle any negative integer. I have tried `NIntegrate` and some iteration but didn't get me too far... can anyone help me with a better idea? Thank you very much for your help!!!


title: Adding ContourLabels changes contour colors?

text: I have an array `s5` I want to plot using `ListContourPlot`               s5 = Import[       "https://github.com/downloads/stackmma/Attachments/data_13545.m"];     ListContourPlot[s5, InterpolationOrder -> 6, ColorFunction -> "TemperatureMap",          ContourLabels -> True, ColorFunctionScaling -> True]      ![Mathematica graphic with labels](http://i.stack.imgur.com/ZmGGp.png) Note, the blue spot in the corner. Turning off `ContourLabels` gives               ListContourPlot[s5, InterpolationOrder -> 6, ColorFunction -> "TemperatureMap",        ContourLabels -> False, ColorFunctionScaling -> True]       ![Mathematica graphics](http://i.stack.imgur.com/OoQpV.png) The resulting images have entriely different colors. I cannot understand why adding `ContourLabels` should change the colors, and for other data sets it seems to not do that. I ended up using a workaround that involved making one of the pictures mostly transparent and overlaying it with a picture that had the right colors. This I think is actually the simplest workaround proposed so far:               wl = ListContourPlot[s5, InterpolationOrder -> 6,      ColorFunction -> (Append[ColorData["TemperatureMap"][#1], 0] &),      ContourLabels -> True, Contours -> contours];          nl = ListContourPlot[s5, InterpolationOrder -> 6,      ColorFunction -> "TemperatureMap", Contours -> contours];     Show[nl,wl]


title: Converting a matlab program into Mathematica 10

text: I sought help from this entry at Calling MATLAB from Mathematica to see if I could CONVERT a mathlab program which simulates polymer dynamics that is provided at the download section at http://tx.technion.ac.il/~yoniw/CompPhysProjectHtml/PolymerSimProject.htm#_Toc353147515 into a mathematica-10 code. Any ideas as to how the conversion can be done? The origin program simulates the behaviour of chained polymer placed in a solvent of interacting particles, and employs dissipative particle dynamics. There is a linear search via parallel computing. Not clear how this can be implemented in MMA.


title: How to display cell groups in documentation pages

text: I recently introduced my WildCats package in the Meta Thread What third-party packages do you use? and @Szabolcs promptly observed that:   "I noticed that there are many cell groups in the documentation that are collapsed. The documentation browser doesn't display cell brackets so it's a little difficult to expand them (I used the Ctrl-' shortcut)." Indeed I like to close all section groups in the tutorial pages so - upon opening the doc window - the user can immediately see the summarized full contents of the (often long) tutorial. This is much better than having to scroll through a long doc page in search of the relevant piece of information. But then the question is: how do we open these closed section groups, given that documentation pages do not display (section) cell brackets? One solution, although not very user-friendly, was already suggested by Szabolcs: use the Ctrl-' shortcut. But there are better ones! and since they do not seem to be very well-known, I thought of posting this question and my suggested solution


title: Is it safe to change the value of $TimeZone?

text: I'd like to configure some of my notebooks to assume all calculations using dates, times and locations (notably `AstronomicalData` , but others too) take place at the Greenwich Observatory. I know I can achieve this by unprotecting `$TimeZone` and setting it to `0`, as with                   $GeoLocation = {51.476786, 0.00000000};         Unprotect[$TimeZone];         $TimeZone = 0;         Protect[$TimeZone];      but worry that this might have some other consequences that would confuse date and time functions. Is it safe to do this? Does changing the value of `$TimeZone` have side effects I should avoid?


title: When are `If`, `Piecewise`, `Switch`, and `Which` interchangeable and when are they not?

text: Experimenting with joint dependent distributions via the `TransformedDistribution` function, I used the following to derive a distribution where the second variate is distributed dependent on the value of the first variate (very simplified & contrived example follows).               distA = TransformedDistribution[{b,         If[b == 1, d1, d2]}, {b \[Distributed]          DiscreteUniformDistribution[{1, 2}],        d1 \[Distributed] UniformDistribution[{1, 2}],        d2 \[Distributed] UniformDistribution[{2, 3}]}]               distB = TransformedDistribution[{b,         Piecewise[{{d1, b == 1}, {d2, b == 2}}]}, {b \[Distributed]          DiscreteUniformDistribution[{1, 2}],        d1 \[Distributed] UniformDistribution[{1, 2}],        d2 \[Distributed] UniformDistribution[{2, 3}]}]          distC = TransformedDistribution[{b,         Switch[b, 1, d1, 2, d2]}, {b \[Distributed]          DiscreteUniformDistribution[{1, 2}],        d1 \[Distributed] UniformDistribution[{1, 2}],        d2 \[Distributed] UniformDistribution[{2, 3}]}]          distD = TransformedDistribution[{b,         Which[b == 1, d1, b == 2, d2]}, {b \[Distributed]          DiscreteUniformDistribution[{1, 2}],        d1 \[Distributed] UniformDistribution[{1, 2}],        d2 \[Distributed] UniformDistribution[{2, 3}]}]      The first two behave as I'd expect: `Mean, Var, RandomVariate` all do what they're supposed to. The latter two, while behaving as expected for the _simple_ probability functions (e.g. `Mean`), puke on any attempt to sample with `RandomVariate`, with the message > TransformedDistribution::nnbprm: The valid numeric parameters of > distribution > TransformedDistribution[{\FormalX]1,Switch[\FormalX]1,1,\FormalX]2,2,\FormalX]3]},\FormalX]1,\FormalX]2,\FormalX]3}\Distributed]ProductDistribution[DiscreteUniformDistribution[{1,2}],UniformDistribution[{1,2}],UniformDistribution[{2,3}]]] > are expected. Use DistributionParameterAssumptions to obtain the parameter > assumptions. >> I'm a bit puzzled by this, seems the forms in this case should result in equivalent behavior. Any insights?


title: Re[x] vs. x ∈ Reals in the context of Assuming

text: Let's say that $x$ is some real valued number $>0$.   Are the following commands interchangeable in the context of using `Assuming`?   1. `Assuming[{Re[x] > 0}, Integrate[...,x]]`   2. `Assuming[{x ∈ Reals && x > 0}, Integrate[...,x]]` Or, as I suspect, is this not true for the reason that `Re[x] > 0` should just mean that the Real component of $x$ is $>0$? Also, is there a way to more compactly specify `{x ∈ Reals && x > 0}`?


title: Suspend computation so it can be resumed even after the PC is rebooted

text: Sometimes a computation takes a long time. But when I sleep in the night, I want to shutdown my PC. Next morning when I wake, I want to start _Mathematica_ and resume the computation. If you are familiar with the virtual machine `VMWare`, what I am looking for is a feature like `VMWare`'s `suspend/resume`. Does _Mathematica_ have such a feature?


title: Plotting time data with axes labels and point labels

text: I am trying to create a set of commands to automatically create clinical lab value plots. Using time is my major issue here. It is hard to dynamically reference the different point positions to include their labels. The value of each point located directly above it if possible. These values are located at value[i]. What I currently have ![Current Output](http://i.stack.imgur.com/e2O51.jpg) Would I would like roughly ![Desired](http://i.stack.imgur.com/TwIjV.jpg)               (* {{year,month,day,hour,minute},value}  *)     data = {        {{2014, 1, 20, 17, 42}, 6.84},        {{2014, 1, 20, 22, 33}, 5.87},        {{2014, 1, 21, 6, 30}, 4.7}        };          (* Effects the look of plot *)     min = 4;                                                              \           (* Minimum Stable level *)     max = 11;                                                             \         (* Maximum Stable level*)     Title = "WBC Count";                                    (* Label of \     Plot *)     taxis = "Time";                                                 (* \     Label of time axis *)     yaxis = "k/\[Mu]L";                                                (* \     Label of measured axis *)     tend = 20;                                                   (* make \     very large, defines how long the time for the min/max range is *)          RotationDegree = 0;                                    (* Rotate the \     labels by \[Theta] *)     Plotmin = 0;                                                     (* \     Minimum value to display *)     Plotmaxadd = 1;          times = Table[0, {i, Length[data]}];     Do[times[[i]] =        DateString[        data[[i, 1]], {"Month", "/", "Day", " ", "Hour", ":",          "Minute"}], {i, Length[data]}]     value = Table[0, {i, Length[data]}];     Do[value[[i]] = data[[i, 2]], {i, Length[data]}]     a = With[{labels =           Rotate[DateString@#, RotationDegree/180*\[Pi]] & /@ times},         ListPlot[data[[All, 2]], Mesh -> All,          MeshStyle -> PointSize[Large], Joined -> True,          PlotRange -> {Plotmin,            Max[Max[data[[All, 2]] + Plotmaxadd] + Plotmaxadd,             max + Plotmaxadd]},          PlotLabel -> Style[Row@{Title}, FontSize -> 18],          PlotStyle -> {Thick}, Frame -> True,          FrameTicks -> {Transpose[{Range@Length@labels, labels}],            Automatic}, FrameLabel -> (Style[#, 18] & /@ {taxis, yaxis})]];     b = Plot[{min, max}, {t, 0, tend},         PlotStyle -> {{Thick, Red}, {Thick, Green}},         Filling -> {1 -> {{2}, RGBColor[.4, 1, .4, .2]}}];     c = Show[a, b]      **Current Results:** What I currently have ![enter image description here](http://i.stack.imgur.com/ySqia.jpg)               (* Type of Date and units *)     Title = "Platelets";                                        (* Label \     of Plot *)     taxis = "Time";                                                     (* \     Label of time axis *)     yaxis = "k/\[Mu]L";                                                   \       (* Label of measured axis *)     (* {{year,month,day,hour,minute},value}  *)     data = {        {{2014, 1, 20, 17, 42}, 139},        {{2014, 1, 20, 22, 33}, 123},        {{2014, 1, 21, 6, 30}, 126}        };     (* Effects the look of plot *)     dateplotbegin = {2014, 1, 20, 16,         0};(* Time to begin showing extreme values *)     dateplotend = {2014, 1, 21, 7,         10};     (* Time to end showing extreme values *)     min = 150;                                                            \      (* Minimum Stable level *)     max = 450;                                                            \           (* Maximum Stable level*)     plotmin =        0;                                                             (* \     Minimum Value to plot *)     plotmax =        600;                                                       (* Max \     value from the highest value to plot, might need tweeking based on \     lab*)          (* Font Sizes *)     TitleFont = 24;     AxesFont = 24;     PointFont = 20;     TickFont = 12;     (* Plotting, no need to touch this *)     dlp[u_, dmn_, dmx_, plotmin_, plotmax_, min_, max_,        opts : OptionsPattern[]] :=       DateListPlot[u, GridLines -> {None, {min, max}},        FilterRules[{opts}, Options[DateListPlot]],        PlotRange -> {{dmn, dmx}, {plotmin, plotmax}}, Joined -> True,        Epilog -> {{Opacity[0.5], RGBColor[.4, 1, .4, .2],           Polygon[{{dmn, min}, {dmx, min}, {dmx, max}, {dmn,              max}}]}, (Text[             Style[#[[2]], FontSize -> PointFont], {1, 1.1} #] & /@ u)},        BaseStyle -> {FontFamily -> "Times", TickFont},        FrameLabel -> (Style[#, AxesFont] & /@ {taxis, yaxis})]     dlp[data, dateplotbegin, dateplotend, plotmin, plotmax, min, max,        PlotMarkers -> {Automatic, 8},        GridLinesStyle -> Directive[Red, Thick],        PlotLabel -> Style[Row@{Title}, FontSize -> TitleFont],        PlotStyle -> {Thick},       FrameTicks -> {{Automatic, None}, {data[[All, 1]], None}},        DateTicksFormat -> {"Month", "/", "Day", "\n", "Hour", ":",          "Minute"}];     plot = Show[%, ImageSize -> {644, 385}, AspectRatio -> Full]


title: Clustering a bivariate data set with Mathematica

text: I need to partition a bivariate data set into predetermined "n" clusters and, at the same time, to fix the centroid position of each cluster. Is the `ClusteringComponents` function useful? Thanks BR for your help. I will use your example to explain better my question I want to Split your “data” into two (n=2) clusters. Previously, I want to fix the coordinate (centroids) of the two clusters.               data = With[{\[Rho] = -0.4},      RandomVariate[BinormalDistribution[{-1, 1}, {1, 2}, \[Rho]], 10000]];          FIXEDcentroids = {{-2, 0}, {0.5, -0.4}};          Show[ListPlot[data, Frame -> True, Axes -> False],      ListPlot[FIXEDcentroids, Frame -> True, PlotStyle -> {Black, PointSize[0.02]}]]       The next step should be to "force" the clustering process to split the “data” set according the position of the two predefined centroids. If I use the `FindCluster` traditional form:               NumberOfCluster = 2;     clusterdata = FindClusters[data, NumberOfCluster];      I obtained two new centroids.               centroidFindClusters = Mean[#] & /@ clusterdata      Obviously the two new centroids are differents from those that I preselected (i.e. FIXEDcentroids). Therefore I am not able to solve my problem.... ...if were possible to write: `FindClusters[data, FIXEDcentroids]` it would be perfect......


title: Symbolic integration fails while numerical integration succeeds

text: I am hoping to evaluate the following integral               Integrate[((r^3 - 7)^(2/3)*(1 - (r^3 - 7)^(2/3)/r^2))/r^3, {r, 2, Infinity}]      but Mathematica informs me that this integral "does not converge on {2,$\infty$}." However, the numerical integration command               NIntegrate[((r^3 - 7)^(2/3)*(1 - (r^3 - 7)^(2/3)/r^2))/r^3, {r, 2, Infinity}]      yields `0.139837` without mention of any difficulties. Which should I believe?


title: Count sublists which match pattern

text: I have a list which looks like this: `data={{12,0},{0,0},{20,1},{0,0}, {0,-1}}`. Now I would like to count the number of sublists which:   * have both slots zero   * the first slot zero and the second not   * the second slot zero and the first not   * the first slot < 10 and any the second zero


title: I don't understand ListCorrelate!

text: I want to solve a PDE equation (like Schrodinger equation) using finite difference in Mathematica. I don't understand what this code does!               ListCorrelate[{1, -2, 1}/Subscript[h, n]^2,        U[t], {1, 2}, {Subscript[u, n - 1][t]}]/8      Anyone can help me? What does `{1, 2}` mean? and what's the role of `{Subscript[u, n - 1][t]}` ?


title: BaseStyle ->AbsoluteThickness[somenumber] doesn't work in version 10?

text: Users of version 9 might be surprised by this outcome:               Plot[{Sin[x], Cos[x]}, {x, 0, 5}, BaseStyle -> AbsoluteThickness[5]]      ![enter image description here](http://i.stack.imgur.com/0GheD.png) It seems that `BaseStyle->AbsoluteThickness[whatever]` doesn't work anymore. How can one fix this?


title: Set form of all output to InputForm

text: I try to interact with mathematica using MathLink for symbolic computations. By default it returns strings such as `2\012-1 + E\012-------\012 3\012 E` if the input is `Integrate[Exp[-x],{x,1,3}]`. For better usability I would like it to print all output in `InputForm` which I could achieve by wrapping all input by a `InputForm[]` command (would this be bullet-proof for all possible input?). However it would be more elegant if I could define this once for all at the beginning of a session. Is there a way to do this? Furthermore the output seems to include the `Out[#]` labels which I know from Notebook files. I would prefer to suppress it as well. Obviously I could do it by cutting it manually from the returned string but there might be an elegant solution as well.


title: How to convert equation to vector (matrix) form?

text: How can I **convert** expression `a1*u1+a2*u2+a3*u3` to the vector form of dot product `A.U`, where `A={a1,a2,a3}` and `U={u1,u2,u3}`?


title: ParametricNDSolve: Fails to differentiate an matrix differential equation

text: It seems like there is a problem with differentiating a ParametricNDSolve object when the underlying system contains an matrix differential equation. Create a simple ParametricNDSolveValue object which returns x[2], depending on parameter k.               pfun1 = ParametricNDSolveValue[{x'[t] == -k*x[t], x[0] == 10}, x[2], {t, 0, 10}, k]     ParametricFunction[SequenceForm["<", ">"]]      Now we have the same system but we add a matrix differential equation independent of the state `x[t]`. Here `P[t]` should be zero for all t due to the inital condition.               pfun2 = ParametricNDSolveValue[{x'[t] == -k*x[t], x[0] == 10,      P'[t] == P[t], P[0] == {{0, 0}, {0, 0}}}, x[2], {t, 0, 10}, k]     ParametricFunction[SequenceForm["<", ">"]]      We can take out the values for `k=0.4`.               pfun1[0.4]     pfun2[0.4]     4.49329     4.49329      Now we differentiate the systems and take out the value for `k=0.4`.               pfun1'[0.4]     pfun2'[0.4]     -8.98658     Thread::tdlen: Objects of unequal length in {{0.},{0.},{0.},{0.},{0.}}+{{0.},{-10.}} cannot be combined. >>*     Experimental`NumericalFunction::nlnum1: The function value {{{0.},{-10.}}+{{0.},{0.},{0.},{0.},{0.}}} is not a list of numbers with dimensions {5} when the arguments are {0.,{0.,0.,0.,0.,10.},{0.4},{{0.},{0.},{0.},{0.},{0.}}}.      The derivative of the ParametricNDSolveValue object seems to fail when there is a matrix differential equation in the system. Is this a bug?


title: How to save the results in an identical Excel file (.xls) in each iteration of a Do loop

text: Assume the following code (Below code is just an example to clearly illustrate my problem):               Res = {};     Iterations = 5;          Do[     Results = AppendTo[Res, i^2]     , {i, 1, Iterations}];      I have 2 questions:   1. I want to save the results in each iteration in an identical excel file (.xls file). In the end, when the iterations are finished, I will have one Excel file with all the results in it.   2. I tried to make the code more faster and elegant using `Scan[]` , but I failed to do it and I couldn't do that.(It is good to mention that I am just a rookie _Mathematica_ programmer and I don't have much experience in it!). Could you please help me with these poroblems ?


title: Exporting lists to files

text: I am trying to write a program which will generate a list of objects and then exports it in a separate file and clears its memory. As an example I tried the following               Do[{Subscript[l, p] = Table[Subscript[l, p, i], {i, 10}];       Export["\!\(\*SubscriptBox[\"l\", \"p\"]\).mnaz",         Compress[Subscript[l, p]], "String"]; Clear[Subscript[l, p]]}, {p,        1, 3}]      Of course, the above is just a sample (and my actual list(s) are more bulky (actually they are list of matrices)), but I hope it explains the spirit. I wanted to export each list separately so that I can get separate files like `l_1.mnaz`, `l_2.mnaz` etc., which I can import again by using the same type of code. **Motivation** : I need to actually generate a huge list of data. However whatever I do, my system goes out of memory after 5000 loops, which itself takes a lot of time. One reason is that, I need to modify the list at each loop. It seems 1000 loops takes a reasonable time. Hence I am trying to break the loop into smaller chunks, export the data, and clear the memory for the next loop. `Clear[Subscript[l, p]]` is used for that purpose.


title: Is it safe to use older version subkernels with a newer version main kernel?

text: At the moment we only have access to version 8 of the Lightweight Grid (i.e. version 8 of the Mathematica kernel). Is it safe to run version 8 subkernels together with a version 9 main kernel? It does appear to work, but I am not sure if things can go wrong in unexpected ways. (For safety I use a v8 main kernel for these calculations, but I since everything seems to work with a v9 main kernel as well, I was curious if this is actually supported.)