title: Manipulate embedded in a CDF ducument and started by a button

text: **Preamble** : I am working on a document that I plan to publish as a Supplementing in a regular scientific journal in the CDF form. In this document I fail to make the following thing: **Explanations** : There should be a button embedded in the text of a document referred below as the "main document". It is very much like in my recent question: How to specify a StyleSheet of a newly programmatically-created notebook? Upon its pressing, this button should bring up a notebook containing some text and an evaluated Manipulate statement. To be specific, here is a simplified example:                   Button["Show",      CreateDocument[       Column[{         TextCell["Some text" , "Text", FontSize -> 20],         ExpressionCell[          Manipulate[           Plot[Sin[a*x], {x, 0, 2 \[Pi]}], {a, 0, 1}]          ]         }],       WindowTitle -> "Some title", WindowSize -> {550, 400}],       ImageSize -> {50, 18}, BaseStyle -> {"GenericButton", Bold}]      Upon evaluation of this code a button appears. This button can be copy-pasted into any line of the text cell of the main notebook document. It should like like this:                                    Some text button some more text.       where instead of the word "button" the button should stay. Upon pressing this button the notebook opens. It contains the text "Some text" and should contain the dynamic demonstration defined by the Manipulate statement above. **The problem** : It works nicely in Mathematica. It does not, if I transform the main document into cdf. When I press the button in this cdf version of the document, the interactive part is not shown, instead a gray rectangle appears and a message comes up "This dynamic content cannot be displayed by the CDF player. To display this dynamic content requires Mathematica". However, it is a very innocent Manipulate statement, which is certainly displayed, if I put it in the CDF directly, not by such an oblique way. I guess that it is some CDF limitation here. However, **My questions** :   * Do you see any workaround here?    * May it be that it is since the document created this way is .nb, rather than .cdf, and it results in my attempts to use the CDF-Player to read the .nb document?   * If yes, most probably I cannot instruct Mathematica to create .cdf instead of .nb starting from the cdf main document, can I? Thank you in advance. Later edit: I indeed asked already this and have forgotten it completely. I am sorry. The outcome is that such a thing is impossible. That's a pity.


title: Alternatives pattern in a function definition

text: I thought that I remembered a way to write a function definition using "|", but can't find documentation for it. So for example, I'd want to define:               f[1, x_] := x^2;     f[2, x_] := x*12;      I thought there was a syntax, kind of like a "select case" or "switch" statement that used "|". Is there?


title: How to texturize a Disk/Circle/Rectangle?

