title: Where does Workbench deploy to?

text: After a few months pause, I am using Workbench again and I cannot determine where is WB sending (deploying) my built package. WB does not ask for a destination folder, so I guess it must use some preference I set before... only I do not remember it! So, can someone please tell me how to find/set the destination folder for deployed applications? (Searching on my HDDs takes a long time.)


title: Is it safe to assign a variable and function of the same name for different things?

text: I'm writing out a notebook that goes through the van der Waals Equation of State for gases, and I run into a situation where I want to assign (simplified) Tc[b_]:=5b, use that to solve for b in terms of Tc with               b[Tc_]/.Solve[Tc==Tc[b],b][[1]]      Is it ok to assign Tc[b_] and still use Tc as a variable?   * If it is ok, is it possible to assign Tc[b_] and leave Tc blue instead of black, like other variables? What about assigning Tc[b_] and Tc to different things? How do the mechanics behind assigning things work in Mathematica such that I can assign Tc and not bother Tc[b_]? Here's my full code, it works fine, I'm just wondering down the road if evaluating like this will work in a more complicated situation.               RGas = Quantity["MolarGasConstant"];          Pvan[V_, T_] := (R*T)/(V - b) - a/V^2     Pvan[V_, T_]' := D[Pvan[V, T], V]     Pvan[V_, T_]'' := D[Pvan[V, T]', V]          CriticalValues =        Solve[{Pvan[V, T] == P, Pvan[V, T]' == 0 == Pvan[V, T]''}, {V, T, P}]          Pc[a_, b_] = P /. CriticalValues[[1]]     Vc[a_, b_] = V /. CriticalValues[[1]]     Tc[a_, b_] = T /. CriticalValues[[1]]          Zc[Pc_, Vc_, Tc_] := (Pc[a, b]*Vc[a, b])/(R*Tc[a, b])     Zc[Pc, Vc, Tc]          abCritical = Solve[{Tc == Tc[a, b], Pc == Pc[a, b]}, {a, b}]     a[Tc_, Pc_] = a /. abCritical[[1]] /. R -> RGas;     b[Tc_, Pc_] = b /. abCritical[[1]] /. R -> RGas;     \[Nu]c[Tc_, Pc_] := b[Tc, Pc]/4 /. R -> RGas;     \[Sigma][Tc_, Pc_] := ((3*\[Nu]c[Tc, Pc])/(4*\[Pi]*N₀))^(1/3) /.R -> RGas;          Solve[Eliminate[{P == Pvan[V, T], TR == T/Tc[a, b], VR == V/Vc[a, b],        PR == P/Pc[a, b]}, {P, T, V}], PR] // FullSimplify      It follows the first 3 pages of this.


How to find the maximum of a function on a set of discrete points? For example, what is the best way to find the maximum of               -2 a - 2 b - 2 c - 2 d - 2 e - 2 f + e (-2 + d + f) - 2 g + f (-2 + a + e + g) -       2 h + c (-2 + b + d + h) - 2 i - 2 j + a (-2 + b + f + j) + i (-2 + h + j) +       h (-2 + c + g + i + j) - 2 k + d (-2 + c + e + k) + j (-2 + a + h + i + k) -       2 l + g (-2 + f + h + l) + k (-2 + d + j + l) - 2 m + (-2 + b + l) m + l       (-2 + b + g + k + m) + b (-2 + a + c + l + m)      where $a,b,c,d,e,f,g,h,i,j,k,l, m \in \\{-1,1\\}$? Any help or suggestion will be appreciated!


title: LogLikelihood function from the Time Series package is apparently missing

text: The Time Series package for Mathematica comes with a function called `LogLikelihood`. It is discussed and used extensively in the documentation (pdf). So does Mathematica 8. First I though my inability to use `LogLikelihood` was that it was being shadowed by the `LogLikelihood` function in Mathematica itself, but apparently not. Loading the package with               Needs["TimeSeries`TimeSeries`"]      works for every other function, but the only `LogLikelihood`function I have access to is Mathematica's built in one. Trying to refere to it with the full context, like so               TimeSeries`TimeSeries`LogLikelihood      doesn't work either. It is as if this one function simply isn't there. I've also tried re-downloading the package and reinstalling in case I got a corrupt version the first time around, but this hasn't helped. **EDIT:** The way I am calling the function should be correct:               data = TimeSeries[ARModel[{0.5, -0.2}, 1], 20]     (*{0.775171, -0.0377616, -0.568652, 1.56771, 1.32269, -1.60302, \     -1.53275, 0.127154, 1.37393, 0.138493, -0.0484376, -0.506817, \     0.731963, 2.28373, 0.374458, 0.468365, 2.48781, 1.24375, 1.0746, \     -0.401619}*)          LogLikelihood[data, ARModel[{0.5}, 1]]     (*LogLikelihood[{0.775171, -0.0377616, -0.568652, 1.56771,        1.32269, -1.60302, -1.53275, 0.127154, 1.37393,        0.138493, -0.0484376, -0.506817, 0.731963, 2.28373, 0.374458,        0.468365, 2.48781, 1.24375, 1.0746, -0.401619}, ARModel[{0.5}, 1]]*)      **EDIT2:** Using full context in calling the function has the same result:               TimeSeries`TimeSeries`LogLikelihood[data, ARModel[{0.5}, 1]]     (*LogLikelihood[{0.775171, -0.0377616, -0.568652, 1.56771,        1.32269, -1.60302, -1.53275, 0.127154, 1.37393,        0.138493, -0.0484376, -0.506817, 0.731963, 2.28373, 0.374458,        0.468365, 2.48781, 1.24375, 1.0746, -0.401619}, ARModel[{0.5}, 1]]*)      **EDIT3:** This is the context path:               $ContextPath     (*{"TimeSeries`TimeSeries`", "PacletManager`", "WebServices`", \     "System`", "Global`"}*)


title: Animation: presenting events that persist in time