text: The documentation for `Texture` states that " ** _other filled objects_** " can be texturized: > `Texture[obj]` is a graphics directive that specifies that _obj_ should be > used as a texture on faces of polygons and other filled graphics objects. And also: > Texture can be used in FaceForm to texture front and back faces differently. Though I fail to apply a simple texture to any of the following objects. It seems like that "other filled objects" only include `Polygon`s and `FilledPolygon`s, and `FaceForm` does not work with those.               img = Rasterize@        DensityPlot[Sin@x Sin@y, {x, -4, 4}, {y, -3, 3},          ColorFunction -> "BlueGreenYellow", Frame -> None,          ImageSize -> 100, PlotRangePadding -> 0];     {      Graphics[{Texture@img, Disk[]}],      Graphics[{FaceForm@Texture@img, Disk[]}],      Graphics[{Texture@img, Rectangle[]}],      Graphics[{FaceForm@Texture@img, Rectangle[]}],           (* Only this one works *)      Graphics[{Texture@img,         Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}},          VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}],      Graphics[{FaceForm@Texture@img,         Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}},          VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]}]      }      ![Mathematica graphics](http://i.stack.imgur.com/3M0Id.png) **Edit:** It turns out that "Applying `Texture` to a disk directly isn't possible" (according to Heike, thanks s.s.o. for the link). This unfortunately means that:   1. the official documentation of `Texture` is wrong (or at least is misleading, as graphics objects usually include primitives);   2. either `Texture` is not fully integrated with the system, as it is not applicable for such primitives as a `Rectangle`, which seems to be just a very specific `Polygon`; or `Rectangle` is something else and is defined some other way at the lowest level than a `Polygon` (maybe it is some OS-dependent object). Frankly, it is quite hard to imagine what kept developers to include this functionality, but I must assume they had a good reason.


title: Problem with ListContourPlot feeding data format and WeatherData

text: With following code I am trying to show the mean wind speed patterns for a few geographic locations.               cords = Select[                 Reverse[CityData[#, "Coordinates"]] & /@ {"Oslo", "Vadso","Hammerfest"},                 Head@# == List &             ];      ListContourPlot[       Join @@ {#,List@WeatherData[#,                                   "MeanWindSpeed",                                    {{2013, 1, 25}, {2013, 5, 1}, "Day"}                       ][[1,2]]} & /@ cords     ]      How can I improve the code to solve following problems:   1. Even if the requested date window is wider (a few days), it only takes one day data from `WeatherData` and when I am changing the partitioning part to `[[All,2]]` the plot doesn't work and says the format it wrong.   2. For even wider data range (a few years), there are some missing data for some days. How can I also filter that bad data in the code? Remember, I need them exactly on the geographic location no matter how wide my data range is.


title: Options in a StringReplace rule

text: * case1              Options[f] = {"t" -> "0"};     f[___, OptionsPattern[]] :=  StringReplace["content", "t" :> OptionValue["t"]]          f[]          (*     con0en0     *)        * case2              rule = {"t" -> OptionValue["t1"]};          Options[gg] = {"t1" -> "T1", "t2" -> "1"};     gg[___, OptionsPattern[]] := StringReplace["content", rule]          gg[1]          (*     con~~OptionValue[t1]~~en~~OptionValue[t1]     *)      Here `OptionValue` couldn't get the value of "t1" So, how to make case 2 works like case 1? * * * I found one solution is               Options[gg]={"t1"->"T1","t2"->"1"};     gg[___,OptionsPattern[]]:=Hold[StringReplace]["content",rule]//ReleaseHold//Evaluate      Any simpler methods?


title: Install issue: Mathematica 9 on Ubuntu 13.10

text: I am trying to install Mathematica 9 on a Ubuntu 13.10 system. I had this working on my previous 13.04 version but now it breaks on when trying to unpack the sh archive:               $ sh Mathematica_9.0.0_LINUX.sh     Mathematica Secured 9.0.0 for LINUX Installer Archive          Verifying archive integrity.      Extracting installer. ...........................................................................     /home/stefan/Downloads/.3719     CRITICAL FAILURE: Fundamental Error      Installer text not found.      sudo sh ... produces same error, the md5 hash checks out ok. Anybody encountered this problem, and more to the point, figured out what is wrong? I submitted a ticket to Wolfram support but no luck there so far. Thanks for any ideas to try.


title: Removing pairs that meet a given criterion from a list

text: Let $(x_{min},x_{max})$ and $(y_{min},y_{max})$ represent lowerbound and upperbound acceptable values for some coordinate $c_i$. Setting $x_{min} = y_{min} = 1$ & $x_{max} = y_{max} = 9$, how can I take a list of values, e.g.:               val = {{0, 10}, {2, 10}, {4, 4}, {5, 6}, {10, 4}};      and use `DeleteCases` to get rid of coordinates such as `{0, 10}, {2,10}, & {10,4}` (the examples in the above list) where _either_ the $x$ or $y$ component of a pair is outside of the specified upper and lower bounds for acceptable values? Is `DeleteCases` an appropriate tool for large arrays?


title: Filling between parametric plots

text: I am new with Mathematica, but am trying to fill an area between two parametric plots               ParametricPlot[{{u + Sin[u], -Cos[u]}, {u + Sin[u + Pi], Cos[u + Pi]}},      {u, 0, Pi}, Axes -> True ]      which thus far are nice, clean curves: ![1](http://www.mat.univie.ac.at/~stuhlmeier/Trochoid.png) Thanks to the answers here: How do I fill in a circle made by ParametricPlot with one solid color? I became aware of `ListLinePlot`. However, my `ListLinePlot` for this situation               ListLinePlot[Table[{{u + Sin[u], -Cos[u]}, {u + Sin[u + Pi], Cos[u + Pi]}},     {u, 0, Pi, 0.0005}], Mesh -> All,      MeshStyle -> Directive[AbsolutePointSize[0.0005], Black],      PlotStyle -> Directive[Thin, LightGray]]      ![2](http://www.mat.univie.ac.at/~stuhlmeier/Filled_Trochoid.png) does not seem to give as good a resolution no matter how finely I subdivide the interval, and also produces problems with self-intersection near the boundaries when plotting several periods. In particular, the contrast with similar curves filled in `Plot` is striking. Is there a smarter way to fill the area between these parametric curves? Perhaps using something else than `ListLinePlot`? Thanks!


title: Calculating derivatives of roots of equation

text: I am interested in calculating how the roots of an equation change as one of the variables does, when the equation is evaluated numerically rather than symbolically. I have edited this code to be simpler than the original one.               Remove["Global`*"]     d = 1/1000; mig = 1/500; kappa = 1/10;     N1[x_] = 50*(1 + 17/100*x - mig);     Estar[x_] = (d)/(kappa*mig*N1[x]);     lambda[x_] = mig*N1[x]*(1 - Estar[x]);     I1star[x_] = kappa*Estar[x]*(1 - Estar[x])*mig*N1[x]/d;     M1[q_, t_, z_] = Sum[z^(n)*d*E^(-t*d)*E^(-N1[q]*mig*t)*(N1[q]*mig)^n*t^n/n!, {n, 0,      Infinity}];     Part1[q_, z_] := NIntegrate[M1[q, t, z], {t, 0, Infinity}]     RootFcn[q_, z_] := (1 - Estar[1]) + Estar[1]*((1 - kappa) + kappa*Part1[q, z]) - z      The question I'm interested in is how the solutions for z of (RootFcn[q,z]=0) change as q increases at the point q=1. There are two roots, 1 and a value between 0 and 1; the smaller value is the one that I'm interested in. If one uses Integrate in the above instead of NIntegrate, they can simply take the solution of Solve[RootFcn[q, z] == 0, z], and use D[] to get the derivative where q=1 (which yields -0.00124613). However unfortunately in my actual problem this is not possible to do as it's more complicated and cannot be evaluated symbolically; and NIntegrate must be used. Also I cannot use the definition of a derivative (Solving for RootFcn at arbitrarily close values and divide by some epsilon), because in my problem it is too time-consuming due to the very high precision required to get a reasonable answer. So each time I numerically evaluate Solve[RootFcn[q, z] == 0, z] it takes a few minutes but since I will have to solve an equivalent problem to this derivative question thousands of times, this is prohibitive. It seems like this is probably possible using numerical derivatives, but I'm not sure. Any help would be very appreciated.


title: Mathematica output doesn't work as input

text: Sometimes when I do, for example, a series expansion Mathematica gives me output that it won't take as input. For example if I do a series expansion:               Series[Hypergeometric2F1[a,x,y,z], {a,0,0} ]      produces:               Out[xx]= 1+ a Hypergeometric2F1^(1,0,0,0)[0,x,y,z] + O[a]^2      If I literally then click on this cell and evaluate it as input, or alternatively cut and paste this term into another input line and evaluate it returns the following error:               Syntax::sntxf: "(" cannot be followed by "1,0,0,0)".          Syntax::sntxi: Incomplete expression; more input is needed .      So it doesn't seem to like the exact form as input that it just gave me as output. What gives? EDITS: 1) I apologize for the formatting errors in the posting and the confusion that resulted, that should be fixed now. Thank you to those that pointed them out. 2) I have tried the suggestions to use `InputForm[%]`-the thing this, the expressions I am dealing with are very long, and when I put it into input-form they become unwieldy. I would prefer a way to retain the standard-form expression and manipulate that - but this might be impossible (it seems like it is impossible). Thanks for the help so far anyway.


title: symbolic solution for a system of nonlinear equations in mathematica

text: Would appreciate any help on the following in mathematica I cant figure it out. I have a system of equations that I am trying to solve symbolically. I have 9 equations and 8 unknowns (I have also tried a version of this with 6 equations and 6 unknowns with same result :(   Note this is after I had quit all applications and had mathematica running alone for about 20hours.   _No more memory available. Mathematica kernel has shut down. Try quitting other applications and then retry._ Below I am showing the version with 6eqns and 6 unknowns               (*setting these to reduce equations to 6 equations and 6 unknowns*)     Subscript[b, 11] = 1;     Subscript[b, 21] = 0;          y11 = (Subscript[a, 11] *Subscript[b, 11]) - (Subscript[a, 21]*       Subscript[b, 21]) ;     y21 = (Subscript[a, 21] *Subscript[b, 11]) + (Subscript[a, 11]*       Subscript[b, 21]);          y13 = ((Subscript[K, 1 R]*Subscript[a, 11]) *     \!\(\*SubsuperscriptBox[\(b\), \(11\), \(3\)]\)) + (Subscript[a, 11]       Subscript[b, 13]) - ((Subscript[K, 1 L]*Subscript[a, 21])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) *Subscript[b,       21]) + ((Subscript[K, 1 R]*Subscript[a, 11])* Subscript[b, 11]      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) - ((Subscript[K,         1 L]*Subscript[a, 21])*      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(3\)]\)) - (Subscript[a, 21]       Subscript[b, 23]);     y23 = ((Subscript[K, 1 L]*Subscript[a, 21])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(3\)]\)) + (Subscript[a, 21]       Subscript[b, 13]) + ((Subscript[K, 1 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) Subscript[b,       21]) + ((Subscript[K, 1 L]*Subscript[a, 21])* Subscript[b, 11]      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) + ((Subscript[K,         1 R]*Subscript[a, 11]) *     \!\(\*SubsuperscriptBox[\(b\), \(21\), \(3\)]\)) + (Subscript[a, 11]       Subscript[b, 23]);          y15 = ((Subscript[K, 2 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(5\)]\)) + (3 *(Subscript[K,         1 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) Subscript[b,       13]) + (Subscript[a, 11] Subscript[b,       15]) - ((Subscript[K, 2 L]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(4\)]\) Subscript[b,       21]) - (2 *(Subscript[K, 1 L]*Subscript[a, 21])* Subscript[b, 11]       Subscript[b, 13] Subscript[b,       21]) + (2 *(Subscript[K, 2 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(3\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) + ((Subscript[K,         1 R]*Subscript[a, 11])* Subscript[b, 13]      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) - (2 *(Subscript[K,         2 L]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(3\)]\)) + ((Subscript[K,         2 R]*Subscript[a, 11])* Subscript[b, 11]      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(4\)]\)) - ((Subscript[K,         2 L]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(5\)]\)) - ((Subscript[K,         1 L]*Subscript[a, 21])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) Subscript[b,       23]) - (2 *(Subscript[K, 1 R]*Subscript[a, 11])* Subscript[b, 11]       Subscript[b, 21] Subscript[b,       23]) + ((Subscript[K, 1 L]*Subscript[a, 21])*      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\) Subscript[b,       23]) - (Subscript[a, 21] Subscript[b, 25]);     y25 = ((Subscript[K, 2 L]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(5\)]\)) + (3* (Subscript[K,         1 L]*Subscript[a, 21])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) Subscript[b,       13]) + (Subscript[a, 21] Subscript[b,       15]) + ((Subscript[K, 2 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(4\)]\) Subscript[b,       21]) + (2 * (Subscript[K, 1 R]*Subscript[a, 11])* Subscript[b,       11] Subscript[b, 13] Subscript[b,       21]) - (2*(Subscript[K, 2 L]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(3\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) + ((Subscript[K,         1 L]*Subscript[a, 21])* Subscript[b, 13]      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) + (2  *(Subscript[K,         2 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(3\)]\)) + ((Subscript[K,         2 L]*Subscript[a, 11])* Subscript[b, 11]      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(4\)]\)) + ((Subscript[K,         2 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(5\)]\)) - ((Subscript[K,         2 L]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(5\)]\)) + ((Subscript[K,         1 R]*Subscript[a, 11])*     \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) Subscript[b,       23]) - (2 * (Subscript[K, 1 L]*Subscript[a, 21])* Subscript[b,       11] Subscript[b, 21] Subscript[b,       23]) - ((Subscript[K, 1 R]*Subscript[a, 11])*      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\) Subscript[b,       23]) + (Subscript[a, 11] Subscript[b, 25]);          h11 = A1*y11 + ((3/4)*(A1)^3*y13) + ((5/8)*(A1)^5*y15) +      I*(A1*y21 + ((3/4)*(A1)^3*y23) + ((5/8)*(A1)^5*y25));          h31 = ((A1^3)/4)*y13 + ((5/16)*(A1)^5*y15) +      I*(((A1^3)/4)*y23 + ((5/16)*(A1)^5*y25));          h51 = ((A1^5)/16)*y15 + I*((A1^5/16)*y25);          h12 = A2*y11 + ((3/4)*(A2)^3*y13) + ((5/8)*(A2)^5*y15) +      I*(A2*y21 + ((3/4)*(A2)^3*y23) + ((5/8)*(A2)^5*y25));          h32 = ((A2^3)/4)*y13 + ((5/16)*(A2)^5*y15) +      I*(((A2^3)/4)*y23 + ((5/16)*(A2)^5*y25));          h52 = ((A2^5)/16)*y15 + I*((A2^5/16)*y25);               h11g = Expand[(A1*         y11 + ((3/4)*(A1)^3*y13) + ((5/8)*(A1)^5*y15))^2 + (A1*         y21 + ((3/4)*(A1)^3*y23) + ((5/8)*(A1)^5*y25))^2];     h12g = Expand[(A2*         y11 + ((3/4)*(A2)^3*y13) + ((5/8)*(A2)^5*y15))^2 + (A2*         y21 + ((3/4)*(A2)^3*y23) + ((5/8)*(A2)^5*y25))^2];     h31g = Expand[(((A1^3)/4)*         y13 + ((5/16)*(A1)^5*y15))^2 + (((A1^3)/4)*         y23 + ((5/16)*(A1)^5*y25))^2];     h32g = Expand[(((A2^3)/4)*         y13 + ((5/16)*(A2)^5*y15))^2 + (((A2^3)/4)*         y23 + ((5/16)*(A2)^5*y25))^2];     h51g = Expand[(((A1^5)/16)*y15)^2 + ((A1^5/16)*y25)^2];     h52g = Expand[(((A2^5)/16)*y15)^2 + ((A2^5/16)*y25)^2];               Solve[{h11g - (A1^2      \!\(\*SubsuperscriptBox[\(a\), \(11\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) + A1^2      \!\(\*SubsuperscriptBox[\(a\), \(21\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) + A1^2      \!\(\*SubsuperscriptBox[\(a\), \(11\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\) + A1^2      \!\(\*SubsuperscriptBox[\(a\), \(21\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) == 0,     h12g - (A1^2      \!\(\*SubsuperscriptBox[\(a\), \(11\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) + A1^2      \!\(\*SubsuperscriptBox[\(a\), \(21\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(11\), \(2\)]\) + A1^2      \!\(\*SubsuperscriptBox[\(a\), \(11\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\) + A1^2      \!\(\*SubsuperscriptBox[\(a\), \(21\), \(2\)]\)      \!\(\*SubsuperscriptBox[\(b\), \(21\), \(2\)]\)) == 0,     h31g == 0, h32g == 0, h51g == 0, h52g == 0}, {Subscript[a,      11], Subscript[a, 21], Subscript[b, 13], Subscript[b, 23],      Subscript[b, 15], Subscript[b, 25]}]


title: What is the proper method to load a Mathematica package inside a DynamicModule

text: I have a `DynamicModule` that requires loading of Mathematica packages. The usual methods do not seem to apply (`Needs["MathematicaPackage`"]]`, etc) I've tried               Dynamic[Initialization :> (Needs["Package`"])];      with only partial success. I'm sure this is done regularly, but cannot find any MMA documentation to that effect.   What's the best way to load Mathematica packages in `Dynamic` or `DynamicModule` and `Manipulate`?


title: Issue with the NDSolve code

text: With this procedure, one may determine an eigen-value function $R(a)$ for any given $\Xi$ (say 0, 25, 50, 75, 100)               g[eta1_, eta3_, R_, a_, Xi_] := {f[1], h[1], q[1]} /.          NDSolve[{D[f[x], {x, 2}] - a^2 f[x] + a (h[x] + R q[x]) == 0,         D[h[x], { x, 2}] - a^2 h[x] + a Xi x f[x] == 0,         D[q[x], {x, 2}] - a^2 q[x] + a f[x] == 0,          f[0] == 0,     f'[0] == 1,     h[0] == eta1,     h'[0] == 0,      q[0] == 0,     q'[0] == eta3      }, {f, h, q}, {x, 0, 1}]     s[a_, Xi_] :=FindRoot[g[eta1, eta3, R, a, Xi], {{R, 0}, {eta1, 0}, {eta3, 0}},        MaxIterations -> 100000]      where the condition $f'(0) = 1$ is a normalisation condition. But the problem is that the code doesn't converge always. The output I am looking for is like this ![enter image description here](http://i.stack.imgur.com/wiBv8.png) Thanks


title: How to identify chemical substance from tattoo?

text: A friend of mine made a tattoo on his chest of some chemical substance formula. He challenged us to identify which substance is that. I thought that perhaps a combination of:   * Mathematica image processing capabilities   * Wolfram|Alpha chemical data   * Manual intervention could do the trick. Here is the picture: ![enter image description here](http://i.stack.imgur.com/SDZGa.png) I am looking for pointers on how to attack the problem (like keywords of Mathematica functions, etc). **EDIT 1** : I suppose the following need to be done:   * Extract the formula from the picture as basic (2D) structure diagram   * Define a distance metric for images or use existing one (e.g., `ImageDistance[]`)   * Calculate the distance of our element's diagram against all `ChemicalData[]` elements   * Pick the few first and do a visual verification At the moment 1st step seems like the most challenging. **EDIT 2** : As shown by Sjoerd it is much easier to search for a formula as string rather than as image!


title: Simplifying expressions involving Sum

text: I am trying to use _Mathematica_ to simplify a symbolic expression involving `Sum`. Particularly, I define a sum via               y = (x - x0)^α Sum[a[n] (x - x0)^n, {n, 0, Infinity}]      Then I take the derivative of `y` with respect to `x` and simplify via               FullSimplify[D[y, x]]      This yields $$(x-\text{x0})^{\alpha -1} \left(\alpha \sum _{n=0}^{\infty } a(n) (x-\text{x0})^n+(x-\text{x0}) \sum _{n=0}^{\infty } n a(n) (x-\text{x0})^{n-1}\right)$$ However, the expression above can be easily simplified further to $$(x-\text{x0})^{\alpha -1} \sum _{n=0}^{\infty } ( a(n) (x-\text{x0})^n(\alpha+n) ) $$ Is there a way to "make" _Mathematica_ recognise this simplification? I presume the problem has something to do with the fact that I use the unknown function `a[n]` in the expression, but I am not sure what can I do about it to get similar functionality. I am quite new to _Mathematica_. Apologies if this is a trivial question.


title: how to load everything when opening a saved notebook

text: generally, when I carry over work in a notebook from the previous day, I have to physically start from the top and re-evaluate every statement before I can begin from where i left off. Is there any setting I can enable so that the notebook will be in state when it becomes active? Thanks, Sid.


title: Format and TeXForm does not work as expected

text: Recently, we had a nice question which brought up an issue that I believe is a bug. In the tutorial Defining Output Formats is an example at the end which doesn't make sense > This specifies the `TeXForm` for the symbol `x`. >   >   >     Format[x, TeXForm] := "{\\bf x}" >   > > The output format for `x` that you specified is now used whenever the TeX > form is needed. >   >   >     TeXForm[1 + x^2] >     (* x^2+1 *) >   The given output is wrong and should instead be something like `{\bf x}^2+1`. Therefore, I tested this with my colleague on all versions available to us and the output below shows, that it only worked back in version 4.2. Is there a simple reason why `Format` does not work as advertised? ### Version 4.2               Format[x,TeXForm]:="{\\bf x}";     TeXForm[1+x^2]     (* 1 + {{\bf x}}^2 *)      ### Version 5.1               Format[x,TeXForm]:="{\\bf x}";     TeXForm[1+x^2]     (* x^2+1 *)      ### Version 6.0               Format[x, TeXForm] := "{\\bf x}";     TeXForm[1 + x^2]     (* x^2+1 *)      ### Version 7.0               Format[x, TeXForm] := "{\\bf x}";     TeXForm[1 + x^2]     (* x^2+1 *)      ### Version 8.0               Format[x, TeXForm] := "{\\bf x}";     TeXForm[1 + x^2]     (* x^2+1 *)      ### Version 9.0               Format[x, TeXForm] := "{\\bf x}";     TeXForm[1 + x^2]     (* x^2+1 *)


title: ListPlot with spherical coordinates with data from file

text: I have a file that is a table of values for r, $\theta$ and f(r,$\theta$) with r and $\theta$ being spherical coordinates, $\phi$ being 0 the whole time. The data thus looks like {{0.1,0.01,2},{0.1,0.02,2.1},{0.1,0.03,2.05},...} How do I plot this in a nice way? I do not want r- and $\theta$-axes but rather convert it to an xz-grid, I guess. Is there any neat way to do this? I just had the idea of converting the variables by myself typing this but also have no idea how to do that either. Any help is appreciated! So a little more thinking solved the problem: I read the data, create an empty array of the same size and transform coordinates by hand.               datalist = ReadList["file.dat", Number, RecordLists -> True];     data2 = Array[0, {Length[datalist], 3}];          For[i = 1, i < Length[datalist], i++,       For[j = 1, j <= 3, j++,        If[j == 1, data2[[i, j]] = datalist[[i, 1]]*Sin[datalist[[i, 2]]]];        If[j == 2, data2[[i, j]] = datalist[[i, 1]]*Cos[datalist[[i, 2]]]];        If[j == 3, data2[[i, j]] = datalist[[i, j]]]      ]     ]          ListPlot3D[data2]`      Not sure if this is the most elegant way but it worked. Thanks for the input and next time I will do my best to state the problem more clearly ;)


title: How to insert elements of a list into list of lists?

text: I have two lists. E.g.               l1 = {{{t1, d11}, {t2, d12}, {t3, d13}},            {{t1, d21}, {t2, d22}, {t3, d23}},            {{t1, d31}, {t2, d32}, {t3, d33}},            {{t1, d41}, {t2, d42}, {t3, d43}}};          l2 = {p1, p2, p3, p4};      I would like to generate a list like res.               l22 = Table[l2[[i]], {i, 1, Length[l2]}, {Length[l1]}];          res = Table[Riffle[l1[[i, j]], l22[[i]], 3], {i, 1, 4}, {j, 1, 3}]      > >     {{{t1, d11, p1}, {t2, d12, p1}, {t3, d13, p1}}, >     {{t1, d21, p2}, {t2, d22, p2}, {t3, d23, p2}}, >     {{t1, d31, p3}, {t2, d32, p3}, {t3, d33, p3}}, >     {{t1, d41, p4}, {t2, d42, p4}, {t3, d43, p4}}} >   It would be nice to have a code in one step and without counting the length of the list. I have seen similar manipulations with `Append` or `Join`, but I could not combined with mapping to get the right structure.


title: How to remove quotation marks from a generic InputField

text: I need to use an InputField with a generic dynamic variable (not restricted to be Number or String or whatsever) and I don't want to see the quotation marks in the case the input is a string. Here is an example               z="";     InputField[Dynamic[z]]      I know the Cell's option ShowStringCharacter but here doesn't work, for instance see               z = "";     Panel[Column[{Style[InputField[Dynamic[z]],          ShowStringCharacters -> False], Spacer[5],         Row[{"This is the value of variable z", Spacer[5], Dynamic[z]}]}]]      and this one               z = "";     ExpressionCell[      Panel[Column[{Style[InputField[Dynamic[z]],           ShowStringCharacters -> False], Spacer[5],          Row[{"This is the value of variable z", Spacer[5],            Dynamic[z]}]}]], ShowStringCharacters -> False]      Any suggestion? Thanks in advace, Roberto


title: GraphPlot not working properly

text: The code               e = {{Subscript["E",1,2],Subscript["E",2,3]} -> {Subscript["E",1,3]}};     v = {{Subscript["E",1,2]}, {Subscript["E",1,3]}, {Subscript["E",         2,3]}, {Subscript["E",1,2], Subscript["E",2,3]}};     GraphPlot[Join[e, #->#& /@ v], VertexLabeling->True,       EdgeLabeling->False, DirectedEdges->True, SelfLoopStyle->False,      VertexCoordinateRules -> ((#->{Length[#],Automatic})& /@ v)]      produces ![enter image description here](http://i.stack.imgur.com/1MzVq.jpg), but clearly my input also specifies a vertex $\\{E_{1,2}\\}$. Where is it?


title: How to determine coordinates of a shape in an image?

text: I have a pre-processed image, from which I have to get coordinates of some components. ![sample image](http://i.stack.imgur.com/xg4lA.png) There are 7 green components (pigs actually) that I have already isolated from an angry bird screen shot. So what I want is to locate those six components on the image. I tried               ImageValuePositions[u, RGBColor[1, 0, 0], .1]     { Mean[#1], Mean[#2]}& @@@ Transpose /@ FindClusters[%];     LocatorPane[ %, sample image]      But it doesn't work at all. Could anyone help me out? ![sample2](http://i.stack.imgur.com/ZZyLq.png) How should I figure this out?


title: Formatting plot of symmetric points differently to asymmetric points

text: From an array of numbers, I would like to determine (and then colour appropriately) which points are symmetric about a given axis (here, $x = 1/2$), and which are not. For example, form this:               ListPlot[{{1.5,1.5},{1,1},{1.5,-0.5},{-0.5,-0.5},{-0.5,1},{-0.5,1.5}},      PlotStyle -> Red]      I would like to achieve this:               Plot[{0}, {x, -2, 2}, PlotRange -> {-2, 2}, Epilog ->      {PointSize[Medium], Red,Point[{{{1.5, 1.5}, {-0.5, 1.5}, {1.5, -0.5}, {-0.5, -0.5}}}],     PointSize[Medium], Blue, Point[{{-0.5, 1}, {1, 1}}]}]      (Please excuse the clumsiness with which I code: I am very new to _Mathematica_.) I have looked at `Symmetric` in Wolfram Documentation, but it doesn't seem to cover this. I don't know of a method for selecting certain arrays and formatting them with one colour, then selecting a different set and formatting that with another colour, other than by doing it manually. Is there a way of automating this process? (My goal is to do this for arrays of over `1000` points, so sorting manually is not really an option!) # Update2 Data: array link # Update3 @Kuba, Using the code you provided in answer to my other post:               sol = Solve[N[Table[BernoulliB[n, z], {n, 1000, 1000}] == 0]];      would it be possible to find symmetric points? (And also format the plot: `AspectRatio -> Automatic, Plot Axis @ x = 1/2`, etc.?) # Update4 Note: So as not to mislead, I have included a corrected plot. The strange pattern produced without precision adjustment: ![enter image description here](http://i.stack.imgur.com/G3f5k.gif) is purely caused by numerical error (thanks to Antonio Vargas for pointing this out) - the corrected plot for n = 171 (n = 1000 is too much for my machine!), calculated to greater precision, looks like this: ![enter image description here](http://i.stack.imgur.com/DcbGs.gif) Plotted using Kuba's code:               sol = Solve[N[Table[BernoulliB[n, z], {n, 171, 171}] == 0, 50]];     point[x_?VectorQ] := {PointSize@.01, Red, Point[x]}     point[x : (_?VectorQ ..)] := {PointSize@.01, Blue, Point /@ {x}}     axis = 1/2;     point @@@ GatherBy[{Re@z, Im@z} /. sol,(*Round added*)     Round[{Abs[#[[1]] - axis], #[[2]]}, 0.001] &] //      Graphics[#, Frame -> True, GridLines -> {{axis}, None}] &


title: How can I add a tangent arrow at a certain point of a curve in a LogPlot?

text: How can I add an arrow at a certain point of a curve with the direction of the arrow tangential to that point? (Line are not straight in a log-plot.)               LogPlot[(1 - τ)^(-0.5),      {τ, 0, 1}, PlotRange -> {{0, 1}, {0.66, 20}},      Frame -> {{True, True}, {True, False}},      ImageSize -> 600,      PlotStyle -> {Directive[Black, Thick]},      BaseStyle -> {FontSize -> 30},      RotateLabel -> False,      AspectRatio -> 1      ]      ![enter image description here](http://i.stack.imgur.com/MAuZq.png)


title: BezierCurve in EdgeShapeFunction fails when used on multiedges graph

text: I would like to create a network graph with curved edges. To do this, I wrote this function:               edgeFun[pts_, e_] := Module[{controlPts},          controlPts = pts /. {a_, b_} :> {a, {a[[1]] + .1 b[[1]], a[[2]]},                                              {a[[1]] + 0.1 b[[1]], b[[2]]}, b};            BezierCurve[controlPts]     ];      With no multiedges the `edgeFun` function works fine:               pts = {1 -> 2, 2 -> 3, 3 -> 1};     Graph[pts, VertexLabels -> Placed["Name", Center], EdgeShapeFunction -> edgeFun]      ![Mathematica graphics](http://i.stack.imgur.com/NL3rJ.png) But when I want to create a network with multiple edges (note `1 -> 2` and `2 -> 1`, _Mathematica_ complains and the graph is pinked out:               pts1 = {1 -> 2, 2 -> 3, 3 -> 1, 2 -> 1};     Graph[pts1, VertexLabels -> Placed["Name", Center], EdgeShapeFunction -> edgeFun]      > >     Part::partd: "Part specification 0.496922[[1]] is longer than depth of > object" >   Does anyone know how to solve this problem?


title: Filtering elements from a list

text: Suppose that I have a list               {{{2, 1}, {4, 3}, {2, 4}}, {{2, 1}, {4, 3}, {3, 1}},      {{2, 1}, {2, 4}, {3, 1}}, {{4, 3}, {2, 4}, {1, 2}}}      I want to make a new list that only contains the entries for which the first component of each pair does not repeat itself. So for example, the element               {{2, 1}, {4, 3}, {2, 4}}      would be eliminated since `2` appears in the first component of both `{2,1}` and `{2,4}`. Likewise, `{{2, 1}, {2, 4}, {3, 1}}` will also be eliminated. Is there a simple condition I can use with the `Select` function to do this? Thanks in advance.


title: Standard errors for maximum likelihood estimates in FindDistributionParameters

text: I am trying to fit a non-standard PDF to data and `FindDistributionParameters` works great, and gives me the parameters of the distribution back using maximum likelihood, but I cannot find a way to get Mathematica to spit out the standard errors (or confidence intervals) for those estimated parameters. Anyone knows how to do it, or should I just go to a different program, i.e. MATLAB?


title: Swap two entries in a matrix

text: Is there a nice, simple script one can use to swap two entires in a matrix? For example, suppose we have the matrix below: $A=\begin{pmatrix}2 & 4 & 1\\\ 3 & 1 & 2\\\ 4 & 3 & 1 \end{pmatrix}$ Is there a script of the form `switch[A,a,b]`, which will swap all occurrences of $a$ in the matrix with $b$, and vice versa, and then update the matrix $A$ accordingly? So in this case the output of `switch[A,2,3]` would be: $A=\begin{pmatrix}3 & 4 & 1\\\ 2 & 1 & 3\\\ 4 & 2 & 1 \end{pmatrix}$ My own solution involves a lot of `If` and `For` functions, and will, I think, also run into the problems detailed here. I think it will work eventually (and I'd be happy to post what I have so far if people would like), but really I'm just wondering whether there's a simpler way to do this. Thanks!


title: How can I rationalize the denominator of an expression?

text: _Mathematica_ doesn't rationalize the denominator automatically, and I haven't found anything in the documentation about it. But I found an old post on MathGroup, which proposes a solution using `ComplexityFunction`. In very simple cases, it works fine, but it fails in more complex cases. Is there a better way to do it?


title: Distinguishing slots in a function mapping Position across a list

text: Suppose that I have a list `myList` that has more than one level. Here is an example of such a "data structure":               myList = {{10, "c"}, {20, "a"}, {30, "b"}};      Now suppose that I have a list of characters, called `charList`:               charList = {"a", "b", "c"};      I want to use `Position` to find the positions of the `charList` characters in `myList`. Of course, I can do this manually -- by calling `Position` for each character in `charList`:               Position[myList, _?(#[[2]] == "a" &), {1}, Heads -> False]     Position[myList, _?(#[[2]] == "b" &), {1}, Heads -> False]     Position[myList, _?(#[[2]] == "c" &), {1}, Heads -> False]      > {{2}} > > {{3}} > > {{1}} And, of course, I can shorten this process by using `Table` to call `Position` repeatedly:               Table[      Position[myList, _?(#[[2]] == charList[[i]] &), {1}, Heads -> False],      {i, 1, Length[charList]}]      > {{{2}}, {{3}}, {{1}}} But, is it possible to shorten the code even more by using `Map`? (I often find `Map` more convenient and easier to read than `Table`.) My initial thought was to do something like this:               Map[      Position[myList, _?(#[[2]] == # &), {1}, Heads -> False] &,     charList]      but I get undesired output: > {{}, {}, {}} I think that I have failed to distinguish between the two different `#` slots, which refer to two different things (they refer to different `&`s). How can I distinguish the two `#` so that I can `Map` `Position` across `charList`?


title: Fastest way to create a NxNxNxN dimensional matrix

text: I have a function that outputs a complex number               Func[x_,y_]:= blah blah;      I have constructed a table of all possible values of this function.               Bar = Table[Func[x,y],{x,1,N},{y,1,N}];      I do this so it can be faster accessed in the next step. I need to compute the following matrix/table of all possible values of two of these functions multiplied by each other.               result = Table[Bar[[x,z]] Bar[[y,w]], {x,1,N}, {y,1,N}, {w,1,N}, {z,1,N}];      And this actually takes quite some time, because this table would have around `150^4` entries for `N=150`. How can I speed this up? It currently takes around 1 hour using `ParallelTable`. What is the fastest way to make a table of this size and store it to memory to be accessed in a calculation? EDIT: `Bar` has the following symmetry:               Bar[[x,y]] = Bar[[y,x]]


title: Thread a function over a list and with a non-atomic 2nd parameter?

text: From the documentation, Thread's behavior on functions where the first parameter is a List and the second is an atomic expression, is this:               Thread[f[{a, b, c}, x]]           (* {f[a, x], f[b, x], f[c, x]} *)      If the second argument of 'f' is not atomic, it is possible to thread over its first argument {a,b,c} while treating the 2nd argument as if it were atomic? For example, consider:               M = Table[i + j, {i, 1, 3}, {j, 1, 2}]          (* {{2, 3}, {3, 4}, {4, 5}} *)      Then,               Thread[f[{a, b, c}, M]]          (* {f[a, {2, 3}], f[b, {3, 4}], f[c, {4, 5}]} *)      This is understandable because M is not atomic so For example:               g[p_, M_ /; Dimensions[M] == {3, 2}] := {p, M}      Threading over `g` Doesn't work as intended:               Thread[g[{a, b, c}, M]]          (* {{a, {2, 3}}, {b, {3, 4}}, {c, {4, 5}}} *)      Worse still, the result above is due to a coincidence: Length@M==3. If this is not the case, Thread returns an error:               Thread::tdlen: Objects of unequal length in f[{a,b,c},{{2,3,4,5},{3,4,5,6}}] cannot be combined. >>      I've also considered wrapping M in some variation of Hold, but none yield atomic expressions. Is there a way to force Thread to treat the 2nd argument of the function as atomic? The ultimate goal is to `SetAttributes` of the function to `Listable`.


title: Help with finding solution for utility function

text: I'm brand new to Mathematica and having trouble finding a solution for Lh based on the first order condition. I'm not sure if it is something I'm doing in Mathematica or something wrong with the equations. Any suggestions?               Utility[x_] = (((x - Eta)^(1 - Theta))/(1 - Theta))     Harvest[Lh_] = (Lh)^Beta     Livestock[Nt_] = Nt*(1 + b - Delta*(T*Nt)/(L - Lh))     constraint = P*Harvest[Lh] - Alpha*Livestock[N]     Langragian = Utility[Livestock[N]] + Lambda*constraint     {FOC1 = D[Langragian, Lh],       FOC2 = D[Langragian, Lambda]}     sols = Solve[{FOC1 == 0, FOC2 == 0}, {Lh, Lambda}]


title: Calculating the Mean of a Truncated Multinormal Distribution

text: First, I'm a little disappointed that Mathematica balks at:               Mean[TruncatedDistribution[{{0, Infinity}},MultinormalDistribution[{0}, {{1}}]]]      Second, is the numerical computation of means from truncated multinormal distributions so hard? Is anyone aware of a package that implements the algorithm of Leppard and Tallis (1989) (see here for FORTRAN code) or anything like it? **Edit** : rm asked for an example that fails to compute:               Mean[TruncatedDistribution[{{0, Infinity}, {0, Infinity}},          MultinormalDistribution[{0.5, 1.5}, {{1., 0.3}, {0.3, 1.}}]]]


title: How to get a rule for, e.g., (x + y) to apply to (-x - y), etc.?

text: For example, the substitution `(x + y) -> s` fails here:               In[1]:= (-x - y) /. (x + y) -> s          Out[1]= -x - y      Of course, I could try applying the rule `(-x - y) -> -s`, but this strategy becomes unwieldy in more complicated cases. At the very least it would require duplicating a lot of rules. For example, if the expression to be transformed were something like               (x + y)^2 + 2 (-x - y)      ...then I'd need to use something like               {(x + y) -> s, (-x - y) -> -s}      Is there a better way to transform the above expression to `s^2 - 2 s`?


title: How to quickly calculate intersections of filled curves?

text: I am trying to quickly calculate the intersection of polygons with more than 6,000 points. A compiled solution would be preferable. Here is one example of the problem:               o = First[            First[ImportString[              ExportString[               Style["O", Italic, FontSize -> 24, FontFamily -> "Times"],                "PDF"], "PDF", "TextMode" -> "Outlines"]]];          p = First[        First[ImportString[          ExportString[           Style["P", Italic, FontSize -> 24, FontFamily -> "Times"],            "PDF"], "PDF", "TextMode" -> "Outlines"]]];          Graphics[{EdgeForm[Black], ColorData["Crayola", "Sunglow"], {o, p}}]      Another:                   Module[{a = FilledCurve[{{Line[{{2, 3}, {0.8125, 0.625}}],           BezierCurve[{{0.6875, 0.375}, {0.375, 0.25}, {1.125, 0.25}},             SplineDegree -> 2],            BezierCurve[{{0.8125, 0.375}, {0.9375, 0.625}}],           Line[{{1.3125, 1.375}, {2.4375, 1.375}, {2.8125, 0.625}}],           BezierCurve[{{2.9375, 0.375}, {2.625, 0.25}, {3.625, 0.25}},             SplineDegree -> 2],            BezierCurve[{{3.3125, 0.375}, {3.1875, 0.625}}]},          {Line[{{1.875, 2.5}, {1.375, 1.5}, {2.375, 1.5}}]}}]},       Graphics[Table[{EdgeForm[Black], Hue[RandomReal[]],          Translate[Rotate[Scale[a, RandomReal[5]], RandomReal[2 Pi]],           RandomReal[20, {2}]]}, {30}]]]      **So in the problem is:** how to intersect of multiple (or two at a time) polygons (with or without) holes (and with up to 6000 points in their triangulations)? I have tried using the Weiler–Atherton clipping algorithm but my implementation was too slow (anything relying on bitmaps is too slow). Perhaps there is a solution that uses LibraryLink to harness a standard library? I found one here http://www.cs.man.ac.uk/~toby/alan/software/gpc.html ## Updates It was suggested in the comments that Graphics`Mesh` be used but this is way too slow in even 100 points and doesn't handle holes:               a = Polygon@RandomReal[1, {100, 2}];     b = Polygon@RandomReal[1, {100, 2}];     AbsoluteTiming[c = Graphics`Mesh`PolygonIntersection[a, b]]     Graphics[{Blue, a, Red, b, Yellow, Polygon /@ List @@ c}]      ![enter image description here](http://i.stack.imgur.com/nernU.png) Here is a sample input polygon for the letter G:                G = Polygon[{{-0.466796, -0.0328696}, {-0.466336, 0.0186753}, {-0.463089,         0.0682893}, {-0.459379, 0.100181}, {-0.451495,         0.146241}, {-0.444693, 0.175763}, {-0.432171, 0.21827}, {-0.422278,         0.245423}, {-0.411147, 0.271628}, {-0.39878, 0.296886}, {-0.37791,         0.332996}, {-0.362451, 0.355885}, {-0.345756,         0.377826}, {-0.327823, 0.398819}, {-0.300607,         0.426707}, {-0.281598, 0.443668}, {-0.251786,         0.466663}, {-0.231046, 0.480362}, {-0.198638,         0.498465}, {-0.176168, 0.508902}, {-0.141165,         0.522112}, {-0.116964, 0.529288}, {-0.0793649,         0.537605}, {-0.0534337, 0.541519}, {-0.013239,         0.544944}, {0.0144228, 0.545596}, {0.0521431,         0.544603}, {0.0973423, 0.540566}, {0.140374, 0.533423}, {0.181237,         0.523175}, {0.212366, 0.512741}, {0.249327, 0.496903}, {0.283288,         0.47845}, {0.310993, 0.459561}, {0.336333, 0.438254}, {0.359309,         0.414528}, {0.379921, 0.388384}, {0.398168, 0.359821}, {0.414052,         0.328839}, {0.427571, 0.295438}, {0.438725, 0.259618}, {0.444849,         0.234395}, {0.449921, 0.208096}, {0.309296, 0.208096}, {0.299494,         0.244597}, {0.29219, 0.264834}, {0.283819, 0.283824}, {0.267496,         0.312703}, {0.256279, 0.328367}, {0.243996, 0.342784}, {0.235215,         0.351703}, {0.221153, 0.364041}, {0.206024, 0.375133}, {0.189953,         0.385077}, {0.161346, 0.399325}, {0.14309, 0.406478}, {0.124015,         0.412584}, {0.0904026, 0.420435}, {0.0691431, 0.42375}, {0.0470644,         0.426018}, {0.00844619, 0.427471}, {-0.0284694,         0.425533}, {-0.0551123, 0.421535}, {-0.0892443,         0.412813}, {-0.121786, 0.400214}, {-0.152737,         0.383739}, {-0.182097, 0.363387}, {-0.209866,         0.339158}, {-0.235987, 0.311056}, {-0.248019,         0.295569}, {-0.259191, 0.279133}, {-0.269503,         0.261747}, {-0.278956, 0.243411}, {-0.291525,         0.214127}, {-0.298829, 0.193418}, {-0.305275,         0.171759}, {-0.313331, 0.137489}, {-0.321066,         0.0884734}, {-0.325362,         0.0356589}, {-0.32624, -0.0188127}, {-0.324105, -0.0667413}, \     {-0.319123, -0.112199}, {-0.311294, -0.155187}, {-0.300618, \     -0.195705}, {-0.294213, -0.215037}, {-0.28327, -0.242878}, \     {-0.270726, -0.269329}, {-0.25151, -0.302436}, {-0.235136, \     -0.325433}, {-0.216766, -0.346138}, {-0.196376, -0.3645}, {-0.173967, \     -0.380518}, {-0.149538, -0.394191}, {-0.123089, -0.405521}, \     {-0.104334, -0.411771}, {-0.0846818, -0.41698}, {-0.0535202, \     -0.422841}, {-0.0203389, -0.426357}, {0.0148622, -0.427529}, \     {0.0509528, -0.426065}, {0.0853497, -0.421672}, {0.118053, \     -0.414352}, {0.149062, -0.404104}, {0.171208, -0.394496}, {0.1924, \     -0.383241}, {0.212641, -0.370339}, {0.231928, -0.35579}, {0.250217, \     -0.339572}, {0.266916, -0.321406}, {0.281843, -0.301207}, {0.290811, \     -0.286611}, {0.302785, -0.263022}, {0.312987, -0.237399}, {0.321418, \     -0.209743}, {0.326054, -0.190175}, {0.331531, -0.159129}, {0.334198, \     -0.137302}, {0.336722, -0.102866}, {0.337421, -0.0787786}, {0.174296, \     -0.0787786}, {0.0111708, -0.0787786}, {0.0111708,         0.0393464}, {0.238983, 0.0393464}, {0.466796,         0.0393464}, {0.466796, -0.517529}, {0.377235, -0.517529}, \     {0.343661, -0.386923}, {0.320697, -0.411362}, {0.294314, -0.43722}, \     {0.26921, -0.459296}, {0.245385, -0.477589}, {0.222841, -0.492099}, \     {0.200503, -0.503935}, {0.174026, -0.515381}, {0.145794, -0.524995}, \     {0.108033, -0.534437}, {0.0758485, -0.539931}, {0.0331483, \     -0.544223}, {-0.0029876, -0.545596}, {-0.0362581, -0.545124}, \     {-0.0713561, -0.542341}, {-0.10544, -0.537172}, {-0.138509, \     -0.529619}, {-0.170564, -0.51968}, {-0.191371, -0.511729}, \     {-0.211727, -0.502717}, {-0.231632, -0.492646}, {-0.260644, \     -0.475551}, {-0.279422, -0.462829}, {-0.29775, -0.449047}, \     {-0.315626, -0.434205}, {-0.324396, -0.426386}, {-0.34277, \     -0.405934}, {-0.367955, -0.373398}, {-0.390289, -0.338633}, \     {-0.403595, -0.314218}, {-0.415633, -0.288813}, {-0.426404, \     -0.262417}, {-0.440185, -0.220965}, {-0.447788, -0.192092}, \     {-0.456817, -0.146926}, {-0.461252, -0.115577}, {-0.465529, \     -0.0666954}, {-0.466796, -0.0328696}}];


title: How can I remove a style from the list of available styles?

text: I have a stylesheet that has inherited some base definitions from another, but would like to "prune" the list of available styles, by removing or disabling1 some. Is there a way to do this? * * * 1\. This is not a question about how to _delete_ I style I've defined from my stylesheet, but how to _disable_ a style that my stylesheet has inherited.


title: Is there a way to base one style on another?

text: I'm setting up a stylesheet and and finding the process of defining related styles tedious and error prone. In particular, I have several related styles that need to have synchronized settings (e.g., such as "DisplayFormula" and "DisplayFormulaNumbered"). Is there a way to base one style on another, or perhaps simply to copy or duplicate an existing style as the starting point for another?


title: Execute code when file is modified

text: I have a function the takes some time to complete. The function imports data from a .csv, parses it, and plots certain vectors from there. The .csv is constantly being updated from an external program. Ideally, the file size of the .csv would be monitored and when it changes the function is run. Here's what I have so far (assuming the described function is `f`).               file = "testfile.csv"     Dynamic[         Refresh[          filesize:=FileByteCount[file];          data = Import[file, "CSV"];          f[data],TrackedSymbols:>{filesize},UpdateInterval->5]]      This works, but seems to run `f` every 5 seconds no matter if the file size has changed or not. This doesn't seem to be very efficient. Also, if I try to use inside `DynamicModule` it doesn't work at all. So, what's the best way to monitor and execute code on a file change?


title: Graph rendering not working as expected

text: I'm running the older Mathematica v6 which seems to go through the edges of graphs twice. Is this a bug? Is it fixed on the latest version? Please just try this command:               GraphPlot[{1 -> 2, 2 -> 3, 3 -> 1},       EdgeRenderingFunction -> (If[True, Print["e ", ##]; Black] &),       VertexRenderingFunction -> (If[True, Print["v ", ##]; Black] &)]                    v {0.496926,0.867793}11     e {{0.496926,0.867793},{0.999994,0.00354563}}{1,2}None{1,2}     e {{0.999994,0.00354563},{0.,0.}}{2,3}None{2,3}     e {{0.,0.},{0.496926,0.867793}}{3,1}None{3,1}     e {{0.496926,0.867793},{0.999994,0.00354563}}{1,2}None{1,2}     e {{0.999994,0.00354563},{0.,0.}}{2,3}None{2,3}     e {{0.,0.},{0.496926,0.867793}}{3,1}None{3,1}     v {0.496926,0.867793}11     v {0.999994,0.00354563}22     v {0.,0.}33


title: Package for voting systems

text: Is there a mathematica package that implements common voting systems (like IRV where voters will rank the candidates)?


title: Create triangular mesh from random list of points

text: I have a list of points. I would like to take these points and create a mesh of triangles from them, making sure triangles don't overlap. So here's a list of points:               p0 = Transpose[{RandomReal[{0, 10}, {100}], RandomReal[{0, 12}, {100}]}];     ListPlot@p0      ![enter image description here](http://i.stack.imgur.com/wJmc8.png) Now I've managed to take the first point in the list, find its two nearest neighbours and construct a triangle from this:               Graphics[{Thick, Red, Line[Append[Nearest[p0, p0[[1, All]], 3], p0[[1, All]]]]}]      ![enter image description here](http://i.stack.imgur.com/QVylR.png) What I'd not like to do is from this starting point keep connecting points to make a mesh where all the triangle corners are at one of the points and no triangles overlap. Any suggestions on how to do this? \-- _Below may be irrelevant_ \-- I imagine `DelaunayTriangulation` might come into this, however I'm not sure how. Also when I run it I don't understand what it returns:               DelaunayTriangulation[p0] // MatrixForm      ![image](http://i.stack.imgur.com/nKvTt.png)


title: Generating a "flare" effect in Graphics3D?

text: I'm attempting to indicate that there is a point-source of light at some position in a Graphics3D-generated image. Is there any built-in tool to do this? My patch-work solution thus far has been to imagine a sphere of radius $r$ centered at that point, and to generate a large set of diameter-length chords inside of the sphere. Surely there must be a better way that doesn't involve creating so many line or cylinder primitives?


title: Speed of convergence for NIntegrate

text: I'm trying to optimise numerically a function that entails computing the expected value of a truncated trivariate normal distribution and this is taking extremely long -I also get warned about `NIntegrate::slwcon` I've seen posts (such as this) about rewriting the problem as a differential equation, however I couldn't rewrite the problem successfully. Here's a simplified version of my problem (focusing on the expectation, which is what slows down the optimisation and produces `NIntegrate::slwcon` ):               JointD[X_,Y_,Z_]:= PDF[MultinormalDistribution[       {0,0,0}, {{1, 0.5, 0.5}, {0.5, 1, 0.5}, {0.5, 0.5, 1}}], {X,Y,Z}]          NIntegrate[X*JointD[X,Y,Z],{X, -∞, ∞}, {Y, 1, ∞}, {Z, 2, ∞}]


title: How do I define functions in TraditionalForm?

text: I'd like to be able to define functions (at least simple ones that _Mathematica_ can otherwise understand) using `TraditionalForm`; but this seems to require the use of an underscore. For example, I'd like to be able to have something like $$f(x) = x^2$$ correspond to               f[x_]:=x^2      but _Mathematica_ seems to require $$f(x\text{_}) = x^2$$ which goes a long way towards defeating the whole purpose. Is there, perhaps, a way to define some formatting that's less obtrusive, and more "conventionally notational" than the underscore that could correspond to the `TraditionalForm` underscore (and thus resolve any ambiguities)?


title: Why do I have to install my stylesheet each time I make changes to it?

text: I gather that it should be possible to preserve changes to a stylesheet by simply saving it, but this is not the behavior I'm getting with a stylesheet I've "installed" using the "Install Stylesheet..." button. In order to get any changes I've made to my stylesheet to persist, I need to install the stylesheet again. My saves (I have `Saveable` enabled for the stylesheet) seem to have no effect (the change indicator, doesn't even go away when I "save" it). Do "installed" stylesheets behave differently? Is my opened version of the stylesheet being saved somewhere else, perhaps?


title: How can I collect data for visualization of quick sort?

text: I know how to implement quick sort in Mathematica. But I don't know how to get the temp data for visualization, because I used recursion. I want the effect like this.               qsort[{}] = {};     qsort[{x_, xs___}] := Join[qsort@Select[{xs}, # <= x &], {x}, qsort@Select[{xs}, # > x &]];     qsort@RandomSample@Range@30


title: {Latitude, Longitude} to Transverse Mercator projection

text: I have a shapefile with the following `"CoordinateSystemInformation"`:               "PROJCS" -> {"NAD_1983_StatePlane_Illinois_East_FIPS_1201_Feet",     "GEOGCS" -> {       "GCS_North_American_1983",        "DATUM" -> {         "North_American_Datum_1983",         "SPHEROID" -> {"GRS_1980", 6.37814*10^6, 298.257}},        "PRIMEM" -> {"Greenwich", 0.},        "UNIT" -> {"Degree", 0.0174533}},      "PROJECTION" -> {"Transverse_Mercator"},      "PARAMETER" -> {"False_Easting", 984250.},      "PARAMETER" -> {"False_Northing", 0.},      "PARAMETER" -> {"Central_Meridian", -88.3333},      "PARAMETER" -> {"Scale_Factor", 0.999975},      "PARAMETER" -> {"Latitude_Of_Origin", 36.6667},      "UNIT" -> {"Foot_US", 0.304801}}      I would like to plot {Latitude, Longitude} points and overlay these images, but I am having trouble converting coordinates. The shapefile data contains coordinates in the vicinity of {1.16328*10^6, 1.89271*10^6}. (This is Chicago.) One point I would like to plot is {41.8713, -87.6737}.               GeoGridPosition[GeoPosition[{41.8713, -87.6737}], "TransverseMercator"]      gives the wrong coordinates:               GeoGridPosition[{-0.164851, 0.743066}, "TransverseMercator"]      As does               GeoGridPosition[GeoPosition[{41.8713, -87.6737}], "Mercator"]      which yields:               GeoGridPosition[{1.6114, 0.806147}, "Mercator"]      What am I doing wrong? It's not a question of reversed coordinates as in this thread.


title: Making code version aware

text: Mathics, a free Mathematica-compatible project has been recently launched. It provides a subset of the functions and capabilities of Mathematica at a slower pace. This opens us the tantalizing possibility to share our code even with people who do not have Mathematica on their computers. Since Mathics is currently supporting only a fraction of all Mathematica functions, it becomes important for our code to be able to discriminate whether it is run within Mathematica or Mathics. Is this possible?


title: How to apply restrictions to the "integrated" variable, when using NDSolve?

text: I have to integrate an energy along a path. I know the energy at the "beginning" of the path (`energy[0]`), and I can determine the energy change (gain and loss) along it (`energy'[x]`). But the values the `energy[x]` can have are restricted, since, along the path, the energy is always equal or above a certain value (`minimumEnergy[x]`). This minimum energy limits changes in an abrut manner, and only influence the values downward the path. If this would be done in a Euler step manner, it would be easy: starting from the beginning of the path, at each new step `energy[x]=Max[energy[x-step]+step*energy'[x-step], minimumEnergy[x]]`. How can I put this restrictions on `NDSolve`? I've tried to artificially change the `energy'[x]` equation so that it compensates the difference to have the `minimumEnergy[x]`, but this did not went well. Another problem that I have is that `energy'[x]` is based on the value of energy[x], and the equation has no real value for `energy[x] < minimumEnergy[x]`. I've tried to figure out how to implement it with StepMonitor, but came to no conclusion. The system is slightly complex to be placed here, and so I hope the above explanations are good enough for the understanding of my problem. The following code will not run. I just placed it here for a better understanding. I already implemented J.M. suggestion on the `EventLocator`.               ans = energy/. Flatten[NDSolve[         {             energy[outletChannelEnd] == minimumEnergy[flowrate] + bottomFunction[0],             energy'[x] == headLoss[flowrate, height4Head[flowrate, energy[x] - bottomFunction[x]]]         },         energy,         {x, 0, 241},          Method -> {             "EventLocator",             "Event" -> (energy[x] - (minimumEnergy[flowrate] + bottomFunction[x])),             "EventAction" :> (energy[x] = minimumEnergy[flowrate] + bottomFunction[x])         }     ]]      The result is as follows, where the blue line is the minimum energy, and the purple is the calculated one: ![enter image description here](http://i.stack.imgur.com/aOeZs.gif) EDIT: It correctly detects there is an event on the x=73 (I have asked for a print on the event actions), but it doesn't correct the `energy'[x]`


title: inequalities in equations and constraints

text: Say That I have the constraint:               .5<x1<x2<x3<x4<40      I want to use this constraint in a Nminimize function. It seems that mathematica runs into a problem when you have this. For example Nminimize will output an error saying that this function variable is not real for "-x2" but this constraint defines my variables all to be positive. So is there a better way to write this constraint?


title: How many triangles are there?

text: Some time ago I found a puzzle and it stopped my work until I solved it. ![](http://i.stack.imgur.com/7sTmp.png) One of the possible solutions: Let us sum upright and upside down triangles whose top lies in the $i$-th row. $$ N=\sum_{i=1}^n N_i^\Delta + N_i^\nabla. $$ For upright triangles we should multiply the number of possible sizes $n-i+1$ by the number of possible horizontal positions $i$ $$ N_i^\Delta = (n-i+1)i. $$ An upside down triangle with size $l$ at $i$-th row have $n-i-l+1$ positions and the size $l$ limited by $\min(i,n-i)$, therefore $$ N_i^\nabla = \sum_{l=1}^{\min(i,n-i)}(n-i-l+1). $$ Finally, we have $$ N=\sum_{i=1}^n\Bigl((n-i+1)i+\sum_{l=1}^{\min(i,n-i)}(n-i-l+1)\Bigr). $$ For $n=28$ rows we get $N=5985$ triangles. My question is: could you suggest a less trivial solution, which can reveal the power of the different sides of _Mathematica_? I mean look at this problem from different sides: finding a sequence, image-processing, finding a cycles in a graph and so on.


title: How to abort on any message generated?

text: Mathematica is a bit unusual as a programming language because it never stops on messages, regardless of whether the message is an error, a warning or just an informative message. It simply prints the message and continues with evaluation. This can cause an avalanche of messages and unpredictable behaviour (e.g. memory may get filled up, bringing the machine to a halt with swapping---this is what happened to me) **Is there a way to immediately abort when _any_ message is generated?** Requirements:   1. if a message would be printed, always abort.   2. if no message would be printed, don't abort.   3. do print the first message so I have a hint about what went wrong   4. the mechanism should work with parallel computations and should abort the full evaluation (i.e. main kernel and all parallel kernels) There are many ways to handle message printing, including `On`/`Off`, `Quiet`, and possibly others (such as setting some system options). The solution should work well with these. I am afraid manually handling all possible situations is too fragile (there's always a chance something got left out). I found a solution on MathGroup which aborts, but does not print the message. _I suspect there must exist a robust and simple solution because the Debug palette has a "Break on messages" option._


title: Create Slider to start/stop/move Point

text: I want to be able to start, stop, and move the dynamically moving point simultaneously in both animations. The "PlayPauseButton" in the animations only controls the given animation. Indeed, I want both animations to always by synchronized.               system = {x'[t] == 2 x[t] - 0.08 x[t] y[t], x[0] == 400,               y'[t] == -y[t] + 0.01 x[t] y[t], y[0] == 25};     sol = NDSolve[system, {x[t], y[t]}, {t, 0, 21.5}];     {x1[t_], y1[t_]} = {x[t], y[t]} /. Flatten[sol];          px4 = Plot[x1[t], {t, 0, 21.5}, PlotRange -> {0, 400}, PlotStyle -> {Black}];     py4 = Plot[y1[t], {t, 0, 21.5}, PlotRange -> {0, 400}, PlotStyle -> {Black, Dashed}];          Row[      {Animate[        Show[px4, py4,         Graphics[{PointSize[Large], Red, Point[Dynamic[{t, x1[t]}]],                    Point[Dynamic[{t, y1[t]}]]}]], {t, 0, 21.5,         AppearanceElements -> "PlayPauseButton"}, SaveDefinitions -> True,        AnimationRate -> 0.251, AppearanceElements -> "PlayPauseButton",         BaselinePosition -> Bottom],       Animate[        Show[ParametricPlot[{x1[t], y1[t]},{t, 0, 5.375}, AxesLabel -> {"Prey", "Predator"},                              AspectRatio -> 1, PlotRange -> {{0, 400}, {0, 80}}],              Graphics[{Red, PointSize[Large], Point[{x1[t], y1[t]}]}]],        {t, 0, 5.375, AppearanceElements -> "PlayPauseButton"},         SaveDefinitions -> True, AnimationRate -> 0.251,         BaselinePosition -> Bottom]}, Frame -> True, RoundingRadius -> 10]      The desired slider should fit into the frame space above the first "Animate". Perhaps I could have rewritten this code with Manipulate, but I don't know how to do that either.


title: How to make the computer consider two numbers equal up to a certain precision

text: My problem is that I have a matrix `A` and the computer says is not Hermitian (self-adjoint). Then I check which elements make `A` be not Hermitian by calculating:               B=A-ConjugateTranspose[A]      In case `A` is Hermitian, this difference should be zero. What I get is that `A` is not Hermitian, but the terms I get in matrix `B` all are smaller than `10^(-15)`. So how can I fix it at the beggining of the code, _Mathematica_ to consider two numbers equal, up to `10^(-10)` precision for example, that is it to consider: > 0.00000000010 = 0.00000000012 or saying it in an alternative way, I want _Mathematica_ to consider the following matrix Hermitian:               C={{0,I*1.1^(-10)},{-I*1.2^(-10),0}}      throughout the whole code.


title: using interpolation functions in ParallelMap

text: **Edit** _I am editing the question to give a simple workable example. It is at the bottom under the heading **Example**. The original question is now headed withe **Background**._ **Background** I am trying to calculate large tables with values taken from a normal distribution and an interpolation function (as well as a spherical coordinate). The interpolation function is b[j] below where j is an index denoting a certain interpolation function. The interpolation functions come from large arrays. I would like to calculate for different j in parallel since I have 30 different j to work with (j = 1..30). The problem I am seeing is that the parallel calculation is in fact much slower when the interpolation functions are present. The code is (which you will not be able to run since you don't have the bx,by,bz functions):                l = 0.2;      xEdge = 1990.;      yEdge = 1990.;      zBottom = 36.;      zTop = 126.;                dataMod[j_, rc_] := Module[{},           X = RandomReal[{rc, xEdge - rc}];      Y = RandomReal[{rc, yEdge - rc}];      Z = RandomReal[{zBottom + rc, zTop - rc}];           \[Phi]1 = RandomReal[{0., 2. \[Pi]}];      \[Theta]1 = RandomReal[{0., \[Pi]}];      y = RandomReal[{0., rc/l}];      d = l y;      dx = d Cos[\[Phi]1] Sin[\[Theta]1];      dy = d Sin[\[Phi]1] Sin[\[Theta]1];      dz = d Cos[\[Theta]1];           {y, \[Phi]1, \[Theta]1,      RandomReal[NormalDistribution[0., 1./2.]] + bx[j][X, Y, Z],      RandomReal[NormalDistribution[0., 1./2.]] + bx[j][X + dx, Y + dy, Z + dz],      RandomReal[NormalDistribution[0., 1./2.]] + by[j][X, Y, Z],      RandomReal[NormalDistribution[0., 1./2.]] + by[j][X + dx, Y + dy, Z + dz],      RandomReal[NormalDistribution[0., 1./2.]] + bz[j][X, Y, Z],      RandomReal[NormalDistribution[0., 1./2.]] + bz[j][X + dx, Y + dy, Z + dz]}      ];           data[j_, rc_, nMax_] := Table[dataMod[j, rc], {nMax}];      I would like to calculate the table for several different values of j. Here I use only 2 though in actuality, I will use 30:                list = Map[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      This took **6.6** seconds. On two kernels,                listParallel =       ParallelMap[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      took **119** seconds on two kernels. Why is this so much slower? Are the (10000) elements of the table being calculated in parallel or are j = 1 and j = 2 being calculated in parallel (which is what I was aiming for). I thought ParallelMap would calculate j=1 and j=2 in parallel (i.e. simultaneously so I would expect the time to be $\sim 3.3$ seconds). If I get rid of the interpolation functions,                dataMod[j_, rc_] := Module[{},           X = RandomReal[{rc, xEdge - rc}];      Y = RandomReal[{rc, yEdge - rc}];      Z = RandomReal[{zBottom + rc, zTop - rc}];           \[Phi]1 = RandomReal[{0., 2. \[Pi]}];      \[Theta]1 = RandomReal[{0., \[Pi]}];      y = RandomReal[{0., rc/l}];      d = l y;      dx = d Cos[\[Phi]1] Sin[\[Theta]1];      dy = d Sin[\[Phi]1] Sin[\[Theta]1];      dz = d Cos[\[Theta]1];           {y, \[Phi]1, \[Theta]1,      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]]}      ];      then                list = Map[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      takes 0.99 seconds. The parallel version had a modest speed-up                listParallel =       ParallelMap[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      to 0.92 seconds which is at least not a lot slower as seen with the interpolation functions present. So why is it that the interpolation functions seem to present a problem for ParallelMap? Is there anything else obvious that I can do do speed this up (in reality nMax must be 1-100 million)? **Example** My question concerns using interpolation functions on multiple kernels with ParallelMap. Here is an example that I think illustrates my problem. Define the interpolation functions:                l = 0.2;      xEdge = 4.;      yEdge = 4.;      zBottom = 0.;      zTop = 4.;           {cx[1], cx[2], cx[3], cx[4]} =  Table[Interpolation[       Flatten[Table[{x, y, z, j*Sin[x y z]}, {x, 0, xEdge, 0.1}, {y, 0,         yEdge, 0.1}, {z, zBottom, zTop, 0.1}], 2]], {j, 1, 4}];      I now evaluate the interpolation functions at specific points governed by the following:                ffMod[j_, rc_] := Module[{},            X = RandomReal[{rc, xEdge - rc}];       Y = RandomReal[{rc, yEdge - rc}];       Z = RandomReal[{zBottom + rc, zTop - rc}];            \[Phi]1 = RandomReal[{0., 2. \[Pi]}];       \[Theta]1 =  RandomReal[{0., \[Pi]}];       y = RandomReal[{0., rc/l}];       d = l y;       dx = d Cos[\[Phi]1] Sin[\[Theta]1];       dy = d Sin[\[Phi]1] Sin[\[Theta]1];       dz = d Cos[\[Theta]1];            {cx[j][X, Y, Z], cx[j][X + dx, Y + dy, Z + dz]}       ];      I then want to make a large table of values (20000 here, but actually want to do for 1 million or more):                ffData[j_, rc_, nMax_] := Table[ffMod[j, rc], {nMax}];      for several different j.                ffList = Map[ffData[ #, 1., 2*10^4] &, Range@4]; // AbsoluteTiming      takes 8.9 seconds. In parallel on 4 kernels:                ffListP = ParallelMap[ffData[ #, 1., 2*10^4] &, Range@4]; // AbsoluteTiming      takes 17.6 seconds. How can I speed up the parallel version of this as I would expect that each kernel could operate on the 4 different j's?


title: Importing numerical values from a PDF file

text: I need the numerical values from pdf files like this one. ![Mathematica graphics](http://i.stack.imgur.com/xuZAG.png) When I use the usual `Import` command, the PDF imports, but pages of images. How can _Mathematica_ be used to import the numerical values from a PDF?


title: No builtin function for bitwise rotation?

text: There appears to be no builtin Mathematica function for bitwise rotation. Is that true? I suppose I can write my function:               ROR[x_, k_] := FromDigits[RotateRight[IntegerDigits[x, 2, 32], k]]      Obviously this will be a lot more inefficient than a builtin function because in machine code a rotate right is a single instruction. Is this my only option?


title: Visualize eigenvectors at specified points?

text: I am very new to Mathematica and I got stuck about visualizing eigenvectors 2D and 3D. I want to visualize my largest eigenvector field of tensor data(15x15). I wrote this code for instance :               points = {{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1,      2}, {2, 2}};          ListVectorPlot[{{{0, 0}, {1, 1}}, {{1, 0}, {1, 0}}, {{2, 0}, {0,      1}}, {{0, 1}, {1, -1}}, {{1, 1}, {1, 1}}, {{2, 1}, {-1, 1}}, {{0,      2}, {0, 1}}, {{1, 2}, {-1, 0}}, {{2, 2}, {0, -1}}}, VectorPoints -> points, FrameLabel -> {x, y}, PerformanceGoal -> "Quality", Epilog -> {Red, PointSize[Medium], Point[points]}]      But my vectors don't begin from the specified point. `ListVectorPlot` function locate the vector in the middle of the point. Do you think I have to use another function like `Arrow` and `Graphics`? In addition,I want to plot my second eigenvectors from the same point. For example, I have a matrix and its eigenvectors are {{1,1}, **{-6,5}** } or {{4,5},{-1,3}}. At the end I have to multiply these vectors with their eigenvalues({{2,4}}) and visualize like that. How can I do that at specified points at an order and different lenghts of vectors(multiply with eigenvalues)? Below you can find a basic example data,               datax = {{{{3, 4}, {4, 3}}, {{3, 4}, {4, 3}}, {{3, 4}, {4,       3}}}, {{{3, 6}, {6, 3}}, {{3, 6}, {6, 3}}, {{3, 6}, {6,       3}}}, {{{3, 5}, {4, 3}}, {{3, 5}, {4, 3}}, {{3, 5}, {4, 3}}}};     dataxv = Table[Eigenvectors[datax[[z, t]]], {z, 1, 3}, {t, 1, 3}];     dataxva = Table[Eigenvalues[datax[[z, t]]], {z, 1, 3}, {t, 1, 3}];      Thank you in advance.


title: How to implement Condition programmatically?

text: I am writing my own symbolic functions with custom symbolic properties. So often I wish to introduce some automatic simplifications or evaluations, which return the same head as it's argument. This means I can't use normal function definition to avoid infinite recursion. Suppose I with to create library for naive set theory. I am introducing `MySet` head to represent sets. For example, to create a set with `a`, `b` and `c` elements, I will write               MySet[a,b,c]      and Mathematica will reply               {a,b,c}      since I defined head `MySet` to be displayed in curly braces. Of course               MySet[a,b,c] // FullForm      will give               MySet[a,b,c]      Now suppose I wish to remove duplicates automatically, since sets do not care of duplicates. So that if I wrote               MySet[a,b,b,c]      Mathematica would reply               {a,b,c}      How to accomplish that? Currently I am writing two helper functions, like `HasDuplicates` and `RemoveDuplicates` and write something like that               MySet[x__] :=      MySet@@DeleteDuplicates[{x}] /;         HasDuplicates[{x}];      But this approach requires me to code nearly the same things in two places -- `HasDuplicates` and `RemoveDuplicates` functions. How to avoid this? Is it possible to write this in some following manner:               MySet[x__] := Block[{...},         (* search for duplicates and remove them *)         If[ someweremoved,              MySet[y], (* with removed duplicates *)             MySet[x] (* with no modifications *)         ];     ];      The problem is that I can't prevent infinite recursion here since `MySet` is called again and again in any case. Can I prevent recursion by force? I.e. tell somehow, that expression returning should not be reevaluated? Or may be I can implement `Condition` somehow in programming style? Or may be there is a way to code simplifications somehow? **UPDATE** The set is just a sample. My question is about general solution, suitable for ANY case of simplifications. The general sign of simplification is just was it done something or not. We can't assume we can compare some short list or count some.


title: Setting a binary operator Flat

text: I defined a binary operator in as the first statement in a new _Mathematica_ notebook.               {x1_, y1_} ⊕ {x2_, y2_} := Module[{}, Print["do anything"];]      where the code in the `Module` is somewhat more meaningful. My questions:   1. Why does this not show up in a `?Global`*` query?   2. How can I set the `Attributes` for this operation to be `Flat` so it is associative?   3. Do I need to use the `Notations` Package to do this "properly"?


title: how to get modify the following correlation matrix with a specific list of financial prices?

text: The following takes the last 5 members of the Dow Jones index and plots the correlation matrix of the last 5 years of daily prices:               mem = FinancialData["^DJI", "Members"];     findata =        FinancialData[#, "Price", {{2007}, {2012}, "Day"}][[All, 2]] & /@         mem[[-5 ;; -1]];     fincm = Correlation[Transpose@findata];          tb = Map[Item[NumberForm[#, 2],           Background ->            ColorData["TemperatureMap"][Rescale[#, {-1, 1}]]] &, fincm, {2}];     tb = Prepend[tb, mem[[-5 ;; -1]]];     tb = Join[List /@ Prepend[mem[[-5 ;; -1]], ""], tb, 2];     GraphicsGrid[tb, ImageSize -> 500, Frame -> All]      But what if I want to compare 5 specific equities instead from various listed exchanges; i.e CWC.L, CAP.PA, IFX.DE, ISYS.L and LAD.L? Anyone?


title: NDSolve fails for certain choices of parameters and solve range

text: I'm trying to solve a pair of coupled ODEs with NDSolve. I know roughly what the solution should look like (both should give periodic functions, pi/2 out of phase, the amplitude of which damp towards a common limiting value), but I am trying to work out what the limiting amplitude is for a range of parameters. For certain choices of parameters, the solution looks how I would expect, but for others the NDSolve sporadically takes very large steps and the output either diverges, becomes constant, or shows other noisy/glitchy behaviour. Changing the NDSolve range also makes these effects come and go, and reducing the MaxStepSize or changing the Working Precision to anything but 16 makes things worse - so I'm pretty sure this is a computational problem. I'm pretty new to Mathematica so this is probably something simple, but every suggestion I've seen in other posts (increasing workingprecision, limiting step size etc) has only made things worse so I'm a bit stumped!               ( _Define some constants_ )     wc0 = 0.9645*^8*B/mass /. {mass -> 40, B -> 1.845};     fc0 = wc0/2/[Pi];     ( _Define wz, w1, wc and wm as functions \     of trap voltage V_ )     wz[V1_] = Sqrt[4*0.9645*^8*1*V1/40/0.0189^2];     w1[V1_] = Sqrt[wc0^2/4 - wz[V1]^2/2];     wc[V1_] = wc0/2 + w1[V1];     wm[V1_] = wc0/2 - w1[V1];     ( _Want to find limiting value as these parameters are varied_ )     V = 244;     d = 100000;     rate = 2*^6;     rm0 = 5*^-6;     rc0 = 5*^-6;     ( _Solve for dynamics_ )     mysolve =        NDSolve[{           rc'[t]==rate*B/w1[V]^2/2/rc[t]-rate*wc[V]*A*rc[t]/w1[V]/2+d*rm[t],           rm'[t]==rate*B/w1[V]^2/2/rm[t]+rate*wm[V]*A*rm[t]/w1[V]/2-d*rc[t],            rm[0] == rm0, rc[0] == rc0} /. {B -> 3.4*^-4, A -> 3*^-3},           {rc[t], rm[t]}, {t, 0, 0.009}, MaxSteps -> Infinity           ];                              range = 1*^-6;     ( _Plot dynamics_ )     Plot[Evaluate[rc[t] /. mysolve], {t, 0.0, 0.008},       PlotRange -> {-range, range}, AspectRatio -> 0.25, ImageSize -> 800]     Plot[Evaluate[rm[t] /. mysolve], {t, 0.0, 0.008},       PlotRange -> {-range, range}, AspectRatio -> 0.25, ImageSize -> 800]                              ( _Find limiting value_ )     intmin = 0.004;     intmax = 0.008;     lrc = Sqrt[2*NIntegrate[Evaluate[rc[t]^2 /. mysolve], {t, intmin, intmax}]/(intmax-intmin)]     lrm = Sqrt[2*NIntegrate[Evaluate[rm[t]^2 /. mysolve], {t, intmin, intmax}]/(intmax-intmin)]                    (**)      The parameters listed above give a sensible result (first image) - but if, for instance, I change the NDSolve window to {t,0,0.004} or {t,0.04}, or change 'd=100000' to 'd=80000' (second image) it starts behaving strangely. Any help would be very much appreciated! ![Expected behaviour for settings listed above](http://i.stack.imgur.com/9dVN6.jpg) ![Glitchy behaviour when parameter changed \(here d=80000\)](http://i.stack.imgur.com/cp4Zf.jpg)


title: An ancient MIDI keyboard?

text: There is a demostration project http://demonstrations.wolfram.com/KeyboardAndComposer/ where you can compose Western music using a 97 keys simulated midi keyboard. I study eastern and ancient music and harmony. So I can not use SoundNote for this kind of music (where each note is represented as a fraction. Using middle Do as a base (i.e., `base = 260.741 Hz`), the next notes are represented by `re = 9/8 base`, `mi = 5/4 base`, `fa = 4/3 base`, `sol = 3/2 base`, `la = 3/2 9/8`, `si`=`3/2 5/4`) So my problem is to change the above keyboard so that   1. the keys have pitches defined using some fractions like the ones mentioned above   2. The user could simultaneously use his/her computer keyboard with the midi keyboard for music synthesis and polyphony. For example: While simultaneously pressing R on computer keyboard and midi button fa on the Mathematica Midi Keyboard the user could hear re + fa continuously (or at least as long as the R key and fa button are pressed.). But when R is released (and midi button fa is still pressed) only fa will be heard. Some help, please!


title: Alternatives to Mathematica

text: Inspired by the recent question Alternatives to LaTeX (currently 58 upvotes) on http://tex.stackexchange.com/: Are there any paid-for or open source alternatives to Mathematica which produce equal or even better functionality, specifically with regard to solving, manipulating and visualising algebraic expressions. Note: a similar question is Best open-source Mathematica equivalent, however this question is targeted at users of Mathematica.SE (and is five years in the future).


title: Automatic inverse for Lambert’s Azimuthal Equal-Area Projection

text: I’m interested in finding closed-form inverses for map projection equations in general (of course, this is not always possible). I’m hoping Mathematica can help me with some of the trickier ones. As a **practice run** , I thought I would try and use Mathematica to invert Lambert’s Azimuthal Equal-Area Projection. There are of course closed-form inverse equations on MathWorld, but I’m wondering how I would go about finding these using Mathematica. I’ve tried using `Solve` and `Reduce`, for example:               k = Sqrt[2/(1 + s1 Sin[y] + c1 Cos[y] Cos[x])]     Solve[{u, v} == {       k Cos[y] Sin[x],        k (c1 Sin[y] - s1 Cos[y] Cos[x])     }, {x, y}]      But no luck so far. Perhaps I need to specify more constraints? For example, I know that the longitude and latitude (`x` and `y` above) have:               -π ≤ x ≤ π     -π/2 ≤ y ≤ π/2      I wonder if eliminating variables might also help the solving routines.


title: Integration over a convex combination of a region: $\int_{\Omega} (w_1 z_1 + w_2 z_2)^{1-\sigma} d (z_1, z_2)$ where $\Omega = \{ z_1 + z_2 = 1\}$

text: Take $w,z\in R^{n}$. I am interested in integrating (as generically if possible) $$\int_{\Omega}(w \cdot z)^{1-\sigma} d z$$ Where the domain of $\Omega$ is $1$ dimension, and includes the convex combinations of $z$. i.e. $\Omega \equiv \\{z | \sum z = 1 \\}$ Obviously, for $n=2$, this is easy to rearrange: $$\int_{0}^{1} \left(w_1 z_1 + w_2 (1-z_1)\right) d z_1$$ $$ = \frac{w_2^{2-\sigma} - w_1^{2-\sigma}}{(\sigma - 2)(w_1 - w_2)}$$ And the mathematica code is:               Integrate[(w[1] z[1] + w[2] (1 - z[1]))^(1 - \[Sigma]), {z[1], 0, 1}] // FullSimplify      But it is a little harder to cheat like this as $n$ gets larger, and I am hoping for more general patterns. How would I set up the simple $n=2$ example using the convex combination directly? I tried things like: Integrate[(w[1] z[1] + w[2] z[2])^(1 - [Sigma]), {z[1], 0, 1}, {z[2], 1 - z[1], 1 - z[1]}] // FullSimplify Integration over a convex combination of a region: $\int_{\Omega} (w_1 z_1 + w_2 z_2)^{1-\sigma} d (z_1, z_2)$ where $\Omega = \\{ z_1 + z_2 = 1\\}$ ...but I couldn't get them to work.


title: Import symbolic variables from Matlab with MATLink

text: I'm trying to manipulate with Mathematica symbolic expression created in Matlab. I'm using the MATLink package, and I've succedeed in importing numerical variables, but not symbolic ones :               MEvaluate["syms g real"]     MEvaluate["syms l real"]     MEvaluate["u = g + l"]     MGet["u"]      will output :               u =      g + l % Matlab correctly defines the variable     {}    % Mathematica doesn t succeed in getting the variable      Anyone with experience in dealing with this ?


title: using 'steps' in Manipulate

text: I want to make a `3D` shape move through a specified graph; e.g. `y = Sin[x]`, such that it moves up and down.   My working so far has been to use `Manipulate`, and I think I want to use it with 'steps', as in the documentation, second one down, although I don't know how to use this.   Would this be the way, and if so how do I use it? Here is what I have so far:               Manipulate[Graphics3D[{Green, Cuboid[{0, 0, t}], Blue, Cuboid[{0, 0, 0}]}], {t, 0, 3}]      I think I want something like:               Manipulate[ Graphics3D[{Green, Cuboid[{0, 0, t}], Blue, Cuboid[{0, 0, 0}]}],                 {t, 0, 3, y = Sin[x]}]


title: Predictive interface eats my Esc key

text: After updating to version 9, I found the predict interface very helpful except there is a small problem always annoying me: Consider this: I have a list `abc = Range[1, 10];` and I want to take part of it `abc[[2]]`. For the `[[` and `]]`, I like to use the closer version of the bracket (`\[RightDoubleBracket]`) by press key `Esc`+`[`+`[`+`Esc` and `Esc`+`]`+`]`+`Esc`. ![enter image description here](http://i.stack.imgur.com/9y63p.png) In version 9, when I type `abc` I get this drop list of predictions, and the first `Eec` key goes to remove the drop list and the `[[` is not correctly typed: ![enter image description here](http://i.stack.imgur.com/cZYNW.png) ![enter image description here](http://i.stack.imgur.com/S4BDo.png) So it is possible to make the drop list automatically disappear once what I typed matches the exists variable, so that the first `Esc` key is not eaten by the drop list?


title: Elegant transformation of various rules to strings, {f[z_] -> y} becomes "f = @(z) y"

text: Assume that I have some function for transformation mathematica expressions to strings. For simplicity, just assume it is an identity:               mytostring[e_] := ToString[e]; (* In reality, much more complicated... *)      What I want to take various permutations of variadic rules syntax and apply this function to create a string for the function. e.g. assume my basic test is:               rulestostring[rule_????] := ???     testrules = {f[x,y] -> x, f[x_,y_] -> x, f[x,y] :> x, f[x_,y_] :> x};          (* Create a function rulestostring where all of these give the same output as a string:     ==>    "f = @(x,y) x"     Where the f is actually generated from mytostring[f], x is from mytostring[x], etc.     *)      I need it to support variadic arguments and a few other things:               otherrules = {f[x_] -> x, f[x[bar]] -> x[bar]};     (* ==>   {"f = @(x) x", "f = @(x[bar]) x[bar]"     where in reality both x[bar] would be transformed by mytostring     *)      (you can probably guess that what I am doing is extending the http://library.wolfram.com/infocenter/MathSource/577/ package to generate matlab functions. If anyone has an updated version of this package it would be appreciated)


title: CSS Selectors for Symbolic XML

text:
_Symbolic XML_ is a convenient way of managing **XML** in _Mathematica_ , at least for casual use or small tasks. Here and elsewhere you can find examples of **XML** handling in _Mathematica_ , including **XSLT** / **XPath** emulations. In my opinion, however, if you must perform frequent searches, content extraction, or deep transformations, e.g., Web scraping, _Symbolic XML_ quickly becames clumsy and cumbersome to work with. If you have ever faced any kind of web programming, you're probably aware of the convenient **CSS Selectors** , the more common choice (being the other XPath) to tackle the aforementioned kind of problems. I'm curious, are there implementations of **CSS Selector** (and/or XPath) engines in _Mathematica_? If not, would be feasible/sensible to implement like capabilities in _Mathematica_? Or is it better to stick with ad-hoc queries and follow the examples approach? As elegant code is better than thousand opinions, we could illustrate the answers with this toy, greatly simplified, CSS Selector engine:                      **Pattern** | **Matches**                                                              | **Selector**     ---------------| -------------------------------------------------------------------- | ----------------                  * | any element.                                                         | Universal                  E | any E element (i.e., an element of type E).                          | Type          E.warning | any E element whose class is "warning".                              | Class             E#myid | any E element with ID equal to "myid".                               | Id                E F | any F element that is a descendant of an E element.                  | Descendant              E > F | any F element that is a child of an element E.                       | Child              E + F | any F element immediately preceded by a sibling element E.           | Adjacent Sibling              E ~ F | any F element preceded by an E element                               | General sibling             E[foo] | any E element with the "foo" attribute set (whatever the value).     | Attribute       E[foo="bar"] | any E element whose "foo" attribute value is exactly equal to "bar". | Attribute                    A selector is a chain of one or more simple selectors separated by combinators.     Combinators are: white space, ">",  "+", and "~". White space may appear between a combinator and the simple selectors around it.     A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or class selectors, in any order.     The universal selector may be omitted if followed by other simple selector components.     The simple selector matches if all of its components match.          Examples:     "*div" or "div", all elements with tag "div";     "div *", all descendants at any level of all div elements;     ".aClass+[attr=val]", direct descendants with attr equals val of elements with class aClass.      If you need a formal grammar, take a look to the W3C spec, but for this illustration I think that we can prescind of error handling or stringent processing. Then, given _context_ , any expression containing `XMLElements`, and _selector_ , a string compliant with the toy CSS grammar, implement **positionSelector[ _context_ , _selector_ ]** to return the positions (same format of `Position` built-in) of `XMLElements` matching selector:               xml = ImportString["<!doctype html>
Animals
", "XMLObject"];     positionSelector[xml, "body"]     positionSelector[xml, "*"]     Extract[xml, positionSelector[xml, "h1"]]          (* ==> {{2, 3, 1}} *)     (* ==> {{2, 3, 1, 3, 1}, {2, 3, 1}, {2}} *)     (* ==> {XMLElement["h1", {}, {"Animals"}]} *)          xml = ImportString["
Eh...
What's up, doc?up, doc?

Legen
--
Wait for it
--
Dary!

No.
I am your

 father.

", "XML", "NormalizeWhitespace" -> False];     result = positionSelector[xml, "div>span"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 1, 3, 2, 3, 1, 3, 1}, {2, 3, 1, 3, 2, 3, 1, 3, 3}, {2, 3, 1, 3, 2, 3, 1, 3, 5}} *)     (* ==>     XMLElement["span", {}, {"What's "}],      XMLElement["span", {"id" -> "def"}, {"doc?"}],      XMLElement["span", {"id" -> "def"}, {"doc?"}]}     *)          result = positionSelector[xml, "[class]>div"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 2, 3, 2, 3, 2}, {2, 3, 2, 3, 2}} *)     (* ==>      XMLElement["div", {"class" -> "dClass"}, {"Wait for it"}],      XMLElement["div", {"class" -> "cClass"}, {"--",      XMLElement["div", {"class" -> "dClass"}, {"Wait for it"}], "--"}]}]     *)          xml = ImportString["<!doctype html>
Animals

Lillith>

MaggieFatty
        ",      "XMLObject"];          result = positionSelector[xml, "h2+.dog"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 1, 3, 5}} *)     (* ==> XMLElement["h2", {"class" -> "animal dog mutt", "id" -> "maggie"}, {XMLElement["span", {"class" -> "christian Name"}, {"Maggie"}], XMLElement["span", {"class" -> "nick Name"}, {"Fatty"}]}]} *)          result = positionSelector[xml, "h2+#maggie"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 1, 3, 5}} *)     (* ==> XMLElement["h2", {"class" -> "animal dog mutt", "id" -> "maggie"}, {XMLElement["span", {"class" -> "christian Name"}, {"Maggie"}], XMLElement["span", {"class" -> "nick Name"}, {"Fatty"}]}]} *)          positionSelector[xml, "h1~.dog"]          (* ==> {{2, 3, 1, 3, 3}, {2, 3, 1, 3, 5}} *)          positionSelector[xml, "h1~b"]          (* ==> {} *)      To be clear, I'm not looking for a full-blown implementation, but strategies and idioms of how _Mathematica_ can resolve XML queries, and in which ways is _Mathematica_ better equipped for that than mainstream functional/imperative languages.


title: How do I map a Mollweide projection onto a sphere?

text: I have this Mollweide projection of the Earth circa 600 million years ago (http://jan.ucc.nau.edu/~rcb7/370moll.jpg).(1) ![Mollweide projection of the earth](http://i.stack.imgur.com/XkyQI.jpg) I want to map this onto a sphere. My results have big black splotches in the Pacific Ocean and the continents are distorted, because the code I used also mapped the black corners of the image to the sphere. I need to map just the central ellipse. What sort of code should I use? Perhaps I need to first convert the image to an equirectangular projection. (1) Image credit: Ron Blakey, NAU Geology


title: Opacity limitations?

text: Trying to make a better-looking globe model, I start off with something like this ![enter image description here](http://i.stack.imgur.com/ddScb.png) To enhance the 3D effect, I want the lines further from the eye to be "grayer" than the lines closer to the eye, as if there were a little fog inside the sphere. I thought I might get there by replacing the great-circles with semi- transparent wafers, but it didn't work. It seems as though I hit some kind of internal limit on the number of semi-transparent objects I can create before they become opaque. Here is the original code with polygonal great circles (minus the RGB-XYZ axes):               ClearAll[e, o, g, \[Epsilon]];     e[1] = {1, 0, 0}; e[2] = {0, 1, 0}; e[3] = {0, 0, 1};     o = {0, 0, 0}; g = 1.25; \[Epsilon] = 1/10000;     ClearAll[polycircle];     polycircle[n_: 360] :=        Line@Table[{Cos[2 \[Pi] i/n], Sin[2 \[Pi] i/n], 0}, {i, n + 1}];     ClearAll[globeGrid];     globeGrid[bands_: 6, figure_: polycircle[]] :=       {Table[         Scale[Translate[figure,  Sin[(k \[Pi])/2] e[3]],           Cos[(k \[Pi])/2]]         , {k, -((bands - 1)/bands), (bands - 1)/bands, 1/bands}]        , Table[Rotate[Rotate[figure, \[Pi]/2, e[1]], k \[Pi], e[3]]         , {k, 0, (bands - 1)/bands, 1/bands}]};     ClearAll[showFrames];     showFrames[figure_:polycircle[]] := Show[{           Graphics3D[{          Opacity[0.05], Sphere[], Opacity[1.0]          , globeGrid[6, figure]          }]   }       , Axes -> True       , PlotRange -> {{-g, g}, {-g, g}, {-g, g}}       , ImageSize -> Large];     showFrames[]      To improve it, I replace the polycircles with partially transparent wafers, which are very thin cylinders at low opacity:               ClearAll[wafer];     wafer[opacity_: 1/24] :=       {RGBColor[1, 0.71, 0]        , Opacity[opacity]        , Cylinder[\[Epsilon] {-e[3], e[3]}]        , Opacity[1]};      The results were disappointing               showFrames[wafer[]]      ![enter image description here](http://i.stack.imgur.com/6KVNx.png) **EDIT:** I tried a tube               polytorus[n_: 100] := Tube[polycircle[n], 0.01];     showFrames[polytorus[48]]      it's too slow to be interactive, but it has a better 3D effect. Still looking for a better answer. ![enter image description here](http://i.stack.imgur.com/ZFlZm.png)


title: Behavior of ValueQ inside a function

text: The following code               Cases[Function[{x}, x + 1], a_?ValueQ :> Hold[a], ∞, Heads -> True]      unexpectedly returns > {Hold[x + 1]} According to the manual, "ValueQ[expr] gives True if a value has been defined for expr, and gives False otherwise." In the example above, what is the expression that was assigned the value x+1?


title: Why can I still hear sound when the frequency of the periodic function inside Play is lower than the range of human ear?

text: This question is originally part of this question, but this issue seems to be different from the former one, so I think it's better to start another question for it. Usually, human can't hear sound with a frequency lower than 20 Hz, but what's confused is, the output of the following code can generate very slight shrieks, to be precise, two shrieks for every period, and the pitch of the sound will be lower with lower `SampleRate`:               Play[Sin[2 Pi t], {t, 0, 1}]     Play[Sin[2 Pi t], {t, 0, 1}, SampleRate -> 4000]     Play[Sin[2 Pi t], {t, 0, 1}, SampleRate -> 2000]      After some trial, I noticed that the frequency of the slight shrieks seems to be equal to the `SampleRate`, i.e.                 Play[Sin[2 Pi t], {t, 0, 5}, SampleRate -> 2000]      and                 Play[Sin[2000 2 Pi t], {t, 0, 1}, SampleRate -> 4000 2 Pi]      have same pitch. (Remember to regulate volume since the shriek generated by the former sample is really slight. ) It's probably another kind of artifact, but can someone explain it in detail? * * * ~~Some more information: the shrieks are at the position of peaks and valleys of sine wave i.e.               Play[Sin[2 Pi t], {t, 0, 1}, SampleRate -> 2000]      has $2$ shrieks while               Play[Cos[2 Pi t], {t, 0, 1}, SampleRate -> 2000]      has $0.5+1+0.5$ shrieks.~~ * * * **Edit:** I should admit that I've misheard the position of the shrieks. With the code below, it's easy to distinguish that there's no sound at peaks and valleys:               Column[{Animate[Plot[Sin[2 Pi u], {u, 0, t}, PlotRange -> {{0, 5}, {-1, 1}}],                      {t, 0, 5}, AnimationRate -> 1, AnimationRepetitions -> 1],              EmitSound@Play[Sin[2 Pi t], {t, 0, 5}, SampleRate -> 2000]}]      I've posted the question in sound.SE and the answer I got there is in line with @CL.'s answer. Click here to read the answer (with a self-made video!).