text: I have a list of events that occurred on specific moments in time. In the example below, the three events occurred at 23:09, 23:13 and 23:17. I was able to build an animation that flows from time 23:00 to 0:00 and shows at the right time the event by plotting a disc of a specified magnitude at the specified coordinates.               data = {{{2012, 3, 19, 23, 9}, 44.891, 12.202, 2.6, 2.5,         3541187340}, {{2012, 3, 19, 23, 13}, 44.898, 11.258, 6.2, 4.1,         3541187580}, {{2012, 3, 19, 23, 17}, 44.186, 11.496, 4.2, 2.2,         3541187820}};      Each event is specified by its time of occurrence, x and y coordinates, magnitude 1, magnitude 2, absolute time. First, I specified the start and end time of the animation in absolute time and build a list of times from start to end in steps of one minute:               start = AbsoluteTime[{2012, 3, 19, 23, 0, 0}];     end = AbsoluteTime[{2012, 3, 20, 0, 0, 0}];     time = Table[start + 60*i, {i, 0, (end - start)/60}];      For my convenience I reshuffled my data:               d3 = Table[{data[[i, 6]], data[[i, 2]], data[[i, 3]], data[[i, 4]],         data[[i, 5]]}, {i, Length[data]}];      and checked which values in the 'time' list are taken by the time of my events:               doubles =       Flatten[Table[Position[time, d3[[All, 1]][[i]]], {i, Length[d3]}]];      Lastly, I inserted my events in the 'time' list:               d4 = ReplacePart[time,         Table[doubles[[i]] -> d3[[i]], {i, Length[d3]}]];      I can then generate my frames:               frames = Animate[If[Length[d4[[i]]] > 1,       Graphics[{         White,         Rectangle[{10, 43}, {13, 46}],         Red, Disk[d4[[i, {3, 2}]], d4[[i, 5]]/10],         Black,          Text[Style[           DateString[            DateList[d4[[i, 1]]], {"Day", " ", "MonthNameShort", " ",              "Year", "   ", "Hour", ":", "Minute"}],            FontFamily -> "Helvetica", FontSize -> 20], {10.8, 45.85}]         }],       Graphics[{         White,         Rectangle[{10, 43}, {13, 46}],         Black,          Text[Style[           DateString[            DateList[d4[[i]]], {"Day", " ", "MonthNameShort", " ", "Year",              "   ", "Hour", ":", "Minute"}], FontFamily -> "Helvetica",            FontSize -> 20], {10.8, 45.85}]         }]       ], {i, Range[Length[d4]]}, AnimationRate -> 20];          Export["animation.gif", frames, "DisplayDurations" -> .03]      ![enter image description here](http://i.stack.imgur.com/ny6yA.gif) However, what I would like to achieve is a more complicated animation: once an event is plotted at the right time I would like to then present it also on subsequent frames, but slowly dimming (decreasing Opacity) for a specified time window. At the end of the animation all events would be thus dimmed and superimposed. I simplified a lot the example I provided, real data might span over several days and contain hundreds of events.


title: How do I prevent fonts sizes and line weights from scaling in exported graphics?

text: It's common to export graphics from _Mathematica_ that are subsequently scaled to various sizes that cannot (at least not conveniently) be anticipated. This is problematic in cases where (as is common) fonts and line weights need to fixed (e.g. throughout a document or presentation, or simply to prevent a figure from looking ridiculous). For example, if the default options for fonts and line weights are satisfactory, then               Plot[{Sin[x], Cos[5 x]}, {x, 0, 2 Pi}]      will produce a figure with correct font sizes an line weights ![enter image description here](http://i.stack.imgur.com/OAfFJ.png) and scaling this figure within _Mathematica_ (e.g. by dragging the resize frame) will preserve these font sizes and line weights: ![enter image description here](http://i.stack.imgur.com/f4hTI.png) However, if I export the original graphic in a resizable format (i.e., choosing "Save Graphic As..." and specifying a PDF "Vector Representation", which, as far as I can tell, is the only form suitable for subsequent resizing), the fonts and line weights scale with the graphic ![enter image description here](http://i.stack.imgur.com/5lfdw.png) which is not the desired result. Is there a way to generate and export graphics so that font sizes and line weights are preserved when the exported graphic is resized?


title: What are the Slot Names in a Dataset?

text: I have a dataset which are keyed on `{"Item", "Hour of Day", "Value"}.` In the examples, I noticed that it is possible to apply functions using such as               Select[(#a > 1 &)]      But what would the slot name be for my string values above? Is there a way to interrogate a dataset for its slots? Should I simply avoid the issue and rename them if I wish to perform such operations?


title: Nested list in PairedBarChart

text: I have a dataset consisting of 2 different parameters (`x` and `y`), that are evaluated for 3 different values of parameter `p` and within a set for `p`, there are, say, two groups (`G1` and `G2`, eventually to `Gn`) with again three values for a parameter q. `G1`, `G2` need to be displayed with the same `ColorFunction`. How do I display this using `PairedBarChart`? I believe this is a nested list, but `PairedBarChart` only seems to take two (`x` and `y`) _m-by-n_ (max number of dimensions = 2) matrices? Appreciate your hints! UPDATE: SAMPLE DATA BELOW and extra level added in description above. Data should be interpreted as data left = x, dataright = y. In both, there is three groups p1, p2, p3 each consisting of two lists (G1 and G2), which in turn each consist of {q1,q2,q3}.               dataleft = {{{22.1801, 30.9241, 27.3873}, {30.0898, 42.7793, 38.6847}, {81.5488, 164.131, 97.6132}}, {{28.5354, 30.1192, 26.7762}, {26.7111,27.5938, 25.8865}, {72.1467,91.9632, 53.7431}}};     dataright (*here identical to left, just for the idea*) = {{{22.1801, 30.9241, 27.3873},{30.0898, 42.7793, 38.6847}, {81.5488,164.131, 97.6132}}, {{28.5354, 30.1192, 26.7762}, {26.7111, 27.5938, 25.8865}, {72.1467, 91.9632, 53.7431}}};


title: Numerical Optimization Methods

text: I am curious if any one has comments on "specific characteristics" of a problem that will deem it to be best solved by a specific optimization method such as `SimulatedAnnealing`, `Random Search`, or `Diferential Evolution`, etc. **Edit** : I am familiar with the majority of the `Mathematica` resources which has some useful comments such as:`Random search` requires that the objective function be locally continuous, `DifferentialEvolution` is more suitable for discrete optimization problems since it needs a large gene pool, etc. I wanted a discussion expanding that knowledge based on peoples' experience on when they found one method to be more beneficial than other based on the problem characteristics such as size of solution space, non- linearity, processing speed(time), rate of convergence (iterations), etc. Ps. Thanks for the resources.


title: How can I get the number of slots in Function?

text: Suppose that I define               f = Function[#1 + #2];      And I want to define a new function, `argsNum`, so that it returns a number of arguments of input function:               argsNum[f]      > >     2 >   since `f` has 2 slots, `#1` and `#2`. I found the good Q&A, Function that counts the number of arguments of other functions but it does not work on functions of form like `Function[#1 + #2]` or etc. It works on `Function[{x, y}, x + y]`. But I need a function that works on slots. How can I modify the function in above link or define a new function which also works on slots?


title: Simplification of (Co)sine of a sum

text: I have a huge expression with (Co)Sine of a sum like Cos[[Theta] - 2 [Phi]] (after using \Simplify). I wanted to know if it exists a function which forces Mathematica to express the result in terms of multiplication of (Co)Sine instead of (Co)Sine of a sum ?


title: Why doesn't Mathematica use uniform criteria for validating Options?

text: Plot[Sin[x], {x, 0, 1}, pp -> 0]      Gives as expected: > Plot::optx: Unknown option pp in Plot[Sin[x],{x,0,1},pp->0]. >> However:               Import["http://i.stack.imgur.com/JrxBD.png", pp -> "HSB"]      returns no error. Is there a language design reason for this, or is it just lack of standards?


title: How to programattically create a hyperlink to a local html file?

text: I want to cause a button to open a local html file using the default web browser. When I use:               Hyperlink["Play","myfile.html"]      Clicking on the link opens the html file in a notebook. If I use               Hyperlink["Play","http://myfile.html"]      My browser (FireFox) opens and fails looking for "www.myfile.html". I know this may be trivial but can anyone help with this?


title: Quit Kernel Shortcut

text: How could I set a Keyboard shortcut for the Quit Kernel -> Local command? I find really disappointing to open the Evaluation menu any time!


title: How can I get better tick spacing for multiple ListLogPlots?

text: I am using `Show` with `PlotRange -> All` to overplot multiple `ListLogLogPlot`. The resulting plot has axis ticks that are unevenly clustered toward the top of the y-axis. (right image) When I use `Show` with `PlotRange -> All` to overplot the same data using `ListPlot`, the resulting plot has evenly spaced ticks along the y-axis (left image). ![enter image description here](http://i.stack.imgur.com/XocXU.png) How can I use `Show` with `PlotRange -> All` to overplot `ListLogLogPlot` and get even axis ticks along the y-axis? I can force a fix by specifying the entire range with `PlotRange` in the first plot, but in general I will not know ahead of time the plot ranges and would like to avoid editing the plots themselves.


title: Blank Output for Text Recognition

text: Please Anyone help Why am I getting Blank Output for TextRecognization for the this Image Is it because the size of image.??? Please help Neither am getting output for this code               x = Import["http://i.stack.imgur.com/RbqrD.jpg"];     TextRecognize[x]      Nor for this one:               x = Import["http://i.stack.imgur.com/RbqrD.jpg"];     img = ImagePartition[x, {50, 69}];     MatrixForm[img];     p=img[[4,1]];     TextRecognize[p]      ![enter image description here](http://i.stack.imgur.com/RbqrD.jpg)


title: How can I fill in a matrix at every iteration of a Do loop?

text: I have a matrix whose dimensions are 26x26x3. For my assignment I have written a program which is using a `Do` loop (maxx=maxy=10,maxz=2):                Do[       n = 0;       h=0.4;       k = Table[              If[a <= #1 <= a + h && b <= #2 <= b + h && c <= #3 <= c + h & @@ pts[[w, t]], 1, 0],               {w, 1, Length[pts]},               {t, 1, Length[pts[[w]]]}           ];       pls = Plus @@@ k;       For[i = 1, i <= Length[pls], i++, If[pls[[i]] > 0, n++]];       n,        {a, 1, maxx, h}, {b, 1, maxy, h}, {c, 1, maxz, h}     ]      At every iteration I get a new value for n and I have to assign it to the correct position of my matrix as efficiently and fast as possible. I don't have a counter. So, I am a bit confused. How can I solve this issue? On the other hand, can I create a matrix by saving n at the end of the `Do` loop? Any help is appreciated.


title: Wavelength, wavenumber, energy and frequency in a ruler

text: I would like to generate set of four axis relating wavelength, wavenumber, energy and frequency in an arbitrary range. Like in this image but without the labels such as "RADAR". ![example of ruler](http://i.stack.imgur.com/pd0oF.gif) The selection of the nice numbers could be done similar to plots with two x-axis with different units but without an ordinate "y axis".               range = {Quantity[0.1, "THz"], Quantity[10, "THz"]};     ticksmeV = FindDivisions[QuantityMagnitude@UnitConvert[Quantity["Planck's constant"] #, "meV"] & /@ range, 10]      > {0, 5, 10, 15, 20, 25, 30, 35, 40, 45} and so on. But I'm not clear how to put this in a graphic with correct scaling. What would be the best way to do this both in linear and logarithmic scaling? **Edit** Based in the answer by @ubpdqn I have done this:               rangeTHz = Quantity[{0.1,10}, "THz"];     rangemeV = UnitConvert[Quantity["Planck's constant"] #, "meV"] & /@ rangeTHz;     range\[Lambda] =  N@UnitConvert[Quantity["Speed of Light"]/#, "micrometer"] & /@ rangeTHz     rangeWn = N@UnitConvert[#/Quantity["Speed of Light"], "Wavenumbers"] & /@ rangeTHz     TableForm@Table[HorizontalGauge[Null, k, GaugeFrameStyle -> Transparent,  ScalePadding -> {0, 0}, ScaleDivisions -> 10, GaugeMarkers -> None, GaugeLabels -> Placed[QuantityUnit@First@k, Top], ImageSize -> 600, GaugeFaceStyle -> Transparent, LabelStyle -> 16,  AspectRatio -> 1/15], {k, {rangeTHz, rangemeV, range\[Lambda],      rangeWn}}]      > ![Mathematica graphics](http://i.stack.imgur.com/syGMH.png) but the problem is that the Wavelength scaling should be inverted. How can I fix that?


title: Preparing 2d plots for publication

text: When it comes to plotting a data my general attitude is to avoid post processing (say with adobe illustrator) as much as possible. To follow this strategy I would like to prepare **publication-ready** pdf plots with _Mathematica_. Here are my requirements   * Plotted lines should have width of **exactly 1pt**.    * The same should be true for the lines forming axes, frames, ticks.    * The ticks have a commensurate length. I find it is optically pleasing to have **major ticks of 4pt** lengths.   * The graph should have a dimension of one column, i.e. ~ **8.5cm** or 240pt.   * All the tick labels, axes labels, etc. should be done with **12pt Helvetica**.   * No white background. One can argue about the art value of this setup. I, personally, find it is a good compromise between the visibility and simplicity. I remember these numbers and keep them the same across different programs and publications. I tried to develop very easy solution that can be kept in mind. Since there is a known problem with tick length (it cannon be set explicitly) I decided to adjust the rest of parameters to this dimension. At first step I am just plotting the function               fx[x_] := 1/(Exp[-x - 7] + 1) + 1/(Exp[x - 7] + 1) - 1      with default settings and nice blue-apple color               blue = RGBColor[17.6/100, 41.6/100, 63.1/100];     u = Plot[fx[x], {x, -15, 15},            PlotRange -> All, AxesLabel -> {"x", "fx(x)"},            PlotStyle -> Directive[AbsoluteThickness[0.5], blue]]      The absolute thickness was set to 0.5pt because I am going to enlarge the graph on the second step:               Show[u,        AxesStyle -> Directive[AbsoluteThickness[0.5], 6, FontFamily -> "Helvetica"],        ImageSize -> 120]     Export[FileNameJoin[{$UserDocumentsDirectory, "u1.pdf"}], %]      As you see the graph has now the horizontal dimension of 120pt, i.e. 50% of the desired result. But I tolerate this since it is a vector graphics. All lines have the right thickness of 50%$\times$1pt=0.5pt and major ticks are of 50%$\times$4pt=2pt. The font sizes are also right: 50%$\times$12pt=6pt. The only problem in present approach is wrong placement of some tick labels. Numbers -10 and 10 are vertically misaligned: ![enter image description here](http://i.stack.imgur.com/ti7op.png) I would appreciate any help on this particular issue, or, on the production of publication ready graphs in general. I explicitly decline possibilities of drawing ticks manually, using additional packages or post processing. **Please, feel free to criticise my artistic style.** **Update** I would like to make some comments on my approach. The whole idea comes from the fact that it is unacceptable for me to use additional packages for very simple plots. At the same time I have **very modest requirements** on graphics parameters for visual appeal. Crucial parameters for me are the lines' thickness and the ticks' length. Since there is no simple way to set the ticks' length explicitly I am forced to rescale the image. That is, the image of 240pt is required, however, it is prepared at 120pt. Everything would be perfect provided ticks' labels are properly placed.


title: Saving a notebook without output lines

text: Is it possible to change the way Mathematica saves so that `Out[]` lines are never included? I have a `.nb` file that processes a lot of data, and displays most of it as standard output. These graphs, tables, and intensity plots almost double the size of the file. I'd like to easily save these files in a smaller form and also prevent accidentally sending confidential results to users outside my company or not under an NDA. That is, of course, without using `Cell -> Delete All Output` before each save. I can't be expected to remember to do that all the time! :-P


title: How to sort cells in a notebook based on cell tags?

text: Suppose I have a notebook with cells tagged with both numbers and words with numbers always list first, and some cells without cell tags e.g.:               Notebook[{     Cell[ ..., CellTags->{"1","cat"}],     Cell[ ..., CellTags->{"2","dog"}],     ...     Cell[ ...],     Cell[ ..., CellTags->{"7","cow"}],     ...     }, notebook options ...]      What is the easiest way to sort the cells based on 1) cell tag numbers, i.e. the first element in the cell tag list; and 2) cell tag words, i.e. the second element in the cell tag list? Note that there could be additional tags but the first and second tags are always number and single word. Note also there there is unlikely to be grouped cells (none at this stage), although a solution that took cell grouping into account and rendered a sorted ungrouped answer would be fine. I want a fast way to sort a notebook and render the newly sorted form. I'm thinking ideally I'd like a palette button for this.


title: How to sort Table/Matrix including legend(Labellings)

text: I want to sort table including its legend for graph I have table similar to               M1   M2   M3      1     5    2     3     1    4      4     2   -10     5     7    11     6    -2    1      I want the labellings `M1`, `M2` and `M3` to move with the first row of numbers while sorting by row basis.                   M1   M3   M2          1     2    5         ...........          ...........      OK The code is below               (* Initial matrix *)     h = {{M1, M2, M3}, {1, 5, 2}, {3, 1, 4}, {4, 2, -10}, {7, 5, 11}, {6, -2, 1}}      then sorting by basis `h1 = Sort /@ h` gives                M1,   M2,  M3      1,    2,  5      1,    3,  4      -10,  2,  4      5,    7,  11      -2,   1,  6      I want `M1`, `M2` and `M3` to be together with the fist row of numerical values since they are labellings attached to the first numerical values of each column AS               M1   M3   M2      1     2    5      ..... .... In that way it will be easy to put the legend in graphs


title: Ploting a 3D vector field using Manipulate, VectorPlot3D and NDSolve

text: My aim is to plot a vector field of the following system with a few trajectories: $$r'(t)=i-l.r(t)-\text{ux}. r(t). x(t)-\text{uy}. r(t). y(t) \\\ x'(t)=\text{ex}. \text{ux}. r(t). x(t)-\text{mx}. x(t)\\\y'(t)=\text{ey}.\text{uy}. r(t). y(t)-\text{my}. y(t)$$ $i,l,ux,uy,mx,my,ex,ey$ are parameters. Here is what I have managed to do so far:               Manipulate[       ParametricPlot3D[         Evaluate[           {r[t], x[t], y[t]} /.              NDSolve[{               r'[t] == i - l*r[t] - ux*r[t]*x[t] - uy*r[t]*y[t],                x'[t] == -mx*x[t] + ex*ux*r[t]*x[t],                y'[t] == -my*y[t] + ey*uy*r[t]*y[t],                r[0] == 1, x[0] == 1, y[0] == 1},                {r, x, y}, {t, 0, 100000},                MaxSteps -> Infinity,                AccuracyGoal -> 10]],          {t, 0, 10000},          PlotRange -> Full,          AxesLabel -> {"r(t)", "x(t)", "y(t)"},          PlotStyle -> {Green, Thickness[0.01]}],        {i, 0, 100},        {l, 0, 1},        {ux, 0, 1},        {uy, 0, 1},        {mx, 0, 1},        {my, 0, 1},        {ex, 0, 1},        {ey, 0, 1}]      This plot one trajectory and it works fine (although you might not think so looking at it but it is due to the equations. Then when I tried to plot the vector field alone and I got stuck.I do not know what is going wrong:               Manipulate[       VectorPlot3D[         Evaluate[           {r[t], x[t], y[t]} /.              NDSolve[{               r'[t] == i - l*r[t] - ux*r[t]*x[t] - uy*r[t]*y[t],                x'[t] == -mx*x[t] + ex*ux*r[t]*x[t],                y'[t] == -my*y[t] + ey*uy*r[t]*y[t],                r[0] == 1, x[0] == 1, y[0] == 1},                {r, x, y}, {t, 0, 100000},                MaxSteps -> Infinity,                AccuracyGoal -> 10]],          {r[t], 0, 100}, {x[t], 0, 100}, {y[t], 0, 100},          VectorColorFunction -> "DeepSeaColors"],        {i, 0, 100},        {l, 0, 1},        {ux, 0, 1},        {uy, 0, 1},        {mx, 0, 1},        {my, 0, 1},        {ex, 0, 1},        {ey, 0, 1}]      The next thing to do was to plot both the vector field and trajectories on the same plot, I have not tried as I could manage to plot the vector field, so if you can give me any piece of advice about this too, I would be extremely grateul. For 2D, without using `Manipulate`, I used `Show` but I guess it will not work if I use `Manipulate` as I need to make the parameters vary simultaneously for the vector field and the trajectories. (Do not expect any fancy trajectories with these equations, you can change them to have nicer things, I just would like the general way how plotting this for any system of three equations). EDIT: THE TWO ANSWERS BELOW GIVE DIFFERENT THINGS SO I DO NOT KNOW WHAT TO DO.


title: Speeding up export of a matrix to a dat file

text: I'm trying to export a 1000*100 matrix of numbers to a `.dat` file using `Export` (I want the numbers to be separated by a tab) and it's very slow, it takes several minutes, whereas when I export to an Excel file it takes a few seconds. Is there a way to speed this up ? Also how can I control the number of decimals I want to export ? **Edit**   I found the issue, this happens when I export my dat file on a network drive (at work), the export to an Excel file and a dat file must be implemented in different ways that produce different behaviours. Thank you though for the different interesting answers.


title: String replacement of special characters

text: The function               StringReplace["y\\/G", {"|<" -> "K", "\/" -> "V", "]" -> "J",        "><" -> "X", "_" -> "", "." -> "", "," -> "", "'" -> ""}]      fails to provide the expected answer `"y\VG"` and instead returns `"y\/G"` due to the unusual (to me) way Mathematica handles strings in order to allow for symbols and images in strings. How would one do a string replace where the symbols are literally replaced, in the order the string is shown?


title: Ordering vertices with minimum Edge Crossing in Circular Graphs

text: Weighted and sorted _Mathematica_ circular graphs are shown below. My question is how to reorder the vertices in such a way that they have **minimum cuts** (intersection of edges) while keeping the circular graph in shape. Some useful links to `GraphPlot`, circular graph and `EdgeRenderingFunction` for edge thickness from Mathematica.StackExchange and StackOverflow:   * Ordering vertices in `GraphPlot`   * Removing edge weights from a graph   * Label edges with their weights   * Graph layout that reflects edge weights Mathematica code:               (*vertex shape function with labels*)     options =        Sequence[Method -> "CircularEmbedding", VertexLabeling -> True,         EdgeLabeling -> False,        EdgeRenderingFunction -> ({Text[Style[#3, 15], Mean[#1]],            Blue, AbsoluteThickness[0.8 + #3/5],            Arrowheads[0.02 + #3/170],            Arrow[#1, 0.075]} &), ImageSize -> 200];      Default _Mathematica_ circular graph arranges vertices differently.               (*default mathematica circular graph*)     connections = {{1 -> 5, 1}, {4 -> 3, 3.6}, {6 -> 8, 1}, {2 -> 4,          2}, {2 -> 5, 2.5}, {5 -> 4, 0.9}, {7 -> 8, 2}, {3 -> 8,          1}, {8 -> 2, 1}};     gp1 = GraphPlot[connections, options];      So, we need to sort circular graph vertices to start calculating minumum cut (intersecting edges).               (*sorted mathematica circular graph*)     Needs["Combinatorica`"];     sortedVertices =        Sort[Union[         Flatten[{connections[[All, 1, 1]], connections[[All, 1, 2]]}]]];     sortedConnections = Table[        sortedVertices[[i]] ->          Partition[Flatten[CircularEmbedding[Length[sortedVertices]]], 2][[i]],        {i, Length[sortedVertices]}];     gp2 = GraphPlot[connections, options,         VertexCoordinateRules -> sortedConnections];     (*show two graphs*)     Row[{gp1, gp2}]      ![Mathematica graphics](http://i.stack.imgur.com/5MIRT.png) The question is how the above code can be rearranged in such a way that `GraphPlot` has **minimum cuts** (intersection of edges) while keeping the circular graph in shape. The vertex points order may be changed but not the number of connections or directions.


title: Detecting spikes by shrinking WaveletPacket basis using a specific threshold

text: Last time, I asked how I can use the command `DiscreteWaveletPacketTransform[data, filter, 0]` for spike detection and I got answers mostly based on an automatically defined threshold. In my case _it is crucial to first define a threshold to distinguish between the real and spurious data_ , so built-in functions are not my favorites. I developed my own version of code but as I use a filter like Haar, there would be no difference between a spike on point 19 or 20, as this filter works inherently with pairs of numbers. Once again, in Mathematica version 7 using the above command I had no problem! I read the links given already but no use. That would be great if someone can enhance my code such that it can differentiate between two consecutive spikes.               data = Table[Sin[x] + Random[], {x, 1, 10, 0.1}]     data[[20]] = 100; data[[40]] = 100;      ![enter image description here](http://i.stack.imgur.com/M09Gz.png)               dwt = DiscreteWaveletTransform[data, HaarWavelet[], 1];     Sigma = Mean[ Abs[dwt[[1, 2]] - Mean[dwt[[1, 2]]]]]/0.6745;     Lambda = N[Sqrt[2 Log[Length[dwt[[1, 2]]]]]];     thresh = Lambda*Sigma;     shr[c_, wind_] := If[Abs[#] >= thresh, 1, 0] & /@ c;     dwtS = WaveletMapIndexed[shr, dwt]     ListLinePlot[InverseWaveletTransform[dwtS, HaarWavelet[]]]      ![enter image description here](http://i.stack.imgur.com/jG4Dh.png)


title: What's a good style for inheriting Options[] of built-in function?

text: Options[myPlot] = Options[Plot];     myPlot[args___] := ...      When defining a "wrapper" function like the above, I'd like it to inherit the `System`` function's options. Should I use `Options[myPlot] = Options[Plot]` or `Options[myPlot] := Options[Plot]`?


title: How to print without having newline added automatically at the end?

text: Print["first part of the result", DateString[]]        Print["addition to the result", DateString[]]      will add a newline character at the end of line automatically for each `Print[]`. But I'd like the two strings to be shown on the same line. How can I do this?


title: How to plot a coalition game?

text: Consider a game of a function $v$ which has \begin{align} v(1) & \geq 1\\\ v(2) & \geq 0\\\ v(3) & \geq 1\\\ v(1,2) &\geq 4\\\ v(1,3) &\geq 3\\\ v(2,3) &\geq 5\\\ v(1,2,3) &=8 \end{align} How can I plot such a function in Mathematica (preferably in 2D). Should one use `RegionPlot`or `Graphics`? ![The core plotted](http://i.stack.imgur.com/Ujkk1.png)


title: How to invert an integral equation

text: There have been numerous times when I've needed to invert an integral equation, i.e. I have something like $$f(x) = g_1(x)\int_{0}^x g_2(x') dx'$$ for arbitrary functions $g_1$ and $g_2$, and I would like to find $x$ for a given $f$. The way I've gotten around this is just making some sort of table of f(x) and x with spacing up to some required precision. Is there a more efficient method of doing it (numerically or analytically)? When I try to use `NSolve[ f(x) == a, x ]` mathematica complains `NIntegrate::nlim: x = x is not a valid limit of integration.`


title: How can I create a list of functions?

text: Can anyone tell me, how to create a list of functions? I've tried the following code, but it doesn't work.               For[i = 0, i < 5, i++,     {       functionList[[i]][t_]:=(t*i*i)     }]          functionList[[3]][10]      Of course, this construction is just an example.


title: Why does FourierTransform[] converge while same integral manually written does not?

text: I'm studying the quantum mechanics of an infinite square well from a computational standpoint. My eigenfunctions are defined as $u_n(x)=\sqrt{2/L}\sin\left(n\pi x/L\right),\quad 0 \le x \le L, \quad n=1,2,3,\dots$ and zero outside of the $[0,L]$ interval. I'd like to transform the wave function from position domain to the momentum domain. My book says that this is achieved by writing the Fourier transform of $u_n(x)$: $\phi_n(k)=\frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} u_n(x)e^{-i k x}dx$               ClearAll["Global`*"];     L = 1;     u[n_, x_] := Sqrt[2/L] Sin[n π x]     φ[n_, k_] := Assuming[{n ∈ Integers, {k, x} ∈ Reals},                     1/(Sqrt[2π]) Integrate[u[n, x] Exp[-I k x], {x, -∞, ∞}]]      > Integrate::idiv: Integral of E^(-I k x) Sin[n π x] does not converge on > {-∞,∞}. >> If I, though, use `FourierTransform[]`, I get the result:               FourierTransform[u[n, x], x, k, FourierParameters -> {0, -1}]      > -I Sqrt[π] DiracDelta[k - n π] + I Sqrt[π] DiracDelta[k + n π] But my book says that the result should be: $\phi_n(k) = \sqrt{\pi L} n \frac{1-(-1)^n e^{-i L k}}{(n\pi -L k)(n\pi + Lk)}$ I tried to get _Mathematica_ to fully simplify the output of `FourierTransform[]`, but I/it couldn't. So my questions are:   1. Why does the integral not converge when written manually but it does converge when it is being calculated via `FourierTransform[]` ?   2. How could I prove that the output of `FourierTransform[]` is equivalent to the formula that is written in my book for $\phi_n(k)$ ?


title: Share experiences, preferably the surprising ones, with using ItoProcess

text: Can people please share their experiences, preferably the surprising ones, with using ItoProcess? I am a big fan of ItoProcess and have already used it for several finance- related tasks, though I suspect that I'm just seeing the tip of the iceberg. I'll kick things off by supplying one answer about a bug that must be worked around before you can use ItoProcess with a correlation matrix. Wolfram Support have responded to my bug report by saying it will be fixed 'in a future release of Mathematica'.


title: ClearAll just for current notebook

text: So in my search to fine tune _Mathematica_ to what works for me, I found a nice setting that helps separate variable declaration between notebooks. Under Global Preferences, searching for CellContext and changing from "Global'*" to Notebook does this. Sweet, but now I am having trouble clearing all the variables. `ClearAll["Global```*"]` no longer works, and so I figured, since that's the setting I changed, maybe it would now be `ClearAll[Notebook]`. However, this doesn't work either and warns that `Notebook` is protected. Maybe there is a better method of operation instead of the path I'm attempting to go down. I use _Mathematica_ to do all of my Physics homework in; between each problem I usually do a `ClearAll` so I'm not contaminating possible variables between problems with wrong values.


title: N-level exponential moving average

text: If anyone knows how to write a mathematica code for n-level exponential moving average or someone has written already the code ?


title: Rising Recursion Relationships

text: Lets say I want to compute the following function in mathematica: $G[n,k]=G[n+1,k-1] + G[n+2,k-2]$ where I know that $G[n,0]=n$ and $G[n,1]=n^2$. So, for example, $G[3,2]=G[4,1]+G[5,0]=4^2+5$ or, less trivially, $G[5,4]=G[6,3]+G[7,2]=(G[7,2]+G[8,1])+(G[8,1]+G[9,0])=((G[8,1]+G[9,0])+G[8,1])+(G[8,1]+G[9,0])= 3G[8,1]+2G[9,0]$ So I attempt it with the following code               RecurrenceTable[{s1[n, k] == s1[n + 1, k - 1] - s1[n + 2, k - 2],         s1[r, 1] == r, s1[r, 0] == r^2}, s1, {n, 2, 6}, {k, 2, 4}] // Grid      However it spits out lots of error messages relating to functions being called with two variables when only one is expected.


title: OpenCL vs. CUDA with Mathematica

text: I am thinking about using GPU programming with Mathematica using a MacBook Pro with a NVIDIA GPU. At this page, the Mathematica documentation says "Programming OpenCL in the Wolfram Language is simple since the user need not write C wrapper code -- which can be quite verbose, difficult to understand, and hard to debug. Using _OpenCLLink_ also guarantees compatibility as new versions of the standard are released." So what advantages might there be to programming in CUDA instead of OpenCL?


title: Finding all sets of elements with two common elements in a large dataset

text: I have a very large network of atoms ($\approx 10^6$ atoms) with fixed positions that resemble a cellular structure: ![enter image description here](http://i.stack.imgur.com/5UH6C.jpg) I have two files including:   * fixed locations of each atom   * set of points which makes each cell. The first one is like:                1 1.72907 3.50783      2 3.89771 506.561      3 514.767 4.35252      ...      The second dataset has $\approx 5 \times 10^5$ rows (but size of each row is different). For example:               {1,3,485,969,970,971,1452}     {1,487,488,970,972}     {1, 485, 486, 487, 966, 968}     {2,99706,99707,99708,99709,100190,100191}     {2,99225,99226,99227,99708,99710,99711}     {2, 99222, 99223, 99224, 99225, 99706}     ...      I need to find out all sets which have exactly two elements in common ($=$ two cells share an edge or in other words, are neighbors). I already have a code but it's inefficient because it compares the sets line by line. Here's my code ($n$ is number of rows):                ParallelEvaluate[file = OpenWrite["RN" <> ToString[$KernelID] <> ".dat"]]               ParallelDo[      WriteString[file, i, " ",      Flatten[Last[Reap[Do[If[Length[Intersection[ring[[i]], ring[[j]]]] == 2,       Sow[j]], {j, 1, n}]]]], "\n"]      , {i, 1, n}];           ParallelEvaluate[Close@file];      I find intersection length of a specific set $i$ (`ring[[i]]`) with all other sets and if it is equal to two, I write the set number in a file. Is there anyway to improve efficiency of this code? ## Update I have an alternative solution without using `Intersection` and with only one loop, as follows:                ring = ReadList["rings.dat", Number, RecordLists -> True];      ParallelEvaluate[file = OpenWrite["RN" <> ToString[$KernelID] <> ".dat"]]               ParallelDo[      RN = Complement[First/@Tally[Flatten[First /@ Position[ring, #] & /@ ring[[i]]]],         {i}];      WriteString[file, i, " ", RN ,"\n"]      , {i, 1, n}];           ParallelEvaluate[Close@file];      But it seems it is not that much better than previous one.


title: CDF Player crashes on start-up Ubuntu 12.04 LTE

text: I'm not sure if this is the right place to ask this, if not, please redirect me. I am trying to get Mathematica's CDF player running on Ubuntu 12.04 LTE (Precise Pangolin). This should be fairly standard and non-problematic. However, the CDF player keeps on crashing right after start-up. I Googled this and couldn't find any related thread. **EDIT** : here is a terminal output of what is going on: ![screenshot of terminal window](http://i.stack.imgur.com/kXgN4.png)


title: Simplifying a time-series segmentation Query

text: This query segments a time-series and filters out dropout frames. Can it be simplified - ie, made more readable?               segmentationQuery =       Query[SplitBy[#, NumberQ[#"POR_X"] &] &  ] /*        Query[Merge[Join] /* Key[True], GroupBy[NumberQ[#"POR_X"] &]]      (Note there's no `SplitBy` operator form in 10.0.0. hence using functional form.) The `Slot` "POR_X" is used twice: in `SplitBy` and `GroupBy` \- this is not pleasing. Using only `GroupBy` in the top-most subquery yields only 2 groups of data (signal and blank) but all the numeric frames are merged (not the intended behavior). This fragment, extracted from eye-tracking dataset, illustrates droputs of variable duration and number of rows:               data = {<|"Time" -> 0.033452, "POR_X" -> 613.76,        "POR_Y" -> 424.74|>, <|"Time" -> 0.066747, "POR_X" -> 611.84,        "POR_Y" -> 424.84|>, <|"Time" -> 0.100124, "POR_X" -> 610.53,        "POR_Y" -> 420.11|>, <|"Time" -> 0.133515, "POR_X" -> 605.95,        "POR_Y" -> 421.18|>, <|"Time" -> 2.01096, "POR_X" -> "",        "POR_Y" -> ""|>, <|"Time" -> 2.04425, "POR_X" -> "",        "POR_Y" -> ""|>, <|"Time" -> 2.07772, "POR_X" -> "",        "POR_Y" -> ""|>, <|"Time" -> 2.24451, "POR_X" -> 412.47,        "POR_Y" -> 805.92|>, <|"Time" -> 2.27792, "POR_X" -> 518.11,        "POR_Y" -> 652.38|>} //Dataset;      ![enter image description here](http://i.stack.imgur.com/3wib1.png)               data[segmentationQuery][All, Dataset] // Normal      ![enter image description here](http://i.stack.imgur.com/nNOzg.png)


title: Making Monte Carlo simulation with ParallelTable

text: I would like to to MonteCarlo simulations of various regressions - basically, doing OLS under various conditions to test approaches. On my macpro 2x 2.8 GHz quad core Xeon, 32 Gb RAM DDR2 @ 667 Mhz, the baseline is 56 seconds for 10'000 lines and 6'000 iterations.               ols = {};     beta = {1, 2, 3};     size = 10000;     iterations = 6000;     out = AbsoluteTiming[        Table[x1 =           Table[{RandomVariate[NormalDistribution[0, 1]],             RandomVariate[NormalDistribution[0, 1]]^2,             RandomVariate[NormalDistribution[0, 1]]}, {size}];         u1 = Table[RandomVariate[NormalDistribution[0, 1]], {size}];         y1 = x1.beta + u1;         LeastSquares[x1, y1], {iterations}]];     out[[1]]     out[[2]] // Dimensions          51.895992          {6000, 3}      Simply by switching to ParallelTable, I get down to about 12.5 seconds After reading Transferring a large amount of data in parallel calculations, I updated my code to use the suggested modifications :   * a modified MemberQ that doesn't do the unpacking (goes down to 12.38 seconds)   * Method-> "CoarsestGrained" (goes down to 11.9 seconds)   * both (goes down to 11.9 seconds)               $IterationLimit = 100000;     out = AbsoluteTiming@withModifiedMemberQ@ParallelTable[     (...)          , {iterations}, Method -> "CoarsestGrained"];      I am wondering what I should do to for further performance gains. I'd like to do 10'000 lines and 10'000 iterations in less than 10 seconds if possible.


title: How to make rules for changing parameters

text: I have one boring problem with changing parameters in printing output. If I have equation                   eq = Plus[Times[a1,Derivative[2,0][q2][x,y]],Times[a2,Derivative[3,1][q1][x,y]]];      I want to replace all derivatives with new variables, for example this                     Derivative[2, 0][q2][x, y]      I want to replace it with $C_{\mathrm{q2}}^{2,0}$ and for all of them on the same way to get `eq` output automatically in this form $\mathrm{a1}\,C_{\mathrm{q2}}^{2,0}+\mathrm{a2}\,C_{\mathrm{q1}}^{3,1}$


title: Is it possible to snip a certain number of pixels from a specified side of an image, without specifying the image's final width and height?

text: It seems that `ImageCrop` allows one to specify the _final_ size of the image. For example, `ImageCrop[image, size, spec]` crops image `image` to size `size`, and one can specify which side of the image the pixels should be taken from, using `spec`. But, what if I don't know the final size `size` of the image? What if I just want to snip 10 pixels from the right side of the image? I might want to do this for a series of images, whose sizes are not known (at least immediately).


title: kernel shuts down during listplot

text: In at least the following situations, I have experienced that the kernel has shut down during evaluation. The thing is that there is no message at all when it shuts down.               SetDirectory[NotebookDirectory[]];     temp = Partition[Flatten[Import["temp.dat", "Table"]], 3];     ResetDirectory[];          ListContourPlot[temp]      P.S. The file `temp.dat` is in the following link: https://dl.dropboxusercontent.com/u/7611247/temp.dat. **Why has the kernel shut down without any warning message? What can I check or how can I fix it?**


title: Improve performance and style of solution to Project Euler #32

text: Since I'm fairly new to Mathematica, I'm trying to learn better ways to improve my coding skills so I've turned to Project Euler and this site to speed up my learning pace. Anyways, I was trying to solve problem 32 on the project Euler forum and came up with the following code               PanDigital[n_, m_] := Sort[Flatten[IntegerDigits /@ {n, m, n m}]] == Range[9];          Module[{k}, k = Select[Flatten[Table[{i j, PanDigital[i, j]}, {i, 2, 9}, {j, 1234,            9876}] ~Join~ Table[{i j, PanDigital[i, j]}, {i, 12, 98}, {j, 123, 987}],           1], #[[2]] == True &]; k = Union@Select[Flatten[k], IntegerQ] // Total] // Timing      > {2.620817, 45228} By the way here is the question: > We shall say that an n-digit number is pandigital if it makes use of all the > digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 > through 5 pandigital. > > The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing > multiplicand, multiplier, and product is 1 through 9 pandigital. > > Find the sum of all products whose multiplicand/multiplier/product identity > can be written as a 1 through 9 pandigital. > > HINT: Some products can be obtained in more than one way so be sure to only > include it once in your sum. My question is, how can I make this code better, in terms of style and speed. I imagine using things like `Reap` and `Sow` could improve the readability and also speed. Also while my code run in under 3 seconds, I saw other people claiming less than 10 milliseconds time. Of course, using `ParallelTable` decreased the time to about 0.6 seconds on my PC but this is still not comparable to those times. Any advise is greatly appreciated.


title: Correct handling of milliseconds in a date time string

text: DateString[{2014, 5, 7, 13, 47, 44.760},        {"Year", "-", "Month", "-", "Day", " ", "Hour", ":", "Minute", ":", "Second", ".",        "Millisecond"}]      Returns 2014-05-07 13:47:44.759 The 44.760 can be 44.76 or 44.76` with no difference, replacing it with 44760/1000 does return 2014-05-07 13:47:44.760. Presumably this is to do with 44.76 not being exactly represented as a machine precision number and milliseconds just cutting out the last 3 digits rather than rounding to 3 decimal places. Can anyone suggest a simple fix?


title: Create heat map from RMSD values

text: After looking through these forums for answers that could work for my problem, I could not find anything. I want to make a heat map comparing values that are in a nested list. That is, I have a nested list of size n x n, and each position in the list is a rational number. How could I make a heat map comparing the greater/lesser of these numbers. The higher numbers would be one color and the lower would be another. An example first three lines of a list of Length 9 is:               {{0., 2.03181, 10.9162, 9.81852, 19.9333, 9.74689, 0.826292, 1.61575,        6.11642}, {2.52762, 0., 12.3072, 13.0194, 5.9971, 20.1544, 2.1197,        0.611078, 5.01625}, {17.5098, 6.42256, 0., 5.32809, 7.09947,        22.5269, 5.43391, 5.56034, 0.48698}}      All assistance is appreciated. Best, CK


title: Consuming a SOAP service that requires a complexType authentification header

text: **Short version:** Why do I get a `$RecursionLimit` error when calling `NewSchemaInstance[SomeInstalledType]` and how do I fix it? **Longer version:** I am trialling a vendor product that presents a web- service to dynamically construct data sets and delivers them via FTP. In production use there would be an intervening service layer between Mathematica and the vendor's web service but for trial purposes I think I should be able to just use the built-in Mathematica WebServicesLink and I'm curious why it doesn't work as expected. My trial agreement with the vendor prevents me from posting some details but I think I can be specific enough. This is my first post and I've done my best to follow protocol but please let me know if I've missed anything. Generally, each call to the web service requires a CredentialsHeader element in the SOAP header that contains a username, password, and tokenId. If the tokenId is blank or unkown, the service looks up the username and password and issues a new tokenId with the response. This tokenId can then be reused in subsequent messages to speed up response times. In Mathematica, that appears as a function argument after calling `InstallService[serviceAddress.wsdl]`:               ?SomeFunctionWithNoActualArguments     {___Data} SomeFunctionWithNoActualArguments[CredentialsHeader_CredentialsHeader]     Documentation was not provided.      The CredentialsHeader element is defined in the WSDL file along with everything else and references a particular namespace:               <xsd:element name="CredentialsHeader" type="typens:CredentialsHeader" />       <xsd:complexType name="CredentialsHeader">         <xsd:sequence>           <xsd:element name="username" type="xsd:string"/>           <xsd:element name="password" type="xsd:string"/>           <xsd:element name="tokenId" type="xsd:string"/>         </xsd:sequence>       </xsd:complexType>      In Mathematica after calling `InstallService[serviceAddress.wsdl]` I can see details of the type:               ?CredentialsHeader     TYPE PROPERTIES     Name      CredentialsHeader     Namespace [redacted]     Global    True     Array     False          TYPE ELEMENTS     Name     Type   MinOccurs MaxOccurs Default Fixed Symbol     username String 1         1         Null    Null  username$735     password String 1         1         Null    Null  password$740     tokenId  String 1         1         Null    Null  tokenId$745      However when I try to create an instance, I get an error.               NewSchemaInstance[CredentialsHeader, {"username" -> "a", "password" -> "b", "tokenId" -> ""}]     $RecursionLimit::reclim: Recursion depth of 256 exceeded. >>     CredentialsHeader -> CredentialsHeader -> CredentialsHeader -> <snip> -> CredentialsHeader ->      NewSchemaInstance[CredentialsHeader, {"username" -> "a", "password" -> "b","tokenId" -> ""}]      Other tested types installed by the service work as expected:               ?DateRange     TYPE PROPERTIES     Name      DateRange     Namespace [redacted]     Global    True     Array     False          TYPE ELEMENTS     Name  Type       MinOccurs MaxOccurs Default Fixed Symbol     start SchemaDate 1         1         Null    Null  start$827     end   SchemaDate 1         1         Null    Null  end$832          NewSchemaInstance[DateRange]     DateRange["start" -> Null, "end" -> Null]      Thanks very much for any advice. Let me know if there is any more detail I can post.


title: Taking Mean for several elements of a list

text: i have the following question: Let us assume we have the following list:               list={1.1,1.2,1.0,2.1,2.2,2,0,3.1,3.0,3.2}      I need a function that always takes three values of this list and put the Mean of these three values into a new list so I want to end with:               list2={1.1,2.1,3.1}      How can i do this easily? Thank you in advance Edit: Thank you very much


title: A deterministic function to generate a random number

text: Using _Mathematica_ , I need to define a function of one integer variable that generates the same real number in the range 0 to 1, if it is called with the same argument, but gives a different real number if its argument is changed. For example :               Func[1] = 0.12675,     Func[2] = 0.11213,     Func[2] = 0.11213,     Func[1] = 0.12675,     Func[3] = 0.02561,      and so on. How can I define such a function? ### Edit A more precise statement of the pseudo-random nature of the function `Func`. The function should generate new numbers for each _Mathematica_ session. So after thousands of sessions, the values `Func[1]` are uniformly distributed on the intervall 0 to 1. For a given session, `Func[1]` generates the same number again and again. But in the next session, `Func[1]` would be a different number. Otherwise, the generated numbers couldn't be considered as "random" if they are always the same.


title: Combinatorica package and graph-theoretical issues

text: I've searched for a solution to my problem a couple of days, and I didn't find one. Hope you guys can help me. I'm currently trying to solve some graph-theoretical problems. One of them is to find the maximum flow throughout a graph. I've managed to draw the graph in _Mathematica_ , and would now like to use the built-in function `NetworkFlow`. To do this I need to load the package `Combinatorica`, but that gives me problems with "shadowed" functions. I've tried to refer to them by their fully qualified names, e.g., `Combinatorica```NetworkFlow`, etc., but I still can't get it to work. I've pasted in some code which I hope will make it easier to see what I'm doing wrong:               Graph[{Kø -> Ro, Kø -> Pu, Kø -> Pa, Ro -> Ha, Ro -> Be, Pu -> Ha,        Pu -> Be, Pa -> Ha, Ha -> Be, Ha -> St, Ha -> Br, Ha -> Li,        Be -> St, Be -> Br, Be -> Li, St -> Br, St -> Li, St -> Par,        Br -> Li, Br -> Par, Li -> Par},       EdgeWeight -> {"2", "11", "8", "3", "5", "14", "11", "10", "12",         "12", "10", "10", "4", "4", "12", "4", "12", "11", "23", "16",         "10"}, VertexLabels -> "Name", ImagePadding -> 10,       GraphLayout -> "SpringEmbedding"]      ![Mathematica graphics](http://i.stack.imgur.com/HQfjj.png) Which gives me a nice graph. Below is the "real" problem:               Needs["Combinatorica`"]     Graph[{Kø -> Ro, Kø -> Pu, Kø -> Pa, Ro -> Ha, Ro -> Be, Pu -> Ha,        Pu -> Be, Pa -> Ha, Ha -> Be, Ha -> St, Ha -> Br, Ha -> Li,        Be -> St, Be -> Br, Be -> Li, St -> Br, St -> Li, St -> Par,        Br -> Li, Br -> Par, Li -> Par},       EdgeWeight -> {"2", "11", "8", "3", "5", "14", "11", "10", "12",         "12", "10", "10", "4", "4", "12", "4", "12", "11", "23", "16",         "10"}, VertexLabels -> "Name", ImagePadding -> 10,       GraphLayout -> "SpringEmbedding"]     Combinatorica`NetworkFlow[%, Kø, Par]      > During evaluation of In[28]:= General::compat: Combinatorica Graph and > Permutations functionality has been superseded by preloaded functionaliy. > The package now being loaded may conflict with this. Please see the > Compatibility Guide for details.               Out[29]= Graph({Kø->Ro,Kø->Pu,Kø->Pa,Ro->Ha,Ro->Be,Pu->Ha,Pu->Be,Pa->Ha,Ha->Be,Ha->St,Ha->Br,Ha->Li,Be->St,Be->Br,Be->Li,St->Br,St->Li,St->Par,Br->Li,Br->Par,Li->Par},EdgeWeight->{2,11,8,3,5,14,11,10,12,12,10,10,4,4,12,4,12,11,23,16,10},VertexLabels->Name,ImagePadding->10,GraphLayout->SpringEmbedding)          Out[30]= NetworkFlow(Graph({Kø->Ro,Kø->Pu,Kø->Pa,Ro->Ha,Ro->Be,Pu->Ha,Pu->Be,Pa->Ha,Ha->Be,Ha->St,Ha->Br,Ha->Li,Be->St,Be->Br,Be->Li,St->Br,St->Li,St->Par,Br->Li,Br->Par,Li->Par},EdgeWeight->{2,11,8,3,5,14,11,10,12,12,10,10,4,4,12,4,12,11,23,16,10},VertexLabels->Name,ImagePadding->10,GraphLayout->SpringEmbedding),Kø,Par)


title: How to force neat linewrapping in Print?

text: I am regularly annoyed by the fact, that a neatly arranged `Print` statement gets ruined by a large piece of data, which - instead of linewrapping "in place" - is pushed below the preceding label. See example:               Print[       "test line 1...............: ", {1, 2, 3}, "\n",       "test line 2...............: ",        Pane[Table["testestestestestestestestest", {10}], 800], "\n",       "test line 3...............: ", {1, 2, 3}       ];      which produces the following output: ![Mathematica graphics](http://i.stack.imgur.com/0sxaS.png) **Question** Is it possible to tell the `Pane` object to wrap its content in a way that does not force the _Table_ to shift to the next line, but is linewrapped in- place (i.e. right next to " _test line 2_ ")? Of course I can specify an explicit width for `Pane`, but since I don't know how big is my screen (user's screen), how large in pixels is the label text (" _test line 2_ "), and many other factors, it just seems useless to give a magic number that should cover all situations. `Full` and `All` does not work either. Any idea?


title: How to check for Mathematica’s definition of XY?

text: The question is: **Can I ask the Mathematica kernel directly what it takes as the definition of the built-in symbol XY?** After all this has to be in the kernel. And if the documentation is not giving any hint as in the following example I’d like to know with what I’m working. The change of the definition of `Binomial[]` from M7 to M8 serves as an example. The Mathworld entry for the Binomial Coeffcient mentiones the change. Mathematica’s online help does not. It just gives the general definition for complex $x, y$: $$\binom{x}{y}=\frac{\Gamma(x+1)}{\Gamma(y+1)\Gamma(x-y+1)}.$$ But for sure Mathematica knows about the special case $n,k\in\mathbb{N}$: $$\binom{n}{k}=\begin{cases}\frac{n!}{k!(n-k)!}&0\le k \le n\\\0&\text{otherwise}\end{cases}$$ As found in Kronenburg’s arxiv paper the definition can be extended to $n<0$. Note that the Gamma function is infinite for negative integers arguments, so this is an extension even to the general complex definition given above. Kronenburg basically extends Pascals Triangle upwards for negative $n$. This change however breaks many equations involving binomials found in the books like Concrete Mathematics and Analytic Combinatorics. For example generalized Fibonacci Numbers where the sum of the last $r$ terms gives the next term, is given by $$c_n^r=\sum_{j,k}\binom{j}{k}\binom{n-rk-1}{j-1}(-1)^k$$ As customary the indices $j$ and $k$ range over integer interval $[0..\infty]$ and the binomial coefficients are $0$ according to the second definition effectively making this series finite. This “trick” or some may say this “abuse of notation” is widely used as it allows to work with identities involving binomial coefficients quite nicely. The change of the definition leads to $c_n^r$ having different results in M7 and M8. * * * EDIT: I like to give another example, besides the bionomial coefficient one from above, why I want to have a look at the definitions. With Mathematica you can specify Forms for the output, e.g. `TeXForm` or `TraditionalForm`. Moreover you can create your own output forms. Typically one does not want to start from the scratch, but just modify a thing or two in the existing ones. To be able to do that, I first need to look at the definition. I’m aware of the fact, that forms like `TraditionalForm` consist of a large collection of rules to produce an approximation to traditional mathematical notation. For this very reason I don’t want to collect all the rules myself (I’m sure I’ll never succeed). I want to build on the work that was already done. I like standing on the shoulders of giants.


title: Using ListPointPlot3D to simulate 2D plots moving in time

text: I wrote a 1D solver for the heat equation $u_t=u_{xx}$, and I can animate the solution using normal `ListPlot` command, where the x-axis is the rod length, and the y-axis is $u(x,t)$. So for each time instance, I make a new 2D plot, etc... Another way to view this, is by 3D, where now each frame is a 2D plot at some time instance, and time travels down the page. This gives a nicer view of the diffusion of heat, I think. So, basically I have a number of 2D frames, and I want to display them in 3D, one frame after the other as time advances. Using MATLAB I use the `mesh` command with `holdon`, and here is a screen shot just to show what I mean from a school project I did: ![MATLAB example](http://i.stack.imgur.com/E4TAF.png) So time advances down the page as the simulation runs. I wrote the same thing using Mathematica for a demo, here is what I have to far, I got the general layout working using `ListPointPlot3D`, but I am not able to figure out how to tell Mathematica to make a curve on top of the points being displayed so I can get the same effect as above. Here is an example, where here I make a sine wave (this will be my solution from above), and plot the frames in time using `Animate`:               f = 0.2;(*hz*)     data1[t_] := Table[Sin[2 Pi f t x], {x, -Pi, Pi, .1}];     data = Table[data1[t], {t, 0, 2, .2}];     Animate[ListPointPlot3D[data[[1 ;; i]], Filling -> Axis,        PlotStyle -> Red, PlotRange -> {Full, {1, Length[data]}, Automatic},        AxesLabel -> {x, "time", "u(x,t)"}], {i, 1, Length[data], 1}]      ![ListPointPlot3D animation](http://i.stack.imgur.com/pXn2e.gif) I kept the `Filling -> Axis` in the above just to make it easier to see. I'd like just have curve lines on top of those red points you see there. If I remove the `Filling` option, then only the points remain, making it hard to see. Also, I can't use `Joined -> True` here. ![enter image description here](http://i.stack.imgur.com/maenk.png) I tried the `ListPlot3D` command also:               f = 0.4;(*hz*)     data1[t_] := Table[Sin[2 Pi f t x], {x, -Pi, Pi, .1}];     data = Table[data1[t], {t, 0, 2, .1}];     Animate[ListPlot3D[data[[1 ;; i]], PlotStyle -> Red,        PlotRange -> {Full, {1, Length[data]}, Automatic},        AxesLabel -> {x, "time", "u(x,t)"}, PerformanceGoal -> "Quality",        Mesh -> 10], {i, 1, Length[data], 1}]      But I need to work more on this, and I find the `ListPointPlot3D` clearer if I can get the curves part to work and I think it is more light weight for a demo as I do not want to slow it down too much. Here is another example from a paper I am reading of the type of plots I'd like to generate of the same PDE solution I have but plots are shown in 3D with time moving down the page: ![enter image description here](http://i.stack.imgur.com/bTqTO.png) **Question** : Any other suggestions to do what I want using Mathematica that I might have overlooked? How can I get the `ListPlotPoint3D` to show just curves on top of the points (i.e. joined at the top, like I showed in my MATLAB screen shot). I looked at the Mathematica visualization functions, but did not see something obvious to use so far other than the above.


title: OpenCL Dot Product

text: I have to calculate billions of dot products. My current implementation uses `Compile` to generate `C` code and it's very fast (10s of seconds). But, I was wondering if I could make it faster by using my GPU (AMD 6670). Unfortunately I don't have an NVIDIA card since it seems that `CUDADot` is implemented. I'm trying to use the OpenCL `DotProduct` code in `FileNameJoin[{$OpenCLLinkPath, "SupportFiles", "DotProduct.cl"}]` code below:               src = "/*      * Copyright 1993-2009 NVIDIA Corporation.  All rights reserved.      *      * NVIDIA Corporation and its licensors retain all intellectual property and       * proprietary rights in and to this software and related documentation.       * Any use, reproduction, disclosure, or distribution of this software       * and related documentation without an express license agreement from      * NVIDIA Corporation is strictly prohibited.      *       */           __kernel void DotProduct (__global float* a, __global float* b, __global float* c, mint iNumElements)     {         // find position in global arrays         int iGID = get_global_id(0);              // bound check (equivalent to the limit on a 'for' loop for standard/serial C code         if (iGID >= iNumElements)         {                return;          }              // process          int iInOffset = iGID << 2;         c[iGID] = a[iInOffset] * b[iInOffset]                     + a[iInOffset + 1] * b[iInOffset + 1]                    + a[iInOffset + 2] * b[iInOffset + 2]                    + a[iInOffset + 3] * b[iInOffset + 3];     }"      I have managed to load the OpenCL function and compute a single DotProdct but this is mostely useless. I've been going over the instructions but I can't seem to figure out how to run many dot products in parallel (the whole point of using the GPU).               srcf = FileNameJoin[{$OpenCLLinkPath, "SupportFiles", "DotProduct.cl"}]          OpenCLDotProduct =        OpenCLFunctionLoad[{srcf},         "DotProduct", {{"Float"}, {"Float"}, {"Float"}, _Integer}, {16,          16}];          output = {0};     a = {1., 2., 2.};     b = {1., 2., 2.};     OpenCLDotProduct[a, b, output, 3]          (*          output -> {{1., 2., 2.}, {1., 2., 2.}, {9.}}          *)      This is correct, great. However, I can't figure out how to do more than a.b:               output = {0, 0};     a = {1., 2., 2.};     b = {1., 2., 2.};     c = {3., 2., 8.};     OpenCLDotProduct[{a, c}, b, output, 6]          (*          output -> {{{1., 2., 2.}, {3., 2., 8.}}, {1., 2., 2.}, {18., 68.}}          *)      I can't figure out what this output means or what the proper syntax is to do multiple dotproducts. I'm also not sure if this implementation is even fast. I found a blog describing another implementation but I haven't been able to compile it (http://www.openclblog.com/2012/11/opencl-and-dot-product.html).


title: Plotting with Units

text: I'm trying to get _Mathematica_ to plot with units, but I'm having some trouble. Below is a minimal example of trying to plot `y = x`, where `x` is a quantity with units. Why does it only seem to work if the units are put directly into the plot function:               (*Define unitful constants*)     x1 = Quantity[1, "Volts"]; x2 = Quantity[2, "Volts"];     (*Try to plot, get an error*)     Plot[x, {x, x1, x2}]     (*But this works*)     Plot[x, {x, Quantity[1, "Volts"], x2}]     (*As does this*)     Plot[x, {x, x1 - Quantity[1, "Volts"], x2}]      There error message is > Plot:plln: Limiting value 1V in {x, x1, x2} is not a machine-sized real > number For reference, here's what I see when I run it ![enter image description here](http://i.stack.imgur.com/u0BPL.png) (View full)


title: Unexpected behavior of UnitConvert

text: When I evaluate this expression:               UnitConvert[Quantity[1920*1080, "Bytes"]*Quantity[24, "1/Seconds"] +           Quantity[44, "Kilohertz"]*Quantity[16, "Bits"],           Quantity["Megabytes"/"Seconds"]]      I get an error message:               UnitConvert::unkunit: Unable to interpret unit specification 1MB/s. >>      But the units should be compatible. FWIW, the old Units package has no problems with the equivalent:               Needs["Units`"]     Convert[1920*1080 Byte*24/Second + 44 Kilo Hertz*16 Bit, Mega Byte/Hour]      The only workaround I've found was to unit-convert the subexpressions myself:               UnitConvert[Quantity[1920*1080, "Bytes"]*Quantity[24, "1/Seconds"] +          UnitConvert[Quantity[44, "Kilohertz"], 1/"Seconds"]*         UnitConvert[Quantity[16, "Bits"], "Bytes"],          Quantity["Megabytes"/"Seconds"]]      Is this a bug or am I using it wrong?


title: Efficient way to utilise Parallel features to make use of many cores

text: Let's say I have 100 cores/kernels as my disposal and want to compute a function of two variables `f[x,y]` over `{x,1,10}`, `{y,0,59}`. So in total 600 data points. Ideally I would like to utilize all 100 cores giving each core 6 data points to compute. How can I achieve this?               ParallelTable[f[x, y], {y, 0, 59 }, {x, 1, 10 }]      Would only parallelize on the first 60 cores and give each core a workload of 10 points and               ParallelTable[f[x, y], {x, 1, 10 }, {y, 0, 59 }]      would do even worse- parallelizing on the first 10 cores and giving each a workload of 60 points. I think doing               ParallelTable[f[x, y], {y, 0, 59 }, {x, 1, 3 }];     ParallelTable[f[x, y], {y, 0, 59 }, {x, 4, 6 }];     ParallelTable[f[x, y], {y, 0, 59 }, {x, 7, 10}];      Would only evaluate the three calls sequentially when the previous `ParallelTable` had finished so would also do not better? Is there a way around this?


title: SetPrecision — different values subtracted from unity gives same value

text: How are my results possible? CODE:               SetPrecision[FibersFailedNew, 40]      > >     3.612171938234261799295174910010284760488*10^-16 >                 SetPrecision[FibersFailedNewT2, 40]      > >     3.612171938234886971562562561866073555376*10^-16 >                 SetPrecision[FibersRemainingNewT2 = 1 - FibersFailedNewT2, 55]      > >     0.999999999999999666933092612453037872910499572753906250 >                 SetPrecision[FibersRemainingNew = 1 - FibersFailedNew, 55]      > >     0.999999999999999666933092612453037872910499572753906250 >   The values are calculated from previous equations in the specific notebook. If I would take only values and copy pasted them in a different notebook, of course, the results given are true. How is this possible? Does _Mathematica_ calculate in a different precision as set? of it calculates what is shown on the screen The values of `FiberFailedNew` and `FiberFailedNewT2` are different, but when subtracted from unity they give the same result.


title: Stop TradtionalForm evaluating expression

text: I'm trying to get this expression to display as typed instead of evaluating the 1/1.121.               SetAttributes[TraditionalForm, NHoldAll];     TraditionalForm[(17.517*CuS^2 - 12.081*CuS + 54.875)/(1.121)]      After reading the documentation I would have thought NHoldAll would have stopped this but it doesn't seem to.


title: Weird resampling when I try to export an Image

text: _Mathematica_ language newbie here. I wrote the following code to quantize an image:               basepath = "~"     SetDirectory[basepath]     jpgpath = FileNameJoin[{basepath, "jpg"}]     pngpath = FileNameJoin[{basepath, "png"}]          domquant[path_, n_] :=       Image[{List @@@          DominantColors[Image[ColorQuantize[Import[path], n]], n]}]          (*Convert each jpg in path to its 256-color quantized sample*)     Scan[( \      img = domquant[#, 24];         Print[#, " ", img];     Export[         FileNameJoin[{pngpath, StringJoin[FileBaseName[#], ".jpg"]}],         img,         "JPEG", ImageResolution -> 300,      ImageSize -> {8192, 512}]) &, {FileNames[     "*.jpg", {jpgpath}][[1]]}]      If I change the 24 in the `domquant` call to a higher value I get what looks like a rasterized image (I think). Specifically, a gradient is applied. For example, here's the result of `domquant[#, 256]`: ![wtf](http://i.stack.imgur.com/WHDma.jpg) However, if I leave the value as `n = 24` or some other smaller number, I get a nice image like this which has discrete boundaries between each value of `n`, and is actually what I am trying to achieve: ![enter image description here](http://i.stack.imgur.com/BpzmQ.jpg) So, why is 24 the magic number beyond which the blur effect takes place? How can I get an image with nice discrete colors using a higher value of `n`? In response to Szabolcs, if I remove the `ImageResolution` and `ImageSize` options, I get this image: ![enter image description here](http://i.stack.imgur.com/7ONuq.png) Not what I'm looking for. I want to create an image like the second one above, where each of 256 colors is represented discretely, and is of arbitrary size. In response to Simon Woods, if I add `Resampling -> "Nearest"` to `Export`, I ge this image with `n=256`, again blurry: ![enter image description here](http://i.stack.imgur.com/mIvlq.png) **Thanks to everyone who commented, the following comment from SimonWoods helped me understand**. Here's the final (working) code and the resulting (quite beautiful) image.               basepath = "~"     SetDirectory[basepath]     jpgpath = FileNameJoin[{basepath, "jpg"}]     pngpath = FileNameJoin[{basepath, "png"}]          domquant[path_, n_] :=       Image[{List @@@          DominantColors[Image[ColorQuantize[Import[path], n]], n]}]          (*Convert each jpg in path to its 256-color quantized sample*)     Scan[(        img = domquant[#, 256];        img = ImageResize[img, {8152, 512}, Resampling -> "Nearest"];        Print[#, " ", img];        Export[         FileNameJoin[{pngpath, StringJoin[FileBaseName[#], ".png"]}],             img, "PNG"]) &, {FileNames["*.jpg", {jpgpath}][[1]]}]      ![enter image description here](http://i.stack.imgur.com/ueYu1.png)


title: Problem with the Plot of Functions and PlotLegends

text: For some odd reason the `PlotLegends` output is not as expected.               Clear[f, g, v]     v = Function[x, k*x^-k];     g = Function[x, (x^-k)*Sin[x^k]/(1 + x^k)];     f = Function[x, x^k/(1 + x^k)];     With[{f = f, g = g},      Manipulate[Plot[{v[x], f[x], g[x], D[f[x] - g[x]]}, {x, 0, 5},     PlotLegends -> "Expressions"], {k, 1, 10}]]      ![enter image description here](http://i.stack.imgur.com/2ftPq.png)


title: Creating a simulation of our Solar System

text: As the title says, my objective is to create a simulation of the motion of the planets in our Solar System using Mathematica. All the theoretical background regarding the equations of motion of planets is well know so, the difficult part is to create a functional code. Below I present what I have so far               Clear["Global`"];     pSun = {0, 0};     rMercury = a/(1 + e*Cos[θ]) /. {a -> 0.387, e -> 0.2056, i -> 7.005};     rVenus = a/(1 + e*Cos[θ]) /. {a -> 0.723, e -> 0.0068, i -> 3.3947};     rEarth = a/(1 + e*Cos[θ]) /. {a -> 1, e -> 0.0167, i -> 0};     rMars = a/(1 + e*Cos[θ]) /. {a -> 1.524, e -> 0.0934, i -> 1.851};     rJupiter = a/(1 + e*Cos[θ]) /. {a -> 5.203, e -> 0.0484, i -> 1.305};     rSaturn = a/(1 + e*Cos[θ]) /. {a -> 9.537, e -> 0.0542, i -> 2.484};     rUranus = a/(1 + e*Cos[θ]) /. {a -> 19.191, e -> 0.0472, i -> 0.770};     rNeptune = a/(1 + e*Cos[θ]) /. {a -> 30.069, e -> 0.0086, i -> 1.769};     rPluto = a/(1 + e*Cos[θ]) /. {a -> 39.482, e -> 0.2488, i -> 17.142};          p0 = ListPlot[{pSun}, Axes -> False,      PlotStyle -> {RGBColor[1, 0.65, 0], PointSize[0.035]}];     p1 = PolarPlot[rMercury, {θ, 0, 2 π}, PlotStyle -> Gray];     p2 = PolarPlot[rVenus, {θ, 0, 2 π}, PlotStyle -> Orange];     p3 = PolarPlot[rEarth, {θ, 0, 2 π}, PlotStyle -> Blue];     p4 = PolarPlot[rMars, {θ, 0, 2 π}, PlotStyle -> Red];     p5 = PolarPlot[rJupiter, {θ, 0, 2 π}, PlotStyle -> Brown];     p6 = PolarPlot[rSaturn, {θ, 0, 2 π}, PlotStyle -> Magenta];     p7 = PolarPlot[rUranus, {θ, 0, 2 π}, PlotStyle -> Cyan];     p8 = PolarPlot[rNeptune, {θ, 0, 2 π}, PlotStyle -> Darker[Green]];     p9 = PolarPlot[rPluto, {θ, 0, 2 π}, PlotStyle -> Black];          S1 = Show[{p1, p2, p3, p4, p0}, Axes -> False, Frame -> True,      FrameTicks -> None, PlotRange -> All, AspectRatio -> 1,      ImageSize -> 500]     S2 = Show[{p5, p6, p7, p8, p9, p0}, Frame -> True, FrameTicks -> None,     Axes -> False, PlotRange -> All, AspectRatio -> 1,      ImageSize -> 500]      \-------------------- INNER SOLAR SYSTEM -------------------- ![enter image description here](http://i.stack.imgur.com/1CEq4.png) \-------------------- OUTER SOLAR SYSTEM -------------------- ![enter image description here](http://i.stack.imgur.com/bv4AP.png) I have divided the Solar System in two different plots. The first one contains the Earth-type planets (Mercury, Venus, Earth and Mars) and the second one the gas giants. The orbits of the planets are ellipses and are given in polar form using Kepler's theory. Obviously, Sun is stationary at one of the focuses. The motion of all the planets is two-dimensional. However, all orbits are not co- planar. Here comes the first issue: (1). Somehow, the ellipses must be rotated according to the inclination of each planet. The inclination (i) in degrees is given. So, we should have a 3D box containing all the 2D inclined ellipses. Earth's inclination is zero thus defying the primary plane (ecliptic) from which we measure inclination. (2). At every orbit, it would be nice if there was a color dot (like the Sun I already have) indicating each planet. Since we speak of a simulation, every dot (planet) should circulate around Sun following the corresponding orbit. Here we have a problem. Every planet has each one rotational velocity according to its mass. However, the polar equation giving the orbit does not include the mass of the planet. Any suggestions here would be greatly appreciated. There are also few additional minor issues. For the time being, the first two issues are important and should be resolved first. From my point of view, this task is indeed not only interesting but also very challenging. Everyone should have a nice model of our Solar System!


title: The Orbit and Perigee of the Flamsteed comet

text: ### Historical context This year we have the 330-th anniversary of the Battle of Vienna \- one of the great formative events of European history, it took place on September 12, 1683. Kara Mustafa, Grand Vizier of the Ottoman Empire, had laid siege to the Hapsburg capital and was on the verge of capturing it when a relieving Christian army under the overall command of Jan III Sobieski, King of Poland, swept into the Turkish ranks. During the siege of Vienna by the Islamic power, before Sobieski's forces joined (on September 11) the rest of the Holy League, there had appeared a comet (later called Flamsteed) on the sky at the end of July and could be seen until September. ### Newton's Principia Mathematica on the comet In the third book of Philosophiae Naturalis Principia Mathematica Isaac Newton says: > The comet of 1683 (also according to the observations of Hevelius) at the > end of July, when it was first sighted, was moving very slowly, advancing > about $40'$ or $45'$ in its orbit each day. From that time its daily motion > kept increasing continually until 4 September when it came to about > $5^{\circ}$. Therefore in all this time the comet was approachin the earth. > This is gathered also from the diameter of the head, as measured with > micrometer, since Hevelius found it to be on 6 August only $6'5''$ including > the coma, but on 2 September $9'7''$. Therefore the head appeared far > smaller at the begining than at the end of the motion, as Hevelius also > reports. Accordingly in all this time, because of receding from the sun it > decreased with respect to its light, notwithstanding its approach to the > earth. ### Astronomical Data With help of built-in `AstronomicalData` we can easily draw the orbits of the comet and the first `4` planets:               Graphics3D[       {{#1, AstronomicalData[#2, "OrbitPath"]} & @@@          Transpose[{ {Orange, Green, Blue, Red}, Take[ AstronomicalData["Planet"], 4]} ],         {Magenta, Line[ AstronomicalData[                           AstronomicalData["CometC1683O1"], "OrbitPath"][[1, 28 ;; 195]]]}       }, Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/4RslT.gif) ### Question I'd like to find the exact date and time of the perigee of the Flamsteed comet and to inset points of locations (at that time) of the first $4$ planets on the graphics.


title: How to run an external program in parallel with a Mathematica package?

text: Under Mathematica 8 (Linux x84_64) I was able to run an external program in parallel from a Mathematica package. However this procedure breaks down under Mathematica 9. Within my Mathematica package I created some artificial links for the sub- kernels to be synchronized with the links created by the master kernel. Otherwise the link numbering of the sub-kernels does not coincide with the numbering created by the master kernel. This procedure is different from that suggested by How to run mathlink external commands in parallel? Here is the relevant code I used in my Mathematica package that did the job successfully under Mathematica 8.               Which[SameQ[Global`$ParaMode,"False"] && SameQ[Global`$NotebookMode,"False"],False,               SameQ[Global`$ParaMode,"False"] && SameQ[Global`$NotebookMode,"True"], False,           SameQ[Global`$ParaMode,"True"]  && SameQ[Global`$NotebookMode,"False"],kc=$KernelCount;Table[LinkCreate[],{kc-1}],           SameQ[Global`$ParaMode,"True"]  && SameQ[Global`$NotebookMode,"True"],kc=$KernelCount;Table[LinkCreate[],{kc+6}]           ];      Now let us see what will happen under Mathematica 9. To keep the example small I launch only two sub-kernels.               In[1]:= LaunchKernels[2];          In[2]:= $KernelCount          Out[2]= 2      After loading my package into the master kernel and sub-kernels I have the following link connections for the master kernel               In[50]:= Links[]               Out[50]= {LinkObject[/pfs/data/software/all/mathematica/9.0/Executables/math\          >      -subkernel -noinit -mathlink, 83, 1],           >    LinkObject[/pfs/data/software/all/mathematica/9.0/Executables/math -subkernel\          >      -noinit -mathlink, 84, 2], LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddma\          >      thlink, 123, 3], LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2g\          >      mp, 124, 4], LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2, 125,           >     5]}      and here the link connections for the two sub-kernels.               In[51]:= ParallelEvaluate[Links[]]               Out[51]= {{LinkObject[q63_shm, 3, 1],           >     LinkObject[34611@xxx.xxx.xxx.xxx,59020@xxx.xx.xx.xx, 101, 2],           >     LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink, 102, 3],           >     LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 103, 4],           >     LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2, 104, 5]},           >    {LinkObject[35c_shm, 3, 1],      LinkObject[56693@xxx.xx.xx.xx,56906@xxx.xx.xx.xx,           >      99, 2], LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink, 100, 3],           >     LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 101, 4],           >     LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2, 102, 5]}}      On a first glance everything seems fine, since the links between the master kernel and its sub-kernels were synchronized as intended. Now, I want to call a function from my Mathematica package in parallel that makes use of the external program.               In[54]:=       a2a=ParallelTable[StrongEpsCore3dV6[ExpGame11,EpsStrValues -> t, ViewKernelSol -> True, KernelCoord -> ker, ViewNucleolusSol -     > True, NucleolusCoord -> mnuc, ViewShapleySol -> True, ShapleyCoord -> shv, ShowCore->True, ShowImputationSet -> True], {t, 30, detlow, -(1/40)     }]      But to my big surprise, the procedure failed. The strange thing here is that both sub-kernels trying to use the connection build up by the master kernel instead of using their own connections.               From KernelObject[2, local]:     LinkObject::linkn:         Argument LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 124, 4] in\          >            LinkWrite[LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 124, 4],\          >             CallPacket[1, {5, 5, {{0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0},              {-25369617/<<9>>7, 0, 0, 0, 1}, {-1, 1, 1, 1, 1}}}]] has an invalid          LinkObject number; the link may be closed.               From KernelObject[1, local]:     LinkObject::linkn:         Argument LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 124, 4] in\          >            LinkWrite[LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 124, 4],\          >             CallPacket[1, {5, 5, {{0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0},              {-25369617/<<9>>7, 0, 0, 0, 1}, {-1, 1, 1, 1, 1}}}]] has an invalid          LinkObject number; the link may be closed.      My question are now as follows: How I have to modify the above code so that the sub-kernels are using their own connections rather than that of the master kernel? How can I avoid this unintended behavior? It might also be helpful to know what changes have been made in the MathLink protocol from Mathematica 8 to 9. **Update** In the meantime I made some small progress while starting from scratch without calling any package defined functions. Contrary to my first observation setting the option > DistributedContexts -> None might have an effect whenever the function of the external program is called directly. To see this, let us call in a first step the external program directly without setting the option `DistributedContexts -> None`, then we still have the same failure               In[17]:= Parallelize[Table[AllVertices[6,5,string1],{2}]]     From KernelObject[2, local]:     LinkObject::linkn:         Argument LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 85, 3] in          LinkWrite[LinkObject[/pfs/data/home/kit/xxxx/xxxxx/bin64/cddmathlink2gmp, 85, 3],           CallPacket[0, {6, 5, {{0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0,              0, 0,<<11>>, 1, 1, 1}, {1, -1, -1, -1, -1}}}]] has an invalid LinkObject          number; the link may be closed.     From KernelObject[1, local]:     LinkObject::linkn:         Argument LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 85, 3] in          LinkWrite[LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 85, 3],           CallPacket[0, {6, 5, {{0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0,              0, 0,<<11>>, 1, 1, 1}, {1, -1, -1, -1, -1}}}]] has an invalid LinkObject          number; the link may be closed.      Now, calling the function directly with the option `DistributedContexts -> None` helps in this case, I got the desired result                In[17]:= Parallelize[Table[AllVertices[6,5,string1],{2}],DistributedContexts -> None]     Out[17]= {{{{{1, 1,  0,  0,  0}, {1,  0, 1,  0,  0}, {1,  0,  0, 1,  0},           >       {1,  0,  0,  0, 1}}, {}}, {{2, 3, 4, 5, 6}, {1, 3, 4, 5, 6}, {1, 2, 4, 5, 6},           >      {1, 2, 3, 5, 6}}}, {{{{1, 1,  0,  0,  0}, {1,  0, 1,  0,  0},           >       {1,  0,  0, 1,  0}, {1,  0,  0,  0, 1}}, {}},           >     {{2, 3, 4, 5, 6}, {1, 3, 4, 5, 6}, {1, 2, 4, 5, 6}, {1, 2, 3, 5, 6}}}}      Nevertheless, when I try to invoke the above package function again with the option `DistributedContexts -> None` to call indirectly the external program, then I still get the same failure. Nothing has improved. It seems that the option `DistributedContexts -> None` must be put in the right place in order to have an effect. But how I have to do that? **Update 2** To simulate a package function call of the external program, I defined ceteris paribus the following indirect function call                In[15]:= callVert[m_Integer,d_Integer,a_String]:=AllVertices[m,d,string1];      In[16]:= DistributeDefinitions[callVert]      Out[16]= {callVert}       To observe that the function is well defined, we call this function first by the master kernel and obtain                In[19]:= callVert[6,5,string1]      Out[19]= {{{{1, 1,  0,  0,  0}, {1,  0, 1,  0,  0}, {1,  0,  0, 1,  0},           >      {1,  0,  0,  0, 1}}, {}}, {{2, 3, 4, 5, 6}, {1, 3, 4, 5, 6}, {1, 2, 4, 5, 6},           >     {1, 2, 3, 5, 6}}}      which coincides with the above result. However, calling now the above indirect function using `Parallelize` with option `DistributedContexts :> None`, we attain still the same failure               Parallelize[Table[callVert[6,5,string1],{2}],DistributedContexts :> None]     From KernelObject[2, local]:     LinkObject::linkn:         Argument LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 88, 3] in          LinkWrite[LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 88, 3],           CallPacket[0, {6, 5, {{0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0,              0, 0,<<11>>, 1, 1, 1}, {1, -1, -1, -1, -1}}}]] has an invalid LinkObject          number; the link may be closed.     From KernelObject[1, local]:     LinkObject::linkn:         Argument LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 88, 3] in          LinkWrite[LinkObject[/pfs/data/home/kit/xxxx/xxxx/bin64/cddmathlink2gmp, 88, 3],           CallPacket[0, {6, 5, {{0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0,              0, 0,<<11>>, 1, 1, 1}, {1, -1, -1, -1, -1}}}]] has an invalid LinkObject          number; the link may be closed.          Out[21]= {$Failed, $Failed}      I even tried               In[17]:= $DistributedContexts = None;     In[18]:= Map[SetOptions[#,DistributedContexts :> None]&, {Parallelize}];     In[19]:= Options[Parallelize]     Out[19]= {Method -> Automatic, DistributedContexts :> None}      without any effect. What's going on here? Why is it not possible to apply the option `DistributedContexts :> None` in an indirect function call for an external program?


title: Problems with RootLocusPlot

text: I am having some trouble to understand how the `RootLocusPlot` works (options, drawing and etc.) Here is an example               RootLocusPlot[      TransferFunctionModel[-((k(s-5/2)(s-2)))/((s-4)(s-1)),s], {k, 0, 10},      PlotRange-> {{-10, 15}, {-5, 5}}, AxesOrigin->{0, 0}     ]      ![enter image description here](http://i.stack.imgur.com/Wmrno.png) I have no problem to draw the RL by hand despite the negative gain (note that there is a problem with $k=1$ when closing the loop). When I use _Mathematica_ to do the same thing, the output does not seem right even when I increase/decrease the range of `k`, the number of `PlotPoints`, the scale and etc. Any help will be greatly appreciated.


title: Is there a Mathematica/Lisp link?

text: I'd like to start learning Lisp as it sometimes leads to interesting answers on this site with concepts borrowed from this language, so I'm curious. As I already spend most of my programming time in Mathematica, is there a way to execute Lisp programs from the Mathematica frontend? Same question for related languages, like Haskell or OCaml.


title: Pretty way to group elements at odd and even positions

text: How to make a function that splits list elements by odd and even positions? Shortest implementation wins. I myself came up with:               splitOdds[x_] :=       Extract[x, {#}\[Transpose]] & /@ GatherBy[Range@Length@x, OddQ]      And:               splitOdds[x_] := Flatten[Partition[#, 1, 2]] & /@ {x, Rest@x}          splitOdds[{a, b, c, d, e, f}]     (*{{a, c, e}, {b, d, f}}*)


title: Is there a way to redefine the looks of buttons, tabs and other UI elements?

text: I am looking for pointers on how to redefine UI elements (in the FE as well as in a CDF document). For example: the looks of a button, or of tab elements, and so on. (I don't mean something like "changing the color of a (pressed or unpressed) button", I really mean the UI element appearance). I have been looking around (web and here) and I didn't come up with an answer, nor with any kind of information... Anyone has any pointers? Is it even possible? Thanks!


title: RLink and R v3.0.1?

text: Running               InstallR["RHomeLocation" -> "C:\\Program Files\\R\\R-3.0.1"]      results in a popup box titled "Version Mismatch" saying > Error: R.DLL version does not match (DLL:3.0.1, expecting: 2.14.0). Does RLink only work with versions of R at or around v2.14?


title: Make second argument same as first when only one argument passed to function

text: Clear[f]     f[n_, k_: n] :={n, k}     f[x]      > {x,n} Actually I would like to get: > {x,x} The following is one wrong definition, I'm showing that I need the argument `n` not a global variable `n` but the same to the first argument `n_`.               (*Clear[f]     f[n_,k_: n_]:={n,k}     f[x]*)      If only one argument passed to `f`, then the second argument is the same to the first argument. So, how could I adjust the definition of `f`? Maybe something like `Default`? I think Kuba's answer give one example to do this. But how to define `f` only once to get the same effect? * * * Chris Degnen's answer is one bad news. I've tried this               Clear[f] f[n0_, k0_: 5] := Module[{n = n0, k = k0}, If[k == 5, {n, k = n0},{n, k}]]     f[x]      > {x,x} Good thing is it works well for numerical values.               f[x, 10]      > {x,10} Bad thing is it works badly for `y`               f[x, y]      > If[y==5,{n$37693,k$37693=x},{n$37693,k$37693}]


title: Analysis of many similar x-ray Images

text: From a 3d x-ray scan, I have many similar slices to analyze. Is there a way to determine the position of the three rectangles and the inner circle? ![X-Ray Image](http://i.stack.imgur.com/EY2EG.png) ![enter image description here](http://i.stack.imgur.com/MAiaH.png) ![enter image description here](http://i.stack.imgur.com/6fQc1.png)


title: An argument pattern that my function can treat as Times[constant, variable]

text: I want to define a function of two variables, `func[f_, g_]`, such that when it sees a general constant multiplying one of the variables, say `a`, it will take it outside the evaluated expression. So for example, if `f` and `g` are variables and `a` is a constant multiplying `g`, it will be evaluated as               func[f_, a_ g_]:= a func[f_, g_]      I need to inform _Mathematica_ that `a` is a constant, not a variable, and that it should be pulled out of the expression.


title: How to make a dynamic stopwatch?

text: For some experiments I need some basic timer function. I tried various methods, and neither of them are fully satisfactory. What I need is a button, that starts/stops a timer, resets timer with each restart, updates some other variables as well besides the timer and has a trigger effect when started/stopped too. It should also be customizable for having any text on the button. Let's see how `Trigger` behaves. First, define a switch that tests whether the counter is `active` or not, a `total` time of 50, and continuous variables for the running `time` and `timeLeft`:               active = False;     time = 0;     total = timeLeft = 50;      The `Trigger` should switch `active` and update `time` and `timeLeft`:               Trigger[Dynamic[time, (time = #; timeLeft = total - #;          active = 0 < # < total) &], {0, total}]          Dynamic@Column@{time, timeLeft, active}      This however has the following issues:   * There seems to be no way to stop the timer other than the `Trigger`'s own pause button.   * The way `active` is set is wasteful, it is unnecessary to test for it every timestep. Sadly, no other way I could figure out how to call a function _only once_ when the `Trigger` is started or stopped. I've tried to play with the start/end arguments (as in `Dynamic[var, {start, update, end}]`) with no success. Perhaps layering a button above the trigger? See next issue.   * No label can be given for the button. The option `Appearance` does not seem to have any effect here, and even if I remove all buttons via `AppearanceElements->{}`, I cannot overlay a normal button over it and wrap it in an `EventHandler` that passes events down to the trigger, as the Trigger object cannot be set to have the same `ImageSize` as the `Button`: .               EventHandler[Overlay[{        Button[Dynamic@If[active, "Stop", "Start"]],        Trigger[         Dynamic[time, (time = #; timeLeft = total - #) &], {0, total},          AppearanceElements -> {"TriggerButton"(*,"PauseButton",           "ResetButton"*)}]        }],      {"MouseClicked" :> (active = ! active)}, PassEventsDown -> True]     Dynamic@Column@{time, timeLeft, active}      ![Mathematica graphics](http://i.stack.imgur.com/Iizlj.png) I also tried to construct my own clock function, as follows. It uses a global clock, that starts immediately when the cell is generated, thus it always runs in the background, and the actual stopwatch is created by subtracting the start time (the moment the button is pushed) from the global clock.               active = False;     total = 50;     start = end = time = 0;          Column@{       Dynamic[globalTime = Clock[{0, total}]; time = globalTime - start;         globalTime],       Dynamic@If[active, time, end - start],       Dynamic@Button[If[active, "Stop", "Start"],          If[active, end = globalTime, start = globalTime];          active = ! active]       }      ![Mathematica graphics](http://i.stack.imgur.com/wEpI8.png) (Note that the actual dynamic value of `globalTime` (upper value) is not copied correctly via Szabolcs's otherwise magnificent image upload palette, and it shows less than _time_ (lower value).) However, It has the annoying feature that if `globalTime` does not appear on screen, no dynamic updating is done. Thus if I want to hide it, I have to wrap it into `Style[..., Opacity[0]]`. Also, `time` is constantly (and unnecessarily) updated, even if the button was not pushed. **Question** **Is there any reliable built-in way to provide such a functionality? How would you solve this problem?** I am interested in any idea, as for the last 3 months, I had to construct 3 guis with three different timing functions, and there is always something new (request/issue/feature) I have to deal with.