Fitting the Plot by fourier Series of either sine or cosine

I have list of data and its plot and I don't know how to fit the plot with fourier series of either sine or cosine. Full Data:               {{0., -0.176091}, {0.034, -0.163291}, {0.067, -0.156391}, {0.1,     -0.152791}, {0.134, -0.149391}, {0.167, -0.144791}, {0.2, -0.141291},      {0.234, -0.135991}, {0.267, -0.126191}, {0.301, -0.123591}, {0.334,      -0.113091}, {0.367, -0.108991}, {0.401, -0.0985909}, {0.434,      -0.0929909}, {0.467, -0.0891909}, {0.501, -0.0831909}, {0.534,      -0.0748909}, {0.567, -0.0667909}, {0.601, -0.0666909}, {0.634,     -0.0679909}, {0.668, -0.0678909}, {0.701, -0.0731909}, {0.734,      -0.0735909}, {0.768, -0.0720909}, {0.801, -0.0690909}, {0.834,      -0.0689909}, {0.868, -0.0634909}, {0.901, -0.0585909}, {0.934,      -0.0551909}, {0.968, -0.0534909}, {1.001, -0.0486909}, {1.035,      -0.0470909}, {1.068, -0.0449909}, {1.101, -0.0424909}, {1.135,     -0.0426909}, {1.168, -0.0407909}, {1.201, -0.0404909}, {1.235,      -0.0379909}, {1.268, -0.0379909}, {1.301, -0.0387909}, {1.335,      -0.0422909}, {1.368, -0.0441909}, {1.402, -0.0480909}, {1.435,     -0.0532909}, {1.468, -0.0636909}, {1.502, -0.0672909}, {1.535,      -0.0740909}, {1.569, -0.0825909}, {1.602, -0.0927909}, {1.635,      -0.102191}, {1.669, -0.108991}, {1.702, -0.120491}, {1.736,      -0.134691}, {1.769, -0.139191}, {1.802, -0.152791}, {1.836,      -0.168791}, {1.869, -0.182891}, {1.902, -0.191091}, {1.936,     -0.198991}, {1.969, -0.219991}, {2.002, -0.236191}, {2.035,      -0.243891}, {2.069, -0.255391}, {2.102, -0.268591}, {2.136,      -0.281391}, {2.169, -0.292691}, {2.202, -0.296891}, {2.236,      -0.313391}, {2.269, -0.323991}, {2.302, -0.334691}, {2.337,     -0.342691}, {2.369, -0.352291}, {2.402, -0.359091}, {2.436,      -0.367891}, {2.469, -0.372091}, {2.502, -0.375991}, {2.536,      -0.377191}, {2.569, -0.376691}, {2.603, -0.377891}, {2.636,      -0.377191}, {2.669, -0.369691}, {2.703, -0.361491}, {2.736,      -0.349791}, {2.769, -0.341491}, {2.803, -0.338591}, {2.837,      -0.333591}, {2.869, -0.321591}, {2.903, -0.311191}, {2.936,      -0.303291}, {2.97, -0.289291}, {3.003, -0.284691}, {3.036,     -0.279691}, {3.07, -0.259491}, {3.103, -0.247591}, {3.136,      -0.244791}, {3.17, -0.236991}, {3.203, -0.231191}, {3.236,      -0.215191}, {3.27, -0.201091}, {3.303, -0.194591}, {3.337,      -0.187891}, {3.37, -0.182991}, {3.403, -0.173591}, {3.437,      -0.160891}, {3.47, -0.157091}, {3.503, -0.150791}, {3.537,-0.142991}, {3.57, -0.137591}, {3.604, -0.131591}, {3.637,      -0.116991}, {3.67, -0.108091}, {3.704, -0.101591}, {3.737,      -0.101591}, {3.77, -0.101591}, {3.804, -0.100291}, {3.837,      -0.104591}, {3.87, -0.112991}, {3.904, -0.122591}, {3.937,      -0.137291}, {3.971, -0.146891}, {4.004, -0.157091}, {4.037,      -0.173491}, {4.071, -0.190691}, {4.104, -0.202191}, {4.137,      -0.219491}, {4.171, -0.231491}, {4.204, -0.238291}, {4.238,      -0.247191}, {4.271, -0.264391}, {4.305, -0.281991}, {4.338,      -0.285991}, {4.371, -0.288691}, {4.404, -0.302691}, {4.438,     -0.310891}, {4.471, -0.319791}, {4.504, -0.325891}, {4.538,     -0.330891}, {4.571, -0.333291}, {4.605, -0.338791}, {4.638,      -0.351091}, {4.671, -0.359491}, {4.705, -0.363591}, {4.738,      -0.370191}, {4.771, -0.378591}, {4.805, -0.385291}, {4.838,      -0.393591}, {4.871, -0.403191}, {4.905, -0.410791}, {4.938,      -0.420591}, {4.972, -0.425491}, {5.005, -0.429491}, {5.038,      -0.428791}, {5.072, -0.423291}, {5.105, -0.411891}, {5.138,      -0.402391}, {5.172, -0.392591}, {5.205, -0.381591}, {5.239,      -0.371091}, {5.272, -0.353891}, {5.305, -0.341791}, {5.339,      -0.335791}, {5.372, -0.325091}, {5.405, -0.309291}, {5.439,      -0.301791}, {5.472, -0.296091}, {5.505, -0.289291}, {5.539,      -0.284391}, {5.572, -0.275991}, {5.606, -0.266891}, {5.639,      -0.259291}, {5.672, -0.251191}, {5.706, -0.242291}, {5.739,      -0.233391}, {5.773, -0.221291}, {5.806, -0.207391}, {5.839,      -0.196291}, {5.873, -0.192791}, {5.906, -0.185991}, {5.939,      -0.176191}, {5.973, -0.165291}, {6.006, -0.152591}, {6.039,     -0.148691}, {6.073, -0.136091}, {6.106, -0.127591}, {6.14,      -0.119391}, {6.173, -0.113891}, {6.206, -0.106791}, {6.24,      -0.0938909}, {6.273, -0.0782909}, {6.306, -0.0742909}, {6.34,      -0.0710909}, {6.373, -0.0606909}, {6.406, -0.0489909}, {6.44,      -0.0412909}, {6.473, -0.0289909}, {6.506, -0.0232909}, {6.54,      -0.0150909}, {6.573, -0.00669086}, {6.607, 0.00140914}, {6.64,        0.00980914}, {6.673, 0.0133091}, {6.707, 0.0205091}, {6.74,        0.0226091}, {6.773, 0.0255091}, {6.807, 0.0254091}, {6.84,        0.0259091}, {6.874, 0.0250091}, {6.907, 0.0299091}, {6.94,        0.0401091}, {6.974, 0.0428091}, {7.007, 0.0410091}, {7.04,        0.0410091}, {7.074, 0.0406091}, {7.107, 0.0370091}, {7.141,        0.0326091}, {7.174, 0.0246091}, {7.207, 0.0196091}, {7.241,        0.0131091}, {7.274,        0.00230914}, {7.307, -0.00419086}, {7.341, -0.0222909}, {7.374,      -0.0349909}, {7.408, -0.0534909}, {7.441, -0.0693909}, {7.474,      -0.0898909}, {7.508, -0.103991}, {7.541, -0.121191}, {7.574,      -0.133891}, {7.608, -0.142891}, {7.641, -0.156591}, {7.674,      -0.173991}, {7.708, -0.188791}, {7.741, -0.197691}, {7.775,      -0.205891}, {7.808, -0.222291}, {7.841, -0.228991}, {7.875,      -0.234191}, {7.908, -0.240591}, {7.941, -0.245191}, {7.975,      -0.254191}, {8.008, -0.265391}, {8.041, -0.271791}, {8.075,      -0.277791}, {8.108, -0.283791}, {8.142, -0.284791}, {8.175,      -0.286991}, {8.208, -0.299891}, {8.242, -0.307491}, {8.275,      -0.309591}, {8.308, -0.314391}, {8.342, -0.321791}, {8.375,      -0.324191}, {8.409, -0.324691}, {8.442, -0.324191}, {8.475,      -0.317291}, {8.509, -0.308491}, {8.542, -0.296091}, {8.575,      -0.287691}, {8.609, -0.283691}, {8.642, -0.275491}, {8.675,      -0.271491}, {8.709, -0.268991}, {8.742, -0.256991}, {8.776,      -0.246491}, {8.809, -0.244191}, {8.842, -0.240491}, {8.876,      -0.233391}, {8.909, -0.226791}, {8.942, -0.211891}, {8.976,      -0.198891}, {9.009, -0.195791}, {9.042, -0.191491}, {9.076,      -0.185791}, {9.109, -0.177791}, {9.143, -0.169491}, {9.176,      -0.163891}, {9.209, -0.149591}, {9.243, -0.144191}, {9.276,      -0.139191}, {9.309, -0.127391}, {9.343, -0.113491}, {9.376,      -0.108791}, {9.41, -0.0967909}, {9.443, -0.0905909}, {9.476,      -0.0789909}, {9.51, -0.0755909}, {9.543, -0.0740909}, {9.576,      -0.0666909}, {9.61, -0.0640909}, {9.643, -0.0581909}, {9.676,      -0.0575909}, {9.71, -0.0627909}, {9.743, -0.0715909}, {9.776,      -0.0876909}, {9.81, -0.0975909}, {9.843, -0.107691}, {9.877,      -0.130391}, {9.91, -0.140491}, {9.943, -0.152091}, {9.977,      -0.159191}, {10.01, -0.160591}, {10.044, -0.185091}, {10.077,      -0.215291}, {10.11, -0.243091}, {10.144, -0.264791}, {10.177,      -0.272491}, {10.21, -0.272791}, {10.244, -0.262091}, {10.277,      -0.247391}, {10.31, -0.243391}, {10.344, -0.239291}, {10.377,      -0.234891}, {10.411, -0.233991}, {10.444, -0.233691}, {10.477,      -0.203691}, {10.511, -0.157191}, {10.544, -0.148491}, {10.577,      -0.148491}, {10.611, -0.148691}, {10.644, -0.143591}, {10.678,      -0.133091}, {10.711, -0.123391}, {10.744, -0.116991}, {10.778,      -0.111891}, {10.811, -0.101491}, {10.845, -0.0897909}, {10.878,      -0.0858909}, {10.911, -0.0777909}, {10.945, -0.0730909}, {10.978,      -0.0731909}, {11.011, -0.0639909}, {11.045, -0.0559909}, {11.078,      -0.0469909}, {11.111, -0.0414909}, {11.145, -0.0336909}, {11.178,      -0.0258909}, {11.211, -0.0174909}, {11.245, -0.00539086}, {11.278,      -0.00059086}, {11.312, 0.00330914}, {11.345, 0.00680914}, {11.378,        0.0155091}, {11.412, 0.0215091}, {11.445, 0.0219091}, {11.478,        0.0266091}, {11.512, 0.0286091}, {11.545, 0.0297091}, {11.58,        0.0274091}, {11.612, 0.0239091}, {11.645, 0.0172091}, {11.679,        0.0113091}, {11.712, 0.0100091}, {11.746, 0.00680914}, {11.779,        0.00770914}, {11.812, 0.00470914}, {11.846, 0.00280914}, {11.879,        0.00370914}, {11.912, 0.00490914}, {11.946, 0.00140914}, {11.979,        0.00130914}, {12.013, 0.00450914}, {12.046, 0.00850914}, {12.079,        0.00830914}, {12.113, 0.00660914}, {12.146, 0.00930914}, {12.18,        0.0105091}, {12.213, 0.00980914}, {12.246, 0.00700914}, {12.279,        0.00520914}, {12.313, -0.0000908604}, {12.346, 0.00330914}, {12.38,        0.00560914}, {12.413, 0.00620914}, {12.446, 0.0191091}, {12.48,        0.0241091}, {12.513, 0.0242091}, {12.546, 0.0250091}, {12.58,        0.0318091}, {12.613, 0.0332091}, {12.646, 0.0370091}, {12.68,        0.0361091}, {12.713, 0.0374091}, {12.747, 0.0370091}, {12.78,        0.0379091}, {12.813, 0.0399091}, {12.847, 0.0394091}, {12.88,        0.0386091}, {12.914, 0.0379091}, {12.947, 0.0386091}, {12.98,        0.0413091}, {13.013, 0.0431091}, {13.047, 0.0459091}, {13.08,        0.0466091}, {13.114, 0.0436091}, {13.147, 0.0419091}, {13.181,        0.0427091}, {13.214, 0.0436091}, {13.247, 0.0394091}, {13.28,        0.0378091}, {13.314, 0.0341091}, {13.347, 0.0224091}, {13.38,        0.0180091}, {13.414, 0.00960914}, {13.448,        0.00410914}, {13.481, -0.00819086}, {13.514, -0.0264909}, {13.547,      -0.0456909}, {13.581, -0.0626909}, {13.614, -0.0694909}, {13.648,      -0.0821909}, {13.681, -0.0941909}, {13.714, -0.113991}, {13.748,      -0.132791}, {13.781, -0.143691}, {13.814, -0.150791}, {13.848,      -0.162191}, {13.881, -0.178391}, {13.915, -0.189691}, {13.948,      -0.195791}, {13.981, -0.203191}, {14.015, -0.223491}, {14.048,      -0.230991}, {14.081, -0.238491}, {14.115, -0.246791}, {14.148,      -0.263591}, {14.182, -0.278591}, {14.215, -0.291291}, {14.248,      -0.296291}, {14.281, -0.300191}, {14.315, -0.298991}, {14.348,      -0.300991}, {14.381, -0.295691}, {14.415, -0.290191}, {14.448,      -0.280791}, {14.482, -0.275191}, {14.515, -0.263791}, {14.548,      -0.251391}, {14.582, -0.239491}, {14.615, -0.231591}, {14.648,      -0.222991}, {14.682, -0.208491}, {14.715, -0.195791}, {14.748,      -0.188491}, {14.782, -0.182491}, {14.816, -0.177191}, {14.849,      -0.165491}, {14.882, -0.155491}, {14.916, -0.146391}, {14.949,      -0.136891}, {14.982, -0.135591}, {15.015, -0.131191}, {15.049,      -0.122891}, {15.082, -0.117491}, {15.116, -0.116591}, {15.149,      -0.117291}, {15.182, -0.121291}, {15.216, -0.123791}, {15.249,      -0.131291}, {15.282, -0.137891}, {15.316, -0.149291}, {15.35,      -0.162091}, {15.383, -0.177391}, {15.416, -0.189691}, {15.449,      -0.201891}, {15.483, -0.214291}, {15.516, -0.225291}, {15.549,      -0.227691}, {15.583, -0.225691}, {15.616, -0.223491}, {15.65,      -0.230191}, {15.683, -0.246191}, {15.717, -0.275491}, {15.75,      -0.296991}, {15.783, -0.311691}, {15.817, -0.289291}, {15.85,      -0.272091}, {15.883, -0.270291}, {15.916, -0.281991}, {15.95,      -0.261391}, {15.983, -0.233891}, {16.017, -0.231791}, {16.05,      -0.234491}, {16.083, -0.220791}, {16.117, -0.185091}, {16.15,      -0.172991}, {16.183, -0.177391}, {16.217, -0.178591}, {16.25,      -0.169891}, {16.284, -0.157691}, {16.317, -0.150291}, {16.35,      -0.143791}, {16.384, -0.141791}, {16.417, -0.140791}, {16.451,      -0.138491}, {16.484, -0.130191}, {16.517, -0.118191}, {16.551,      -0.110491}, {16.584, -0.103891}, {16.618, -0.0959909}, {16.651,      -0.0904909}, {16.684, -0.0904909}, {16.718, -0.0836909}, {16.751,      -0.0777909}, {16.784, -0.0724909}, {16.817, -0.0674909}, {16.851,      -0.0596909}, {16.884, -0.0515909}, {16.918, -0.0463909}, {16.951,      -0.0331909}, {16.984, -0.0270909}, {17.018, -0.0224909}, {17.051,      -0.0218909}, {17.084, -0.0183909}, {17.118, -0.0119909}, {17.151,      -0.00359086}, {17.185, 0.00700914}, {17.218, 0.00790914}, {17.251,        0.0137091}, {17.285, 0.0175091}, {17.318, 0.0217091}, {17.351,        0.0281091}, {17.385, 0.0313091}, {17.418, 0.0370091}, {17.451,        0.0384091}, {17.485, 0.0384091}, {17.518, 0.0418091}, {17.552,        0.0398091}, {17.585, 0.0384091}, {17.618, 0.0480091}, {17.652,        0.0538091}, {17.685, 0.0548091}, {17.718, 0.0468091}, {17.752,        0.0407091}, {17.785, 0.0371091}, {17.818, 0.0346091}, {17.852,        0.0235091}, {17.885, 0.0168091}, {17.919, 0.0129091}, {17.952,        0.00860914}, {17.986,        0.00490914}, {18.019, -0.00749086}, {18.052, -0.0237909}, {18.087,     -0.0261909}, {18.119, -0.0401909}, {18.152, -0.0499909}, {18.186,      -0.0605909}, {18.219, -0.0764909}, {18.253, -0.0861909}, {18.286,      -0.0924909}, {18.319, -0.101291}, {18.352, -0.117191}, {18.386,      -0.126591}, {18.419, -0.139091}, {18.452, -0.146891}, {18.486,      -0.161391}, {18.519, -0.174391}, {18.553, -0.182491}, {18.587,      -0.193191}, {18.619, -0.195291}, {18.653, -0.204091}, {18.686,      -0.216891}, {18.72, -0.227591}, {18.753, -0.237291}, {18.786,      -0.241291}, {18.819, -0.245991}, {18.853, -0.254991}, {18.886,      -0.270091}, {18.92, -0.278391}, {18.953, -0.279591}, {18.986,      -0.284991}, {19.02, -0.292191}, {19.053, -0.294091}, {19.086,      -0.291091}, {19.12, -0.287191}, {19.153, -0.281091}, {19.186,      -0.277591}, {19.22, -0.270791}, {19.254, -0.261891}, {19.287,      -0.249191}, {19.32, -0.242891}, {19.353, -0.241091}, {19.387,      -0.235791}, {19.42, -0.229191}, {19.453, -0.222491}, {19.487,      -0.217291}, {19.52, -0.209791}, {19.554, -0.203391}, {19.588,      -0.197691}, {19.62, -0.187791}, {19.654, -0.178791}, {19.687,     -0.172691}, {19.72, -0.159691}, {19.754, -0.148191}, {19.787,      -0.138191}, {19.821, -0.127691}, {19.854, -0.117891}, {19.887,      -0.105391}, {19.921, -0.0924909}, {19.954, -0.0861909}, {19.988,      -0.0772909}, {20.021, -0.0648909}, {20.054, -0.0556909}, {20.087,      -0.0488909}, {20.121, -0.0394909}, {20.154, -0.0287909}, {20.188,      -0.0213909}, {20.221, -0.0153909}, {20.254, -0.0106909}, {20.288,      -0.00649086}, {20.322, 0.0114091}, {20.354, 0.0145091}, {20.388,        0.0144091}, {20.421, 0.0176091}, {20.455, 0.0183091}, {20.488,        0.0201091}, {20.521, 0.0279091}, {20.555, 0.0352091}, {20.588,        0.0421091}, {20.621, 0.0456091}, {20.655, 0.0477091}, {20.688,        0.0557091}, {20.722, 0.0580091}, {20.755, 0.0602091}, {20.788,        0.0637091}, {20.822, 0.0637091}, {20.855, 0.0691091}, {20.888,        0.0686091}, {20.922, 0.0674091}, {20.955, 0.0656091}, {20.989,        0.0704091}, {21.022, 0.0710091}, {21.056, 0.0712091}, {21.088,        0.0693091}, {21.122, 0.0697091}, {21.155, 0.0712091}, {21.188,        0.0705091}, {21.222, 0.0705091}, {21.255, 0.0696091}, {21.289,        0.0705091}, {21.322, 0.0691091}, {21.355, 0.0724091}, {21.389,        0.0724091}, {21.422, 0.0711091}, {21.455, 0.0707091}, {21.489,        0.0705091}, {21.522, 0.0694091}, {21.556, 0.0657091}, {21.589,        0.0632091}, {21.622, 0.0539091}, {21.656, 0.0461091}, {21.689,        0.0448091}, {21.722, 0.0351091}, {21.756, 0.0250091}, {21.789,        0.0183091}, {21.823, 0.00920914}, {21.856,        0.00010914}, {21.89, -0.0142909}, {21.923, -0.0217909}, {21.956,     -0.0273909}, {21.989, -0.0379909}, {22.023, -0.0471909}, {22.056,      -0.0487909}, {22.089, -0.0635909}, {22.123, -0.0775909}, {22.157,      -0.0885909}, {22.189, -0.0981909}, {22.223, -0.106291}, {22.256,     -0.121391}, {22.29, -0.135991}, {22.323, -0.145691}, {22.357,      -0.155891}, {22.39, -0.168691}, {22.424, -0.187791}, {22.456,      -0.201491}, {22.49, -0.213791}, {22.523, -0.230891}, {22.557,      -0.235091}, {22.59, -0.241291}, {22.623, -0.250991}, {22.657,      -0.265291}, {22.69, -0.279791}, {22.723, -0.284491}, {22.757,      -0.296391}, {22.79, -0.317691}, {22.824, -0.321991}, {22.857,      -0.329291}, {22.89, -0.332491}, {22.924, -0.332391}, {22.957,      -0.330691}, {22.99, -0.328191}, {23.024, -0.314891}, {23.057,      -0.301791}, {23.091, -0.296791}, {23.124, -0.288291}, {23.157,      -0.280491}, {23.191, -0.270791}, {23.224, -0.259591}, {23.257,      -0.251391}, {23.291, -0.239891}, {23.324, -0.237791}, {23.358,      -0.233791}, {23.391, -0.222491}, {23.424, -0.211591}, {23.458,      -0.210391}, {23.491, -0.203691}, {23.524, -0.198591}, {23.558,      -0.195691}, {23.591, -0.191591}, {23.624, -0.186991}, {23.658,      -0.185691}, {23.691, -0.180891}, {23.725, -0.171091}, {23.758,      -0.167991}, {23.791, -0.166091}, {23.824, -0.162691}, {23.858,      -0.149191}, {23.891, -0.145791}, {23.925, -0.134991}, {23.958,      -0.122291}, {23.991, -0.115091}, {24.025, -0.106691}, {24.058,      -0.102491}, {24.092, -0.0934909}, {24.125, -0.0914909}, {24.158,      -0.0871909}, {24.192, -0.0756909}, {24.225, -0.0709909}, {24.258,      -0.0594909}, {24.292, -0.0575909}, {24.325, -0.0567909}, {24.359,      -0.0535909}, {24.392, -0.0495909}, {24.425, -0.0410909}, {24.459,      -0.0401909}, {24.492, -0.0363909}, {24.525, -0.0332909}, {24.559,      -0.0315909}, {24.592, -0.0267909}, {24.626, -0.0248909}, {24.659,      -0.0169909}, {24.692, -0.0114909}, {24.725, -0.00659086}, {24.759,      -0.00119086}, {24.792, 0.00590914}, {24.826, 0.0110091}, {24.859,        0.0117091}, {24.893, 0.0118091}, {24.926, 0.0142091}, {24.959,        0.0103091}, {24.993,        0.00530914}, {25.026, -0.00219086}, {25.059, -0.00399086}, {25.092,        0.00250914}, {25.126, 0.0104091}, {25.16, 0.00570914}, {25.193,        0.00620914}, {25.226, 0.00510914}, {25.259, 0.00370914}, {25.293,        0.00580914}, {25.326, 0.00760914}, {25.36, 0.0110091}, {25.393,        0.0129091}, {25.426, 0.0126091}, {25.459, 0.0139091}, {25.493,        0.0148091}, {25.526, 0.0178091}, {25.56, 0.0205091}, {25.593,        0.0200091}, {25.626, 0.0205091}, {25.66, 0.0209091}, {25.693,        0.0179091}, {25.727, 0.0129091}, {25.76, 0.00490914}, {25.793,        0.00280914}, {25.827, -0.00349086}, {25.86, -0.0106909}, {25.893,     -0.0205909}, {25.927, -0.0304909}, {25.96, -0.0372909}, {25.993,      -0.0457909}, {26.027, -0.0514909}, {26.06, -0.0641909}, {26.094,      -0.0774909}, {26.127, -0.0875909}, {26.16, -0.0986909}, {26.194,      -0.111591}, {26.227, -0.125291}, {26.26, -0.136691}, {26.294,-0.146391}, {26.327, -0.160691}, {26.361, -0.177291}, {26.394,      -0.193791}, {26.427, -0.207691}, {26.461, -0.221691}, {26.494,      -0.231391}, {26.527, -0.243591}, {26.561, -0.261691}, {26.595,      -0.280291}, {26.627, -0.287191}, {26.661, -0.300991}, {26.694,      -0.317491}, {26.728, -0.325491}, {26.761, -0.330891}, {26.794,     -0.342691}, {26.828, -0.349091}, {26.861, -0.358891}, {26.894,      -0.373891}, {26.928, -0.379791}, {26.961, -0.382891}, {26.994,      -0.385391}, {27.028, -0.386191}, {27.061, -0.381991}, {27.095,      -0.377691}, {27.128, -0.368991}, {27.161, -0.358691}, {27.195,      -0.345991}, {27.228, -0.341191}, {27.261, -0.337791}, {27.295,      -0.328791}, {27.328, -0.323091}, {27.362, -0.310791}, {27.395,      -0.301091}, {27.428, -0.290891}, {27.462, -0.282591}, {27.495,      -0.275791}, {27.529, -0.258291}, {27.562, -0.252991}, {27.595,      -0.244791}, {27.629, -0.238991}, {27.662, -0.234291}, {27.695,      -0.228291}, {27.729, -0.219491}, {27.762, -0.216991}, {27.795,      -0.211691}, {27.829, -0.205591}, {27.862, -0.202391}, {27.895,      -0.202991}, {27.929, -0.203891}, {27.962, -0.204391}, {27.996,      -0.203891}, {28.029, -0.198791}, {28.062, -0.193691}, {28.096,      -0.191491}, {28.129, -0.191991}, {28.162, -0.194391}, {28.196,      -0.201891}, {28.229, -0.219591}, {28.262, -0.240891}, {28.296,      -0.265491}, {28.329, -0.270991}, {28.363, -0.245291}, {28.396,      -0.234191}, {28.429, -0.230191}, {28.463, -0.230591}, {28.496,      -0.210591}, {28.529, -0.189991}, {28.563, -0.188491}, {28.596,     -0.181291}, {28.63, -0.156991}, {28.663, -0.146191}, {28.696,      -0.146091}, {28.73, -0.148191}, {28.763, -0.144691}, {28.796,      -0.137391}, {28.83, -0.130191}, {28.863, -0.122891}, {28.896,      -0.111391}, {28.93, -0.107091}, {28.963, -0.0970909}, {28.997,      -0.0891909}, {29.03, -0.0774909}, {29.063, -0.0731909}, {29.097,      -0.0659909}, {29.13, -0.0527909}, {29.164, -0.0428909}, {29.197,      -0.0354909}, {29.23, -0.0246909}, {29.263, -0.0196909}, {29.297,      -0.0161909}, {29.33, -0.0139909}, {29.364, -0.0113909}, {29.397,      -0.00589086}, {29.43, -0.00259086}, {29.464, -0.00219086}, {29.497,      -0.00219086}, {29.53, -0.00199086}, {29.564, -0.00269086}, {29.597,      -0.00989086}, {29.63, -0.0256909}, {29.664, -0.0306909}, {29.697,      -0.0460909}, {29.73, -0.0574909}, {29.764, -0.0722909}, {29.797,      -0.0874909}, {29.831, -0.102591}, {29.864, -0.117291}, {29.898,      -0.134191}, {29.931, -0.148991}, {29.964, -0.165391}, {29.998,      -0.187091}, {30.031, -0.197291}, {30.064, -0.206891}, {30.098,      -0.219791}, {30.131, -0.230491}, {30.164, -0.233891}, {30.198,      -0.239491}, {30.231, -0.249491}, {30.265, -0.260891}, {30.298,      -0.279191}, {30.331, -0.284591}, {30.365, -0.292591}, {30.398,      -0.297491}, {30.431, -0.307391}, {30.465, -0.317591}, {30.498,      -0.321491}, {30.531, -0.322391}, {30.565, -0.316891}, {30.598,      -0.318591}, {30.632, -0.322391}, {30.665, -0.328791}, {30.698,      -0.332291}, {30.732, -0.334091}, {30.765, -0.334091}, {30.798,      -0.334091}, {30.832, -0.337691}, {30.865, -0.338491}, {30.899,      -0.338491}, {30.932, -0.337591}, {30.965, -0.341491}, {30.999,      -0.343491}, {31.032, -0.346791}, {31.065, -0.353091}, {31.099,      -0.354991}, {31.132, -0.353991}, {31.166, -0.355691}, {31.199,      -0.351291}, {31.232, -0.340791}, {31.266, -0.334091}, {31.299,      -0.330791}, {31.332, -0.326091}, {31.366, -0.309391}, {31.399,      -0.295391}, {31.432, -0.285991}, {31.466, -0.275391}, {31.499,      -0.265091}, {31.533, -0.256591}, {31.566, -0.242991}, {31.599,      -0.230091}, {31.633, -0.219391}, {31.666, -0.203691}, {31.699,      -0.189291}, {31.733, -0.183891}, {31.767, -0.169391}, {31.799,      -0.167091}, {31.833, -0.157091}, {31.866, -0.150791}, {31.9,      -0.137991}, {31.933, -0.123091}, {31.966, -0.114891}, {32.,      -0.108691}, {32.033, -0.0979909}, {32.066, -0.0907909}, {32.1,      -0.0796909}, {32.133, -0.0709909}, {32.166, -0.0611909}, {32.2,      -0.0513909}, {32.233, -0.0411909}, {32.267, -0.0323909}, {32.3,      -0.0251909}, {32.333, -0.0188909}, {32.367, -0.0125909}, {32.4,      -0.00609086}, {32.433, 0.00120914}, {32.467, 0.0100091}, {32.5,        0.0127091}, {32.533, 0.0126091}, {32.567, 0.0154091}, {32.601,        0.0235091}, {32.633, 0.0270091}, {32.667, 0.0255091}, {32.7,        0.0262091}, {32.734, 0.0262091}, {32.767, 0.0262091}, {32.8,        0.0257091}, {32.834, 0.0237091}, {32.867, 0.0241091}, {32.901,        0.0252091}, {32.934, 0.0262091}, {32.967, 0.0286091}, {33.001,        0.0328091}, {33.034, 0.0380091}, {33.067, 0.0442091}, {33.101,        0.0433091}, {33.134, 0.0389091}, {33.168, 0.0373091}, {33.201,        0.0316091}, {33.234, 0.0274091}, {33.268, 0.0295091}, {33.301,        0.0342091}, {33.334, 0.0312091}, {33.368, 0.0305091}, {33.401,        0.0299091}, {33.434, 0.0295091}, {33.468, 0.0346091}, {33.501,        0.0386091}, {33.535, 0.0375091}, {33.568, 0.0380091}, {33.601,        0.0443091}, {33.635, 0.0462091}, {33.668, 0.0469091}, {33.701,        0.0482091}, {33.735, 0.0500091}, {33.768, 0.0536091}, {33.801,        0.0540091}, {33.835, 0.0520091}, {33.868, 0.0532091}, {33.901,        0.0489091}, {33.935, 0.0472091}, {33.968, 0.0521091}, {34.002,        0.0484091}, {34.035, 0.0465091}, {34.068, 0.0456091}, {34.102,        0.0414091}, {34.135, 0.0386091}, {34.169, 0.0347091}, {34.202,        0.0271091}, {34.235, 0.0255091}, {34.269, 0.0161091}, {34.302,        0.0125091}, {34.338,        0.00480914}, {34.369, -0.00539086}, {34.402, -0.0129909}, {34.435,      -0.0208909}, {34.469, -0.0297909}, {34.502, -0.0326909}, {34.536,      -0.0474909}, {34.569, -0.0595909}, {34.602, -0.0718909}, {34.636,      -0.0764909}, {34.669, -0.0861909}, {34.703, -0.0960909}, {34.736,      -0.107591}, {34.769, -0.117691}}      ` This is the graph of whole data. ![enter image description here](http://i.stack.imgur.com/Gt9P1.jpg)


Checking equality with ComplexInfinity and testing whether a function is (mathematically) undefined

This seems ridiculously basic, but I cannot find anywhere explaining how to do it. If you evaluate certain undefined functions like `1/0` or `Tan[\[Pi]/2]`, Mathematica evaluates to `ComplexInfinity`. For some reason, however, the following expression does not act as expected:               1/0 == ComplexInfinity      This results in > ComplexInfinity == ComplexInfinity rather than the expected > True So the question is, how do you test whether a function evaluates to `ComplexInfinity`, or better yet, how do you test if a function is (mathematically, not programmatically) undefined?


MinGW-64 and CompilationTarget -> "C": can't make library

I'm trying to set up my new Windows 8.1 tablet to compile Mathematica (9.0.1) functions to C, using the MinGW-64 compiler. I have it set up so that the following works:               greeter = CreateExecutable[StringJoin[         "#include <stdio.h>\n",         "int main(){\n",         "  printf(\"Hello MinGW-w64 world.\\n\");\n",         "}\n"],        "hiworld"];     Import["!\"" <> greeter <> "\"", "Text"]      However, function compilation to C fails, as follows:               zeroC = Compile[{         },        0,        CompilationTarget -> "C"        ];          CreateLibrary::cmperr: "Compile error: collect2.exe: error: ld returned 1 exit status          Compile::nogen: A library could not be generated from the compiled function.      On an older computer that I had previously set up for compilation, this same function definition works fine. Any clues as to what is going wrong? It would of course be helpful if I could see exactly what commands Mathematica is passing to the shell, and what complaint ld makes. `CreateExecutable` has an option `"ShellOutputFunction" -> Print` that shows what it's doing, but I can't figure out how to pass this to `Compile`.


Animation of double pendulum

Sadly, I am a completely newbie. I am studying Physics and in our theoretical physics class we got the task to solve the double pendulum using _Mathematica_. We just got the program, but no introduction how to use it. So I am trying to animate the parametric plot. Any ideas?               sol = NDSolve[{       2*phi1''[t] + phi2''[t]*Cos[phi1[t] - phi2[t]] +          phi2'[t]^(2)*Sin[phi1[t] - phi2[t]] + 2*9.81*Sin[phi1[t]] ==        phi2''[t] + phi1''[t]*Cos[phi1[t] - phi2[t]] -          phi1'[t]^(2)*Sin[phi1[t] - phi2[t]] + 9.81*Sin[phi2[t]] == 0,        phi1[0] == Pi/2, phi2[0] == Pi, phi1'[0] == 0, phi2'[0] == 0},        {phi1[t], phi2[t], t}, {t, 0, 10}]           Plot[{phi1[t], phi2[t]} /. sol, {t, 0, 10}]          x1[t] := Evaluate[Sin[phi1[t]] /. sol]     y1[t] := Evaluate[-Cos[phi1[t]] /. sol]     x2[t] := Evaluate[Sin[phi1[t]] + Sin[phi2[t]] /. sol]     y2[t] := Evaluate[-(Cos[phi1[t]] + Cos[phi2[t]]) /. sol]          ParametricPlot[Evaluate[{{x1[t], y1[t]}, {x2[t], y2[t]}} /. sol], {t, 0, 10}]


Strategies for solving problems involving searches

As an example of a search-oriented problem, consider finding _**all** constrained $n$-colorings of a graph._ An "$n$-coloring" associates one of $n \ge 1$ colors to each vertex in such a way that no edge connects vertices of the same color. A "constrained" coloring requires that certain vertices have certain fixed colors. For instance, here is a graph with one of its vertices already colored red; the default (cyan) vertices are as yet uncolored: ![Partial coloring of a graph](http://i.stack.imgur.com/YDEvm.png) There are 10 ways to color this graph using three colors; say, {red, green, blue}, while keeping the red vertex red: ![All constrained 3-colorings](http://i.stack.imgur.com/QfxRE.png) (Notice that the colorings are _not_ up to isomorphism: all six vertices are considered to be distinct and not interchangeable.) These solutions are found with a brute-force recursive search. The approach exemplifies a large class of problems, such as playing games and solving puzzles. In most interesting cases the search can take a long time (and have a large amount of output), so it is important to find appropriate data structures and efficient search methods. **I am interested in _Mathematica_ -specific advice and strategies for making such searches efficient.** To make this question clearer and more focused, I invite your critical comments concerning this particular solution to the constrained $n$-coloring problem:               constrainedColorings[graph[vertices_, nbrhds_], colors_List, start_List] := Module[        {unassigned, v, candidates},        unassigned = Complement[vertices, start[[All, 1]]];        If[unassigned == {}, Return[start]];        v = First[unassigned];        candidates = Complement[colors, v /. nbrhds /. start];        Map[constrainedColorings[graph[vertices, nbrhds], colors, Append[start, v -> #]] &, candidates]        ];      Its arguments are   * `graph`, which contains a list of the vertices and a list of rules assigning to each vertex the set of its immediate neighbors in the graph;   * `colors`, which is a list of the available colors; and   * `start`, which is a (possibly empty) list of rules assigning vertices to colors: it stipulates any constraints. It is expected that the colors appearing in `start` are contained within `colors`. Its output is a deeply nested list (representing the search tree) whose leaves are lists of rules assigning colors to vertices. Like most such searches, it follows a familiar logic:   1. Determine whether the search is finished.   2. If not, make a list of possible next moves (`candidates`),   3. ... and tentatively make each move in turn, recursively searching for all solutions arising from it.   4. Return a set of all solutions found. To illustrate its use, consider the preceding example. It started out as a _Mathematica_ `Graph` (in order to exploit its graph visualization capabilities) and was converted into a more convenient `graph` structure for this search:               \[Gamma] = Graph[{v1, v2, v3, v4, v5},        {v1 \[UndirectedEdge] v2, v1 \[UndirectedEdge] v4, v1 \[UndirectedEdge] v5,         v2 \[UndirectedEdge] v3, v3 \[UndirectedEdge] v4, v3 \[UndirectedEdge] v5},       VertexShapeFunction -> "Circle", VertexSize -> 0.4];     g = graph[VertexList[\[Gamma]], # -> Cases[EdgeList[\[Gamma]],             # \[UndirectedEdge] v_ | v_ \[UndirectedEdge] # -> v] & /@ VertexList[\[Gamma]]];      Here is the search itself, whereby the available colors are stipulated and the initial constraints are provided:               colorings = constrainedColorings[g, {Red, Green, Blue}, {v5 -> Red}];      We can flatten the output to get a list of all solutions:               colorings /. x : List[_Rule ..] :> coloring @@ x // Flatten      If you care to play with this code, you will want to draw the output:               display[g_Graph, c_coloring] :=  HighlightGraph[g, List @@ c /. Rule -> Style];     display[\[Gamma], #] & /@ colorings      Here, then, is the specific question:   * **In what ways can this code be improved to be faster, simpler, and more flexible?** I am especially interested in advice that would apply not just to this particular problem but to the entire class of problems. What kinds of data structures should one prefer to represent combinatorial objects: arrays, rules, something else? Or perhaps there is no general answer? Are there ways to expedite such searches, such as (possibly) exploiting _Mathematica's_ built-in graph programming capabilities? General replies are fine and so are answers that specifically improve the code here, provided it is clear how such improvements could be applied more generally.


StreamPlot using NDSolve gives error messages

StreamPlot[{x[0], x'[0]} /.        NDSolve[{x''[t] ==  1, x'[0] == v0, x[0] == x0}, {x, x'}, {t, 0, 1}],      {x0, -2, 2}, {v0, -2, 2}]      The above code gives me the errors > NDSolve::ndinnt: Initial condition x0 is not a number or a rectangular array > of numbers. >> > > ReplaceAll::reps: > {NDSolve[{(x^[Prime][Prime])[t]==1,(x^[Prime])[0]==v0,x[0]==x0},{x,x^[Prime]},{t,0,1}]} > is neither a list of replacement rules nor a valid dispatch table, and so > cannot be used for replacing. >> > > NDSolve::ndinnt: Initial condition x0 is not a number or a rectangular array > of numbers. >> > > ReplaceAll::reps: > {NDSolve[{(x^[Prime][Prime])[t]==1,(x^[Prime])[0]==v0,x[0]==x0},{x,x^[Prime]},{t,0,1}]} > is neither a list of replacement rules nor a valid dispatch table, and so > cannot be used for replacing. >> While the code still produces the plot that I want, is it possible to get rid of the error messages?


How can I change cursor style in InputField?

I want to make an `InputField` with a horizontal cursor, like this: ![enter image description here](http://i.stack.imgur.com/HQfAi.png) Note that the blinking cursor should be horizontal and not the mouse pointer! Nevertheless, text input should still be horizontal and not vertical. The code below shows an `InputField` with the standard vertical cursor but I want a horizontal one.               x = Null;     Style[InputField[Dynamic[x], ImageSize -> {180, 60}, Alignment -> Center], Bold, 20]      Is this possible?


Non-preemptive evaluation of a dynamic function?

I want to monitor a long calculation that is triggered by the release of a `Slider`. While one can indicate running calculations when the main evaluation loop is controlled by a queued `Button`, the same cannot be done with more direct `Dynamic` approaches. A bit of trial and error actually confirms that only `Button` and not any of the other controls (`Slider`, `Locator`, even `EventHandler`) can be evaluated non-preemptively. This works as expected, displaying a `ProgressIndicator` while the long calculation is performing:               long[] := Module[{a = .3}, Do[a = 3.5 a (1 - a), {i, n}]];     {active, x} = {False, 1};     {Slider[Dynamic@x, {0, 1}],       Button["Update", (active = True; long[]; active = False;), Method -> "Queued"]}     Dynamic@{If[active, ProgressIndicator[i, {0, 10^6}], "..."], active}      ![Mathematica graphics](http://i.stack.imgur.com/vF9QG.png) The same cannot be done using a `Slider`. The update command was put in the second argument of `Dynamic`, more precisely in the slot which is evaluated when the controller is released. As you can see, it still evaluates `long` (the string is printed) but it does not switch `active` and consequently it does not display the `ProgressIndicator`.               long[] := Module[{a = .3}, Do[a = 3.5 a (1 - a), {i, 10^6}]];     {active, x} = {False, 1};     Slider[Dynamic[x, {(x = #) &, (active = True; Print["evaluating..."]; long[];           active = False) &}], {0, 1}]     Dynamic@{If[active, ProgressIndicator[i, {0, 10^6}], "..."], active}      ![Mathematica graphics](http://i.stack.imgur.com/dHwsE.png) No amount of `TrackedSymbols :> {...}`, `ContinuousEvaluation -> False` or `SynchronousUpdating -> False` helped. **Is there any way to force $f_{end}$ in Dynamic[$x$, {$f$, $f_{end}$}] to be evaluated in a queued fashion, not preempting (its own) previous commands?** As a sidenote: It would be interesting to look into the implementation of `Button` as it definitely stands on something different than `EventHandler`. Does anyone has some insight on this matter?


Switch inside Manipulate controls statement

I am using this code inside of a Manipulate:               Switch[cases,           "custom", Control[{{names, True}, {True, False}}],          "a", Control[{{slide, 0}, 0, 1}],          "b", Control[{{setter, "das"}, {"das", "der", "die"}}]],         {{cases, "custom"}, {"custom", "a", "b"}}      The variable cases is supposed to control which other control type is visible. However i get the following error message: > Manipulate::vsform: Manipulate argument Switch[cases, > > [...] > > does not have the correct form for a variable specification. >> [...] is a placeholder which in mathematica displays the controls i specified above (Odd, right?). I cannot post screenshots yet unfortunately. Does anybody have an idea why this isn't working or how to better implement a manipulate control wich which i can dynamically alter the number and types of the other controls?


TableView displays negative numbers incorrectly

I'm trying to substitute TableForm with TableView because TableView is more handy with big data . But on my Mathematica 9.0.1 (ubuntu 14.04_64bit) there is a problem with negative numbers:               aa = {{5.10, 1.2}, {-5.10, -1.2}}          aa // TableForm       the last is fine but if I type               aa//TableView      the output of negative nuimbers is wrong (see attached immage) Negative numbers like -5.1 appears like -.51 !!!! ![enter image description here](http://i.stack.imgur.com/Nd0bk.png) ######## UPDATE 04.06.2014 @ 8.21 GMT If you work with strings like that:               aa1 = {{"5.1", "1.2"}, {"-5.1", "-1.2"}}      TableView has no problem, look the picture: ![enter image description here](http://i.stack.imgur.com/eTgzO.png)


Plot Wiener Process and its running maximum

I want to plot a Wiener process $B=(B_{t})_{t≥0}$ and its running maximum $S_{1}=\max_{0\leq t\leq1}B_{t}$ on Mathematica. Can anybody help? I only know how to generate a Wiener process using RandomFunction, but I have no idea how to plot its running maximum. thank you! any help is appreciated edit: Thank you for the answers! How do I plot the reflected process $S-B$ ? Is there a command that given the two graphs, outputs their difference?


Working with PhysicalConstants

I recently found the `PhysicalConstants`` package. First I thought this was nice, since I didn't have to look up some quantities all the time and copy them into the worksheet. But then I noticed the carried units. This is not automatically a bad thing, but it seems to me that they do not go together well, because Wolfram didn't just use base units. Consequently, if I use a quantity in `Newton` and divide it by a quantity in `Meter/Second^2`, the result will be `Newton*Second^2/Meter`, and not `Kilogram`. In my first try this made a huge mess in the result. Is there a way to work with these in a useful way?


DeleteMissing level spec confusion

Given:               titanic = ExampleData[{"Dataset", "Titanic"}]      Why does this correctly delete Missing[] elements:                titanic[GroupBy@Key@"class", DeleteMissing[#, 1] &, "age"] // Normal      but not the default level spec? Seems to violate key transparency in `Associations/Datasets`.                titanic[GroupBy@Key@"class", DeleteMissing, "age"] // Normal          (* <|"1st" -> {29, 1, 2, 30, 25, 48, 63, 39, 53, 71, 47, 18, 24, 26, 80,         Missing[], 24, 50, 32,... |>  *)      `DeleteMissing` also works on the bare list, as would any function applied at that Dataset slot. On the other hand:               <| "key" -> {29, 1, 2, 30, 25, 48, 63, 39, 53, 71, 47, 18, 24, 26, 80,         Missing[], 24, ... |> // DeleteMissing[#, 2] &      Level 2 is the minimum needed to delete missing element?


Problem constructing Association tables with some operators

First, set up the example `Dataset` from the documentation:               titanic = ExampleData[{"Dataset", "Titanic"}];      Why does this fail:               titanic[GroupBy[Key@"class"], <| "length" -> Length, "max" -> Max|>, "age"]          (* ... Part age is not applicable to {__Association}  ... *)      yet this re-expression of the query works:               titanic[GroupBy[Key@"class"], All, "age"][All, <| "length" -> Length,        "max" -> Max|>]      As do these modifications:               titanic[GroupBy[Key@"class"], <| "length" -> Length|>, "age"]      Strangely, Max doesn't work if substituted for Length above (bug?). Finally, this is not desirable but works without new key names:               titanic[GroupBy[Key@"class"], Query[{Length, Max}], "age"]


Help with coding triangular nodes/elements

![enter image description here](http://i.stack.imgur.com/Jhbqb.jpg) I'm trying to write a program where it will shoot out the triangle node numbers. For example, in the picture, if we choose to divide this triangle by 5 points, then the program will return out the following:               dat1 = {{0, 1, 6}, {1, 2, 7}, {2, 3, 8}, {3,4, 9}, {4, 5, 10}, {6, 7, 11}, {7, 8, 12}, {8, 9, 13}, {9, 10, 14}, {11, 12, 15}, {12, 13, 16}, {13, 14, 17}, {15, 16, 18}, {16, 17, 19}, {18, 19, 20}}          dat2 = {{1, 7, 6}, {2, 8, 7},{3, 9, 8}, {4, 10, 9}, {7, 12, 11}, {8, 13, 12}, {9, 14, 13}, {12, 16, 15}, {13, 17, 16}, {16, 19, 18}}      So dat1 is the list of the bottom triangles, while dat 2 is the list of the top triangles. So depending on how many points we divide the triangle by (in picture it is 5), then it will return out dat1 and dat2. Any suggestions or help on this?


Problems creating CDF via .NET DLL

I have read several posts at SE and googled a lot, but I still have difficulties to create a CDF via .NET. My first try was the Wolfram example `MathKernelApp.exe` under `FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "NETLink", "Examples", "Part2", "MathKernelApp", "bin", "Release"}]` I was able to create a CDF via input:   * `UsingFrontEnd@ExportString[Table[2^i,{i,16}],"CDF"]`   * `Export[FileNameJoin[{$TemporaryDirectory,"test.cdf"}],Table[2^i,{i, 16}]]` My second try was to reproduce it to compile a .NET DLL, which I can link to my SQL server. I have tested two different scripts, based on MathKernelApp and SimpleLink. The first one also captures Print and Message. First Script:               using System;     using System.Data;     using System.Drawing;     using System.Windows.Forms;     using System.Xml;     using Wolfram.NETLink;     using System.Collections;     using System.ComponentModel;     using System.Data.SqlClient;     using System.Data.SqlTypes;     using System.Text;     using Microsoft.SqlServer.Server;          public class MathLinkCLR     {         [SqlProcedure]         public static int Call(SqlString MLInput, out SqlString MLOutResult, out SqlString MLOutMessage, out SqlString MLOutPrint)         {             string strInput = (string)MLInput;             string strMLOutResult = null;             string strMLOutMessage = null;             string strMLOutPrint = null;             MLOutResult = null;             MLOutMessage = null;             MLOutPrint = null;             int iRV = -1;                  if (strInput != null) {                      /* Init MathLink */                 IKernelLink ml = MathLinkFactory.CreateKernelLink();                 MathKernel mathKernel;                 mathKernel = new MathKernel(ml);                 mathKernel.AutoCloseLink = true;                 mathKernel.CaptureMessages = true;                 mathKernel.CapturePrint = true;                 mathKernel.Input = null;                 mathKernel.LinkArguments = null;                 mathKernel.ResultFormat = MathKernel.ResultFormatType.InputForm;                 mathKernel.UseFrontEnd = true;                      /* Run */                 mathKernel.Compute(strInput);                      /* Results */                 strMLOutResult = (string) mathKernel.Result;                 foreach (string msg in mathKernel.Messages) strMLOutMessage += msg;                 foreach (string p in mathKernel.PrintOutput) strMLOutPrint += p;                 iRV = 0;                      /* Close MathLink */                 mathKernel.Dispose();             }             MLOutResult = strMLOutResult;             MLOutMessage = strMLOutMessage;             MLOutPrint = strMLOutPrint;             return iRV;         }     }      Second script:               using System;     using System.Data;     using System.Drawing;     using System.Windows.Forms;     using System.Xml;     using Wolfram.NETLink;     using System.Collections;     using System.ComponentModel;     using System.Data.SqlClient;     using System.Data.SqlTypes;     using System.Text;     using Microsoft.SqlServer.Server;          public class MathLinkCLR     {         [SqlProcedure]         public static int Call(SqlString MLInput, out SqlString MLOutResult)         {             string strInput = (string)MLInput;             string strMLOutResult = null;             MLOutResult = null;             int iRV = -1;                  if (strInput != null) {                      /* Init MathLink */                 IKernelLink ml = MathLinkFactory.CreateKernelLink();                 ml.WaitAndDiscardAnswer();                      /* Run */                 strMLOutResult = ml.EvaluateToInputForm(strInput, 0);                 iRV = 0;                      /* Close MathLink */                 ml.Close();             }             MLOutResult = strMLOutResult;             return iRV;         }     }      I can compile both scripts to a DLL, which I can link to SQL via `CREATE ASSEMBLY` (and other Windows system DLLs as ASSEMBLYs). I can also execute various Mathematica code, **BUT** I cannot create any CDF output (directly, or via `ExportString`). The SQL proc either hangs or returns `$Failed` as standard Mathematica return value, without any hint. I have tried .NET Framework v2.0.50727 and v4.0.30319. I **always** had to use `UsingFrontEnd` to prevent error message _FrontEndObject::notavail: A front end is not available; certain operations require a front end.Export::errelem: The Export element NotebookObject contains a malformed data structure and could not be exported to CDF format._ My questions are:   * I have used the console tool csc.exe to compile. Do I need to use the Visual Studio directly? Do I need to add other references and special compiling options?   * Do I need to load other Mathematica packages in my script, which are usually loaded by the front-end automatically?   * I have, more or less, used the MathKernelApp example. Why it is working and my dll is not? **Any help or hint is greatly appreciated!** * * * **UPDATE** I made some more tests and also traced the system with the Sysinternals ProcMon. The MathKernel.exe is executing a `CDF.exe` and a `CDF.jar` in one of Mathematica's system folders. Both traces look similar, but the call from within the SQL Management Studio is not working. **Maybe someone could help me with the ProcMon trace files?** I have also tried to execute the compiled program from within the SQL Management Studio, but it's not working, too. **Any ideas how to proceed?** ![cmd](http://i.stack.imgur.com/9ZBEP.jpg) ![sql](http://i.stack.imgur.com/3zlpM.jpg)


How can I set the ratio of the axis to 1:1 when plotrange->1 or how can I scale a rectangle according to the axis

I have a `ListPlot` function               lp2 :=       ListPlot[{#} & /@ #1,         PlotMarkers -> {Graphics@{Rectangle[]}, #2},         AspectRatio -> 1,         AxesOrigin -> {0, 0},         PlotRange -> All,         PlotStyle -> Hue /@ RandomReal[1, {Length@#1}],         Epilog -> {GrayLevel[.3], PointSize[.02], Point@#1, Thick, Line@#1},         Frame -> True,         FrameTicks -> All      ] &      which attempts to add a unit rectangle centered on each point however this relies on having constant axis to scale the unit rectangle to fit the axis. When `PlotRange->All` the axis ignores the aspect ratio and pretty much everything else. Is it possible to alter this behavior or scale the rectangle to the size of the axis chosen by Mathematica?


Breaking down a 3D model into patches

I have a 3D model, say the Stanford bunny, which is available in _Mathematica_ examples.                Import[ "http://exampledata.wolfram.com/bunny.noff.gz" ]      Also information such as the 3D coordinate of vertices and the normal at each vertex is available. Now I'd like to divide the whole thing into $n$, say 10, non overlapping patches. Something like the patches on a football. Patches must contain more or less same number of points, but this is a soft constraint. I see there is a function `FindShortestPath` in _Mathematica_. Maybe that function can help me? Since I am a new user I am not sure how I should approach the problem.


CompiledFunction::cfse: "Compiled expression X should be a machine-size integer

I am trying to use a compiled function in order to save time...               LegrendeTransform = Compile[{y},  MaxValue[Sin[x] - x *y  , x]]      Now I want to to evaluate and plot:               Plot[{LegrendeTransform[y]}, {y, 0, 1}]      But I get this error:               CompiledFunction::cfse: Compiled expression 0.9995462353179709` should be a machine-size integer. >>     CompiledFunction::cfex: Could not complete external evaluation at instruction 1; proceeding with uncompiled evaluation. >>      Could you explain the reason for this result? The number 0.9995462353179709 is so similar to 1 that I would have no problem if Mathematica decides to approximate it with an integer.... A.


Set maximum streamline length in VectorPlot for implicitly seeded streamlines

I have written a function that is meant to illustrate the solution of a DE:               ShowDESolution[f_, {xa_, xb_}, {ya_, yb_}] :=        Animate[VectorPlot[{1, f[x, y]}, {x, xa, xb}, {y, ya, yb},         VectorStyle -> Arrowheads[0],         VectorScale -> {Tiny, Automatic, None},         Axes -> True,         StreamPoints -> {1, Automatic, r},         StreamStyle -> {Directive[Red, Thick], "Line"},         ColorFunction -> "Rainbow", (* for LineIntegralConvolutionPlot *)         ImageSize -> 800], {r, 0, xb - xa}];     ShowDESolution[f_, {a_, b_}] := ShowDESolution[f, {a, b}, {-b, b}];     ShowDESolution[f_] := ShowDESolution[f, {-3, 3}];      This function, however, has the problem that the length of streamlines can only be set when the streamline seeds are explicitly given. (The max streamline length is the third term in `StreamPoints`, `r`.) If I replace the `1` in `StreamPoints` with `{{-xa, 0}}`, for example, the animation works just fine. But if I leave the `1` there, the streamline will be the same length regardless of `r`. Is there any way I could get the optimal streamline seed for that graph and put it in as an explicit seed? Or set the length of implicitly seeded streamlines?


Problems with NDSolve and stiffness

I am trying to solve an ODE in chemical kinetics: $$\begin{align*} \frac{\mathrm d[x]}{\mathrm dt} &= -k_1 [x][y]\\\ \frac{\mathrm d[y]}{\mathrm dt} &= k_1 [x][y] - k_3[y] \end{align*}$$ My solution seems to drop below zero for some reason. This cannot be the case since x, y are concentrations. Is this due to stiffness perhaps? Can I do better?               Needs["DifferentialEquations`NDSolveProblems`"];     Needs["DifferentialEquations`NDSolveUtilities`"];     k1 = 1*10^13;     k2 = 1*10^6;     k3 = 2000;     s = NDSolve[{x'[t] == -k1*x[t]*y[t], y'[t] == -k3*y[t] + k1*x[t]*y[t],      x[0] == 1*10^(-8), y[0] == 1*10^(-14)}, {x, y}, {t, 0, 0.001}];     Plot[Evaluate[{x[t], y[t]} /. s], {t, 0, 0.0003},      PlotStyle -> {{AbsoluteThickness[2],      RGBColor[0, 0, 0]}, {AbsoluteThickness[2],      RGBColor[.7, 0, 0]}, {AbsoluteThickness[2], RGBColor[0, .7, 0]}},      Axes -> False, Frame -> True,      PlotLabel ->      StyleForm[A StyleForm[" B*", FontColor -> RGBColor[.7, 0, 0]] ,      FontFamily -> "Helvetica", FontWeight -> "Bold"] ,      PlotRange -> {{0, 0.00030}, {1*10^-16, 1.5*10^-8}}]      ![ode](http://i.stack.imgur.com/VOmjL.jpg)


Repeating the contents of one cell in another, in "real time"

How could I create two Input cells, such that when the first is evaluated, the contents of the first are copied to the second? So for example, there would be two empty cells - let's call them A and B - and when the user enters `f[x_]:=x^2+4` in A, nothing happens. When that same user evaluates cell A, then the contents of cell B are updated to be `f[x_]:=x^2+4`. There is a similar question here, but I don't need to be that low-level about things, and I also don't want automatic refreshing; only when cell A has been evaluated.


How can I get LineLegend to pick up my plot's BaseStyle?

The new legends functionality in version 9 really simplifies creating legends, and it automatically picks up the styles of the lines.               Plot[{Sin[x], Cos[x]}, {x, 0, 5},       PlotStyle -> {Directive[AbsoluteThickness[3], Orange],         Directive[AbsoluteThickness[3], Brown]}, PlotLegends -> LineLegend["Expressions"]]      ![Nice fat lines](http://i.stack.imgur.com/2SqPR.png) But if there is a `BaseStyle` option to the plot affecting how the lines are plotted, the legend doesn't pick that up. See how the lines in the legend are now skinnier than in the plot.               Plot[{Sin[x], Cos[x]}, {x, 0, 5}, BaseStyle -> AbsoluteThickness[3],       PlotStyle -> {Orange, Brown},  PlotLegends -> LineLegend["Expressions"]]      ![Oh noes! The lines are skinny!](http://i.stack.imgur.com/6EYEX.png) How can I get `LineLegend` to see the `BaseStyle` of the plot while maintaining the automatic functionality of not having to explicitly specify the colors used in the plot?


Mathematica Implementations of the Random Forest algorithm

Is anyone aware of Mathematica use/implementation of Random Forest algorithm?


Real and imaginary parts of a complex number

I would like to find the real and imaginary parts of $x + y$ in terms of polar coordinates. Here is code:               ComplexExpand[Re[x + y], {x, y}, TargetFunctions -> {Abs, Arg}]      How can I add the assumption that $Abs[x]$ equals to $Abs[y]$? For example this code does not work:               ComplexExpand[Re[x + y], {x, y}, TargetFunctions -> {Abs, Arg},      Assumptions -> Abs[x] == Abs[y]]


How to find a path that traverses each edge of a graph exactly twice?

I have a question regarding a graph traversal problem. This is the graph I am working with:               Graph[{1 <-> 2, 1 <-> 3, 2 <-> 3, 2 <-> 4, 3 <-> 4}]      ![enter image description here](http://i.stack.imgur.com/czlOM.jpg) My Problem is following: I want to find a cycle on this graph such that after completion of the cycle I will have traversed each edge of the graph **exactly twice** and will have ended at my starting point. I saw that _Mathematica_ 9 has a built-in function: _FindEulerianCycle[g]_ which does just want I want except that each edge is traversed exactly once. So my idea was to "double" the edges i.e. add a new edge between 2 nodes:               Graph[{       1 <-> 2, 1 <-> 2, 1 <-> 3, 1 <-> 3, 2 <-> 3, 2 <-> 3, 2 <-> 4, 2 <-> 4, 3 <-> 4, 3 <-> 4       }]      But then I get the following error message: > Graph::supp: Mixed graphs and multigraphs are not supported. Apparently Multigraphs are still not supported in _Mathematica_ 8 & 9: Multigraphs in _Mathematica_ 8 Is there a way to implement a solution to the above mentioned problem in _Mathematica_? (I am using _Mathematica_ 9) **Note** : The graph shown above is just a simple example. I need to solve the above mentioned problem on a much bigger undirected graph which has vertices of odd degree.


Mathematica Functions from VBA

I'm trying to call _Mathematica_ functions from VBA (Excel) using .NETLink without success. (Yes, I know _Mathematica Link for Excel_ exists. And yes, I know the proper thing to do is buy it. However, it's not listed as compatible with v9, and on top of that, Episoft's website hasn't been updated since the end of 2011, so I'm not sure I want to rely on that for a long-term solution.) Reading the .NET/Link API documentation is akin to hieroglyphics, and the information out there on how to hook up the two is pretty sparse. I've narrowed it down to these items (after studying the SimpleLink example program included with _Mathematica_.   * Reference needed to NETLink .dll file (located under `FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "NETLink"}]`)   * Using `MathKernel.Compute()` and `MathKernel.Results()` as main functions to send data back and forth. When I set this up in VBA, I get the ever-present error "Can't find DLL entry point".               Public Declare Sub MMACompute Lib "C:\Program Files\Wolfram Research\Mathematica\9.0\SystemFiles\Links\NETLink\Wolfram.NETLink.dll" Alias "MathKernel.Compute" (expr As String)     Public Declare Function MMAResults Lib "C:\Program Files\Wolfram Research\Mathematica\9.0\SystemFiles\Links\NETLink\Wolfram.NETLink.dll" Alias "MathKernel.Result" ()               Sub test()            MMACompute ("2+2")       Debug.Print MMAResults()          End Sub      Any experience out there in getting this set up correctly? (Win7 x64, Office 2007 32-bit, MMA v9.01)


Summing tensors in mathematica

How do I perform the following summation in mathematica? \begin{equation} \Sigma_{m=1}^5 e_{ijklm}A^{mn} \end{equation} I have the $e_{ijklm}$ tensor of rank 5 in 5 dimension as a array and $A^{mn}$ as a 5x5 matrix.


ComplexExpand absolute squared

ComplexExpand[Abs[a + b I]]      Gives > $\sqrt{a^2 + b^2 }$               ComplexExpand[Abs[a + b I]^2]      On the other hand gives > Abs[a + I b]^2 How can I let it evaluate to $a^2 + b^2$ instead?


Rearranging a List

I am trying to rearrange/sort a list i.e.                {{1,2},{10,140},{43,10},{1,140},{43,2}}      into                {{1,2},{2,43},{43,10},{10,140},{140,1}}       or any cyclic permutation of it. The numbers don't repeat more than twice. It needs to be rather efficient since I am applying to large lists, in a large sets of lists. I have a quick code that seems to do the job, but I don't like all those appends.               Myarrangemnt[list_] :=       Module[{x = list, len = Length[list], finalarragment = {First@list},tt},      x = Drop[x, {1}];      While[Length[finalarragment] < len,      tt = First@       Cases[x,         y_ /; Equal[Last@Last@finalarragment, y[[1]]] ||        Equal[Last@Last@finalarragment, y[[2]]]];      If[First[tt] == Last@Last@finalarragment,         finalarragment = Append[finalarragment, tt],         finalarragment = Append[finalarragment, Reverse@tt]        ];      x = Drop[x, First@Position[x, tt]];      ];      Return[finalarragment];      ];      Here is a random test list               test = RandomSample /@ (RandomSample@     Partition[RandomInteger[{1, 1000}, 100], 2, 1, -1])      Is there a more efficient way to achieve this ? Maybe with Reap and Sow and/or SortyBy ?


Converting expressions to "edges" for use in TreePlot, Graph

This question is similar to this: Nested list to graph. How to "flatten" an arbitrary expression, eg               expr = a[b[c, d[e][f], g], h]      to a list of key-value pairs representing Graph edges of the expression tree: ![enter image description here](http://i.stack.imgur.com/MOud6.png) These can be extracted by applying WReach's exception-based method --> Can TreeForm be displayed “sideways”?:               Block[{TreePlot},       t_TreePlot := Throw@Hold@t;       Catch@MakeBoxes@TreeForm[expr]       ][[1, 1]]      Giving:               {{"a", "0", "a[b[c, d[e][f], g], h]"} -> {"b", "1",         "b[c, d[e][f], g]"}, {"b", "1", "b[c, d[e][f], g]"} -> {"c", "2",         "c"}, {"b", "1", "b[c, d[e][f], g]"} -> {"d[e]", "3",         "d[e][f]"}, {"d[e]", "3", "d[e][f]"} -> {"f", "4", "f"}, {"b", "1",         "b[c, d[e][f], g]"} -> {"g", "5", "g"}, {"a", "0",         "a[b[c, d[e][f], g], h]"} -> {"h", "6", "h"}}      (Why are they cast to String?) Note non-atomic sub-expressions replaced with their Head. Based on the above, and the rule: `({h_, _, _} -> {a_, _, _}) :> ToExpression@h -> ToExpression@ a` gives:               {a -> b, b -> c, b -> d[e], d[e] -> f, b -> g, a -> h}      TreeForm is a wrapper around `TreePlot`. `TreePlot[%, VertexLabeling -> True]` gives: ![enter image description here](http://i.stack.imgur.com/NJmgi.png) Since the layout is different, `TreePlot` must be making use of the other components of the output of the Block above. **EDIT:** How do TreeForm and SparseAray`ExpressionToTree (see below) extract these pairs of vertices? "Proof of work" is to extract the position (in the expression) of each vertex along with the edges. Previously, I asked how to extract these "edges" based on a more restricted example Alternatives ordering affects pattern matching in Cases?. Also tried `ReplaceList` but don't know how to map it consistently across all levels.


Additional label on axis - 2D plot

I am finding a local maximum of a curve and I want to make the plot easier to read. I added a point to where the maximum is but I would also like to: 1) add a tick with text below it where the x value of the maximum is (saying "Xmax" or " X* ") 2) a dotted line from the point down to the x-axis. Here is a simpler version of the plot I'm making:               maxi = FindMaximum[Cos[x], {x, 4, 8}];     coordin = {x /. maxi[[2]], First[maxi]};     Plot[Cos[x], {x, 0, 4 \[Pi]}, Epilog -> {PointSize[Large], Point[coordin]}]      I have pictures to better explain this but I'm not allowed to post images.


Integration of a rational function

I am trying to solve the following rational integral (I got assistance here): $$\int_{-\infty}^{\infty}{\frac{a+x}{b^2 + (a+x)^2}\frac{1}{1+c(a-x)^2}}dx$$ where $\\{a, b, c\\}\in \mathbb{R}$. I would like also to find an analytical solution using Mathematica. I have tried `Integrate`,               Integrate[(a + x)/(b^2 + (a + x)^2)*1/(       1 + c*(a - x)^2), {x, -Infinity, Infinity}]      but this gives me an imaginary result based on $a$, $b$ and $c$. I believe the result should be 100% real. Am I using `Integrate` the correct way?


Plotting solutions to Solve results

I am trying to plot a solution to a Solve result, ie I have a function f(x,y) and I want to plot y=y(x) for when f(x,y) = 0.06366. Here is what I am trying to do               f[x_, y_] := 0.5*Erf[(y - 0.04*x^2)/(0.1*Sqrt[x])] + 0.5;     Plot[Evaluate@Table[Solve[f[x, y] == 0.06366, {x, y}, {y, Range[0, 1, 0.2]}],     {x, 0, 7}], PlotRange -> Full]


City/Country Names by GeoLocation

How do I get the city and country names from the output of `FindGeoLocation[]` {lat, long} ?


InputField AutoSize Speed Issue

How do I have an `InputField` adjust to fill the remaining size of the window automatically? For example: ![enter image description here](http://i.stack.imgur.com/wZaPK.png) Using the `ImageSize` option often either freezes or takes 5 seconds or longer to run in Mathematica 8.0 in Windows 7. **No longer an issue.**


How can I prove an equation has a certain number of real roots?

I have this code               NSolve[1-(b/r)^2-g^-2*(2/15 * Σ^9 (1/(r-1)^9-1/(r+1)^9-9/(8r) (1/(r-1)^8-1              /(r+1)^8)) - Σ^3 (1/(r-1)^3-1/(r+1)^3-3/(2r) (1/(r-1)^2-1              /(r+1)^2))) == 0, r, Reals]      I want to prove that for any values of g, b, Σ, I will find, for r, only 4 real roots. The others will be complex. Any ideas?


Mathematica isn't sure whether a sum of two positives is positive or not

Mathematica is not able to tell whether a summation of two positive expressions is positive or not. Which is very strange. My three symbolic arguments, $x$, $y$, and $z$, are all real numbers bounded by zero and one. Hence the following expression should definitely be positive as well. $x + (1 - x) (1 + y)^z$ My code is:               $Assumptions = {(x | y | z) \[Element] Reals} && 0 < x < 1 && 0 < y < 1 && 0 < z < 1          Refine[x + (1 - x) (1 + y)^z > 0]      The expected result is `True`. But what I get is just a repetition of the inequality within `Refine`. To test, I tried the two terms on LHS separately as:               Refine[x > 0]          Refine[(1 - x) (1 + y)^z > 0]      And both give me `True`. But once I combine them it doesn't work. This is very very strange. Can anyone help me out? Thank you so much!


Retain required terms in asymptotic expansions

I am using Mathematica 8 to do lengthy asymptotic expansions for use in statistics. In particular I have $\lambda=\beta+\epsilon+\delta+\gamma+O(n^{-5/2})$ where the first term is of order $O(n^{-1/2})$, the second one is $O(n^{-1})$, the third is $O(n^{-3/2})$ an the last one is $O(n^{-2})$ (where n is some asymptotic index). What I want to do is to expand               Series[Log[1 + A*x], {x, 0, 4}]      where $x=\lambda$ and A is of order $O(n^{-1/2})$, and I want Mathematica to be able to automatically retain all the terms up to $O(n^{-2})$. I have tried to expand and to use Simplify by telling the orders of the components in $\lambda$ through Assumptions, but I am not still able to get anywhere. Does anybody knows a way to do this or a good tutorial to learn from? Thank you in advance, Bstr


How to visualize/edit a big matrix as a table?

Is it possible to visualize/edit a big matrix as a table ? I often end up exporting/copying big tables to Excel for seeing them, but I would prefer to stay in Mathematica and have a similar view as in Excel. Note that I'm looking for a non commercial solution. Thanks


How to solve a signaling game in Mathematica (game theory)

A signaling game is within the field of game theory, and more information can be found here. I would like to know, how one can solve such a game, by finding the Baysian Nash equilibrium in Mathematica. I have been searching for such a solution including in the wolfram library, but without any luck.


Finding areas of beings in microscopic image

I've got lots of images of diatoms. I need to get a list of their equivalent radii. ![some diatoms](http://i.stack.imgur.com/XQJlW.jpg) ![more diatoms](http://i.stack.imgur.com/gGTro.jpg) It's not crucial to get them all, as long as those missed don't mess with the radius distribution (as would happen if it always missed the biggest ones or the smallest ones). I am having trouble mainly because sometimes two little beings end up overlapping, in which case I would need to either separate them or at least discard them. Also, even though some may look like hollow, or even split in two, they are actually one. So               images = Import /@ {"http://i.stack.imgur.com/y7vag.jpg",          "http://i.stack.imgur.com/XQJlW.jpg",          "http://i.stack.imgur.com/gGTro.jpg"};          preproc[im_] :=       ColorConvert[im, "GrayScale"] // Binarize // ColorNegate //          FillingTransform // MorphologicalComponents // Colorize          FlipView[{#, preproc @ #}] & /@ images // TabView      ![diatoms after image processing](http://i.stack.imgur.com/SGgMB.png) An example of an image with the beings approximately rounded manually can be seen here: ![measuring the diatoms](http://i.stack.imgur.com/MYTqZ.jpg) I would appreciate any ideas. Thanks! Note: a semi-automatic solution can still save a lot of time


Finding Roots of Non-linear Systems: Rescaling polynomials

I'm trying to get all isolated finite equilibria of a moderate multi- dimensional non-linear system of equations. Particularly I have 9 independent variables and third order at most. It turns out that, as this system models chemical kinetics, all coefficients have disparate magnitudes. When I throw my system into NSolve it just keeps running. Forever. It does not throw empty brackets or errors or anything of that sort. Furthermore, I know that it has at least one equilibrium point because I used it in a transient problem, i.e. one isolated solution is a steady state (I need all equilibria though). This is first time I try solving such systems in Mathematica but I don't think it is too large for the software to handle it. Is it common for NSolve to take such a long time solving these multidimensional non-linear systems of equations? Would I have to rescale my polynomials before throwing it into NSolve so that I get a better performance? Thanks!


Define the square of a function

Is there any good way to define the square of a function in M9? Usually one can write e.g. `f[z_] = 3*Sin[z]` etc etc. But is it possible to define `g^2[z_] = 2*Cos[z]` for example?


The default bandwidth of the SmoothKernelDistribution function

I am researching the Silverman rule of thumb for bandwidth selection. Below is a sample of my code, from which it seems that BW=63 is close to the default parameter given by _Mathematica_ (2 images are quite similar).               data4 = RandomReal[1024, {3600, 2}];     \[ScriptCapitalD]1 = SmoothKernelDistribution[data4];     \[ScriptCapitalD]2 = SmoothKernelDistribution[data4, 63];     {ContourPlot[PDF[\[ScriptCapitalD]1, {x, y}], {x, 0, 1024}, {y, 0, 1024}],       ContourPlot[PDF[\[ScriptCapitalD]2, {x, y}], {x, 0, 1024}, {y, 0, 1024}]}      ![2 images are similar](http://i.stack.imgur.com/xXVF4.jpg) Yet, according to articles the definition for Silverman R.O.T. should be:               H1 = (4/(dim + 2))^(1/(dim + 4))*n^(-1/(dim + 4)) StandardDeviation[data4[[All, 1]]]     (* -> 74.7864 *)      When I did this analysis for the 1D case, the _Mathematica_ results fit well to expectations. My question is: How does _Mathematica_ calculate BW by default? How can I see the BW results (other than trial and error until images are alike)?


Indexing of Large Autonomous System of Equations for Use in NDSolve

I currently have a list of ~150 autonomous DAE's (differential-algebraic equations) that I need to be able to work with using `NDSolve`. Fortunately I already have them formatted in plaintext, which leaves how to best manipulate them within Mathematica as the remaining task. Each equations is of the form `a'(t) = f(t)` , `b'(t,a) = f(t,a)`, `c'(t,a,b) = f(t,a,b)`, or **_(Edit: for example)_** `c'_6 = kf*(c_1 + mu*c_5) - 2*c_6 + mu*kd^2*c_7 - kd^2*c_6` with `c'_7 = kf*(c_1 + mu*c_6) - 2*c_7 + kd^2*c_8 + kd^2*c_7` and `c'_8 = kf*(z_1 + (mu*c_7 - 2*c_8) + kd^2*c_9 + kd^2*c_8`, etc. where the z'_n (or prime) denotes derivative with respect to time of that equation (labelled z) up until c_150. Each subsequent equation involves the previous functions whose derivatives are given. My best idea as to how to organize this would be to make a VERY long `z = {eqn1RHS,eqn2RHS,...,eqniRHS}` and either list the entirety of each equation within this list, then indexing it by `Part` or `c[[77]]` if, say, equation 77 is needed. My question is simple. Within the context of NDSolve and numerical integration, does this seem to the learned of you to be the best way to efficiently import large systems of equations for future manipulation, accessible individually if the need be? Thank you. (L/RHS = Left/Right Hand Side) **_Edit:_** See the comments. As suggested, this method is appropriate if (as suggested in the answer) the appropriate syntax is given for which parameters are implicit functions of time.


How to select elements from a 4D Array?

I am very new to _Mathematica_ (first time!) and I'm already having troubles with arrays. I basically have a 4D tensor, that is a matrix (call it `M`) which has for each entry another matrix. I want to select the elements of the nested matrices that are bigger than zero, but `Select[M, # > 0 &]` doesn't work. I suspect it is because I do not respect the dimensions. I am kind of lost. Thanks in advance


Range of stability for iterative map

Using linear stability analysis, I would like to compute the range of stability of the fixed points and the 2-cycles of the following iterative map: $x_n = x_{n-1}^{2} - 3\mu$. Setting $x = x^{2} - 3\mu$, using hands and Mathematica I calculated the fixed points: $x_1 = \frac{\sqrt{1+12\mu}}{2}$ and $x_2 = \frac{\sqrt{1-12\mu}}{2}$.   And the two cycles are the fixed points and two other additional points: $x_3 = \frac{-1-\sqrt{3(-1+4\mu)}}{2}$ and $x_4 = \frac{-1+\sqrt{3(-1+4\mu)}}{2}$. Now I am struggling to find the range of stability of the fixed points and 2-cycles using hands and Mathematica.   What I know is we need to compute the slope of the map at the points. So if we differentiate $x^{2} - 3\mu$ and calculate the derivative at the fixed point $x_1 = \frac{\sqrt{1+12\mu}}{2}$, we get $2(x_1) = 1+\sqrt{1+12\mu}$. And similarly for $x_2$, $2(x_2) = 1-\sqrt{1+12\mu}$. Then we set the absolute values < 1\. So we get $|1+\sqrt{1+12\mu}| < 1$ and $|1-\sqrt{1+12\mu}| < 1$. Now here is the problem, I can only find the range of stability for $x_2$ but not for $x_1$. Here is my (hands) work:   $$|1-\sqrt{1+12\mu}| < 1$$ $$-1<1-\sqrt{1+12\mu} < 1$$ $$-2<-\sqrt{1+12\mu} < 0$$ $$-\frac{1}{3} < \mu < \frac{3}{13}$$ But now I try to find the range of stability of $x_1$:   $$|1+\sqrt{1+12\mu}| < 1$$ $$-1<1+\sqrt{1+12\mu} < 1$$ $$-2<\sqrt{1+12\mu} < 0$$ and there is no solution for this inequality. So what can we conclude for the range of stability? And how can I solve this problem using Mathematica? One way of doing it using Mathematica that I can think of is by drawing the cobweb diagram and checking for some values of $\mu$, but this method is exhaustive and time consuming. Is there any more efficient method? Any helps on methods and code are greatly appreciated. Many thanks in advance.


List version of SphericalPlot3D

could you give me some input on how to create a list version of               SphericalPlot3D[r[theta,phi],{theta,min,max},{phi,min,max}]      When r[] is an explicit analytical function it's not an issue, but what if one numerically generates a list {{r1,theta1,phi1},...,{rn,thetan,phin}} and wants to visualize it in a similar manner? Any ideas?


Bare symbol invocation fails but not if used with an argument

How to achieve the following behavior on a symbol f? Background: The main goal is to use the symbol to tag an abstract data structure where downvalues are used to store information. Only defined downvalues are to be used. The bare invocation of a symbol in an expression should result in an error message. Note: I am not asking how to design the abstract data structure. What I am asking is the following: The context in which this symbol is to be used is something like this (a snapshot of a stack):               f := Fail;     f[_] := Fail;     f[1] = value1;     f[2] = value2;      so that only invocation on existing downvalues or when a new downvalue is defined it works, but both invocation on a non-existing downvalue fails, and the bare invocation fails. For example, assume that the stack looks like this before we start using the symbol               f := Fail     f[_] := Fail      and then we start using the f symbol like this               f = 3 (* fails due to f := $Fail *);         f[1] = value1 (* works, an assignment *);         f[2] = value2 (* ibid *);         x = f + 1 (* fails due to f := $Fail *);     x = f[3] + 1 (* fails due to f[_] := $Fail *);     x = f[1] + 1 (* works: x = value1 + 1 *);     x = f[2] + 1 (* works: x = value2 + 1 *);     f[3] = value3 (* works: an assignemnt *);      x = f[3] + 1 (* should now work since f[3] has been assigned *);      Here is an example when one actually tries to implement this               ClearAll[f];     f := fail1;     f[___] := fail2      This results in               Information[f]     Global`f     f:=fail1      which is good. We want it to fail if invoked directly without argument. However, the default invocation on non-existing downvalues is already problematic:               Information[fail1]     Global`fail1     fail1[___]:=fail2      thus something that is not wanted. (I understand why this happens: The `SetDelayed` command evaluates its LHS). Everything goes down the drain right at the beginning, since one would not be able to define the `SetDelayed` part. Background[EDIT]: A mathematica code is being passed to a function which changes it slighlty. the code on input looks like, e.g.,               this@f1 = value1     this@f2 = this@f1 + 1      and the processed code should read               o@f1 = value1     o@f2 = o@f1 + 1      if the user specifies               f1 = value1     this@f2 = this@f1 + 1      the system should complain. I know how to do this on the phraser level, no problem. I wonder, is it possible to arrange for the suitable definitions for f1 and f2 so that the behavior I desired occurs, i.e. later on when f1 = value1 is evaluated that an exception occurs? Also the following is defined silently at the same time               o[id_]@f_ := f[id]      In this way one can define a super simple data strcuture that can be instantiated like a class and operated upon. it should be very natural to write method definitions for such a class.


What are the use cases for different scoping constructs?

Mathematica includes three functions that I know of which can be used to effectively (if not actually) define a variable and give it a value within a local scope: `Module`, `Block`, and `With`. What are the differences between these functions (and any other scoping constructs that may exist which I don't know about), and how do I decide which one is appropriate to use in any given instance? The documentation does describe what the different constructs do to some extent, but I feel like it's insufficiently clear on how exactly they differ from each other. Having some short examples that demonstrate the differences would be great.


Block, With, Module, can anyone help me understand the distinction?

I've been working heavily with Block[] for months in my research so I've read the documentation for the seemingly similar commands With[], Block[], and Module[]. Personally, I've had by far the greatest success with Block, despite With having the connotation of what I think I am trying to accomplish. Sometimes With will solve a problem where Block works as well, but often not. I haven't tried Module as much, but the documentation seems so similar. I am sure there are very critical subtleties which make these three commands have their respective places in the world and I fear choosing the wrong one may cause problems. My incentive for using these types of commands typically is, I work with expressions of several variables (large matrices with 7 variable dependencies), and often I wish to (temporarily) examine a lower-dimensional subspace of my expression; i.e. I may wish to "substitute" numerical values for 5 or 6 of the variables to produce a simpler expression which depends only on 2 or 1 variables. Of course, it is important for me to retain the true expression (with 7 variables) so I don't simply want to set values for the variables (I could do this and then use Clear, but this gets messy very quickly). Also, I have found that using rule substitutions like               (expr)/.x->1.45         often cause mathematica to treat x as 1.45 elsewhere. I need local variable assignments, so it seems Block, With, or Module is the way to go. But how should I chose?               (* ==========================  EDIT  ========================== *)        When Module, for example, is wrapped inside another module, the text becomes red. Does this indicate a problem or is it normal/functioning properly?               Module[{x = 4}, (x^2 + y^2) Module[{x = 1}, (x + y)]]       Block[{x = 4}, (x^2 + y^2) Block[{x = 1}, (x + y)]]     With[{x = 4}, (x^2 + y^2) With[{x = 1}, (x + y)]]        all of the above seem to return the desired output of               (y+1)(y^2+16)        but mathematica gives slightly different variable colorings. Maybe the red isn't bad?


RandomReal behavior in Block environment

I ran into an unexpected behavior of RandomReal function inside the Block environment. If I simplify my problem: I wanted to use two random local variables, such that the second one would be less that the first one. I initialized both of them inside the brackets like this:               ClearAll[x, y]     Block[      {x = RandomReal[10], y = RandomReal[x], z = RandomReal[y]},      Print[x]; Print[y]; Print[z]; Print[x]; Print[y]; Print[z]      ]      I got the following result:               4.84284     0.0453673     1.63126     4.84284     2.68987     1.1345      and a warning:               RandomReal::unifr: The endpoints specified by x for the endpoints of the uniform distribution range are not real valued. >>     RandomReal::unifr: The endpoints specified by y for the endpoints of the uniform distribution range are not real valued. >>      Value of x seems to be the same all the time, but the values of y and z change. Note that the value of y changes even if the variable is not called explicitly (value of z in the third line is greater than the value of y in the second line), but the value of x never changes - I don't want to generalize too soon, but I executed upper code several times and the values of y and z were never greater than the value of x. Since I wanted the values of x,y and z to be fixed, I canged the code into:               ClearAll[x, y]     Block[      {x, y, z},      x = RandomReal[10]; y = RandomReal[x]; z = RandomReal[y];      Print[x]; Print[y]; Print[z]; Print[x]; Print[y]; Print[z]      ]      and got wanted output:               8.72751     2.74445     0.630739     8.72751     2.74445     0.630739      Can someone please explain how Block works? I can't explain the behavior of this construct in the first case I described. I read the documentation but didn't find the answer there - probably missed something? Thanks, Špela


Returning a function from a Module

I'm having problems working with the output from `DSolve` whilst in a module. To handle the result outside a module typically I would do something like                f[t] = y[t] /. solution      But inside a module my `t` is now `t$` followed by some numbers. How can I create and return a function from the output of `DSolve` inside a module? * * * Here is my code:               Module[{equations,solution,h,t},       m=1;       g=9.8;       equations = {y''[t]== -m g,y'[0]==100,y[0]==0};       solution = Flatten@ DSolve[equations,y,t];       h[t] = y[t] /. solution;       h[1]]      I get `h = 100. t$16608-4.9 t$16608^2`, but `h[1] = h$16909[1)`.


What is the difference between Block and Module?

> **Possible Duplicate:**   >  What are the use cases for different scoping constructs? I don't understand the difference between the Matheamtica functions `Block` and `Module`. They seem to do the same thing: they both allow the definition of local variables.


Using With in combination with Graphics

Assume that we are given a symbol `p={x,y}` which should represent a 2D point. If `x` and `y` have numerical values then we can plot the point uisng               Graphics[Point[p]]      Next, I wanted to plot some setting for various `x` and `y`, so I thought I could use the `With` command and have something like:               With[{x = 1, y = 1},      Graphics[Point[p]]      ]      This doesn't work. I guess it has something to do with the order of evaluations, holding stuff etc. but I cannot figure out how to solve this. So the question is how to use `With` together with `Graphics`?


Plot Notes present in sound sample

I would like to visualize a sampled sound, and place the sounds as notes starting from `C0` to `A8` or such. I have a table of frequencies (in $[Hz]$) of these notes, and I have a sample sound. My goal is to have along the $y$ axis the possible notes, and along the $x$ axis the time. My main question is, what are the values of the `SampleSoundList`, and can they easily be related to the frequencies from my table? The table is in _Excel_ , but I could write it out as a list of `{ { C0, 16.35}, .. }`. Any help or pointers in the right direction would be much appreciated. Additional Information: What are values?               toSpectrogram[x_] := Print[Spectrogram[x]] &&  Print[ x ]     Button["Sing", snd = SystemDialogInput["RecordSound"];       toSpectrogram[snd[[1]]], Appearance -> "DialogBox",       Method -> "Queued"]      What I mean by what are the values of a SampledSoundList in this sense:               SampledSoundList[{{0.,0.,-0.0078125,0.,0.,0.,0.,-0.0078125,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.0078125,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.0078125,0., ........ 0.,0.,0.0078125}},11025]      The final value ,11025] is the sample rate. But what are all of the other Reals? How could/would they relate to finding a pitch, or frame to look at to figure out if the sound is a note or what note they are? Can I iterate over this list of "values" and get an idea of the Musical Note at any point, or series of points? I imagine that the sound is sampled at a certain rate, i.e. the 11025 and so this means that a certain block of numbers in the list represent a point in time, but I don't know what the actual numbers mean? Are they some kind of representation of pitches? The numbers are from -1 to 1, so they represent some kind of whole but what that whole is is unknown to me. I am sorry if I am being dense. This is just an area of curiosity for me. Thanks **EDIT** From all the input and more doc reading, I have come up with this:               toSpectrogram[x_] := (Print[Spectrogram[x]]; plotSampledSoundList[x])     plotSampledSoundList[       x_] := (sa = Abs[SpectrogramArray[x[[1]][[1]], 16, 10]];        Print[ListLinePlot[sa[[{10, 35}]], DataRange -> {0, 8000},          PlotRange -> {{500, 5000}}, Ticks -> {Automatic, None}]])     Button["Sing", snd = SystemDialogInput["RecordSound"];       toSpectrogram[snd[[1]]], Appearance -> "DialogBox",       Method -> "Queued"]      This is getting very close to what I want, though I am still unclear on some of the arguments. In the case of SpectrogramArray, the 16 is supposed to be the bit depth of the sample? So if I record at 11khrtz 16bit then this should be good? The plot that comes out is what I was hoping for, but I could be wrong. The final part of my question is: How do I place the Note values up the y axis starting with C0-A8 or what not ( can be smaller range, or even better if it fits the sound to the range).


Behaviour of OutputResponse in ListLinePlot

Ok, I think this is not the best way to do this, so I'm open minded for every suggestion doing it in a better way. The Question is why does `ListLinePlot` not plot all the data when it's inside `Manipulate`? I created a dataset w/ and wo/ noise:               dataFunc[x_] := .5 Sin[x^2 + x]          dataRaw = Table[dataFunc[x], {x, 0, 2 π, .001}];     dataNoise =        Table[dataFunc[x] + RandomReal[{-1, 1}], {x, 0, 2 π, .001}];          Grid[{ListLinePlot /@ {dataRaw, dataNoise}}]     ListLinePlot[{dataNoise, dataRaw}]      ![dataset wo/ and w/ noise](http://i.stack.imgur.com/Cd3Ik.png) I'm doing the built in low-pass filter with `Manipulate`               Manipulate[       ListLinePlot[{LowpassFilter[dataNoise, ω, n], dataRaw}],       {{ ω, .3}, .001, Pi, .001}, {{n, 100}, 1, 500, 1}]      ![enter image description here](http://i.stack.imgur.com/NZQ3c.gif) Now I added my own low-pass filter:               discLowPass[T_, τ_] :=        ToDiscreteTimeModel[ TransferFunctionModel[ 1/(1 + T s), s], τ]      And here it is: Without the dataRaw it works               Manipulate[       ListLinePlot[OutputResponse[discLowPass[T, τ], dataNoise]],       {{T, .1}, .005, 25}, {{ τ, .005}, .001, .025}]      ![enter image description here](http://i.stack.imgur.com/tBp1h.gif) ... but adding the signal without noise to the `ListLinePlot` it doesn't work anymore.   Why?               Manipulate[       ListLinePlot[{ OutputResponse[discLowPass[T, τ], dataNoise],          dataRaw}],       {{T, .1}, .005, 25}, {{ τ, .005}, .001, .025}]      ![enter image description here](http://i.stack.imgur.com/lmRFy.gif) It's just plotting the raw signal without the noise. **EDIT** : Using `Show` it works for the `OutputResponse`, too.               Manipulate[       Show[{         ListLinePlot[OutputResponse[discLowPass[T, τ], dataNoise]],         ListLinePlot[dataRaw, PlotStyle -> Red]}],       {{T, .25}, .005, 5, .005}, {{ τ, .01}, .001, .025}]      ![enter image description here](http://i.stack.imgur.com/8bdwW.png)


Orthogonalizing polynomials with inner product depending on parameters

I need to orthogonalize the polynomials $h_n(x)=x^{2n}(1+x^2)^{-4S}$ with $x\in\textbf{R}$, $2S\in\textbf{N}$ and $n\in\\{1,3,5,\ldots, 4S-1\\}$ over the inner product $\langle h_n,h_m\rangle=32\pi S\displaystyle\int_0^1h_n(x)h_m(x)\frac{x(1-x^2)dx}{(1+x^2)^3}$ $=16\pi S\frac{\displaystyle\sum_{k=0}^{8S-n-m}{8S+2 \choose k}(8S+1-n-m-k)}{\displaystyle2^{8S+1}(n+m+2)(n+m+1){8S+2 \choose 8S-n-m}}$ . Using the integral itself with `Orthogonalize` takes forever and the result is not informative. So I'd like to use the formula above in terms of the parameters $n$ and $m$ instead. Is there a way to do this with Mathematica, i.e. use `Orthogonalize` with an inner product that depends on parameters rather than the functions and their variables?


Using NonlinearModelFit to fit data with errors

Assume we have some data of measurements               SeedRandom[9];     data = Table[{i,2*(1 + 5*RandomReal[])*Exp[-0.01*(1 + RandomReal[])*i]}, {i, {0, 100, 200, 400, 700}}];      and measurement errors associated to it               errors = 10^# & /@ Range[0, -4, -1];      Ignoring the weights in a first step, the fitting works very well:               nlm = NonlinearModelFit[data, a*Exp[-b*x], {a, b}, x, Method -> "NMinimize"];     Show[ListPlot[data, PlotStyle -> PointSize -> Medium],      Plot[nlm[x], {x, 0, 700}, PlotRange -> Full], PlotRange -> All]      ![Fit without measurement errors](http://i.stack.imgur.com/dAwf3.png) Now, according to this how-to, we can include the measurement errors to the fitting procedure:               nlm = NonlinearModelFit[data, a*Exp[-b*x], {a, b}, x, Weights -> 1/errors^2, VarianceEstimatorFunction -> (1 &), Method -> "NMinimize"];     Show[ListPlot[data, PlotStyle -> PointSize -> Medium],      Plot[nlm[x], {x, 0, 700}, PlotRange -> Full], PlotRange -> All]      Clearly, the obtained fit is much worse. ![Fit with measurement errors](http://i.stack.imgur.com/vMLSz.png) **My questions are** :   1. What is the objective function in `NonlinearModelFit` when introducing weights? The how-to says: "It is important to note that weights do not change the fitting or error estimates", but obviously the fit is changed. Thus, the weights have to be a part of the objective functions, which is minimized.   2. How can I obtain a better fit with introduced weights? I was playing around with the `NMinimize` options `"NelderMead"`, `"RandomSearch"`, `"SimulatedAnnealing"` and `"DifferentialEvolution"`, but up to this point none of them was able to reproduce the fit obtained by ignoring the measurement errors.


Numerical solution of the hyperbolic equation

I am trying to solve the following hyperbolic equation with given boundary conditions: ![two muppets](http://rogercortesi.com/eqn/tempimagedir/eqn4118.png) I choose as initial condition $u=1$, and evolve the above hyperbolic equation until reaching a stationary state with some predetermined tolerance. Spatial derivatives are approximated by taking standard centered differences everywhere. The _Mathematica_ input is:               φ[z] = q*(1/z + (-1*q)/(-1*z));     η[z] := k* (1/z + (-1*q)/(-1*z));      r[ρ, z] := sqrt[ρ^2 + z^2];          NDSolve[ {Derivative[u[t, ρ, z], {t, 2}] ==         Derivative[u[t, ρ, z], {ρ, 2}] + (1/ρ)*          Derivative[u[t, ρ, z], {ρ, 1}] +           Derivative[          u[t, ρ, z], {z, 2}] - ((φ[z]^4)/4)* (            Derivative[(η[z] + u[t, ρ, z]  - 1)/φ[                z], {ρ,                1}] Derivative[(η[z] + u[t, ρ, z]  +                  1)/φ[z], {ρ, 1}] +             Derivative[(η[z] + u[t, ρ, z]  - 1)/φ[                z], {z,                1}] Derivative[(η[z] + u[t, ρ, z]  +                  1)/φ[z], {z, 1}]) *((η[z] +                u[t, ρ,                 z])*((η[z] + u[t, ρ, z])^2 - (φ[z]^2)/                2) )^(-1), u[0, ρ, z] = 0, u[t, 6, z] = 1,        u[t, ρ, -6] = u[t, ρ, 6]},       u[t, ρ, z], {t, 0, 10}, {ρ, 0, 6}, {z, -6, 6},       Method -> {"MethodOfLines",         "SpatialDiscretization" -> {"TensorProductGrid",           "DifferenceOrder" -> "Pseudospectral"}}]      which gives errors. I would like to ask if you could help me to solve this problem.


Making sense of output of Assuming/Refine

I have a conditional statement as output:               \[Piecewise]          (-b+a b-2 x+2 y)/(2 (-1+a)^2 a (-1+b) b)          (-b+a b-x+y==0&&-b+ab-x>-1&&                                                         -b+ab+x<=0)||(-b+a b-x+y==0&&                                                       -b+a b-x>-1)     (-b^2+2 a b^2-a^2 b^2-2 b x+2 a b x-2 x^2+     2b y-2 a b y+4 x y-2 y^2)/(2 (-1+a)^3 a      (-1+b) b^2)                                      (-b+a b-x>-1&&-b+a b+x<=0&&                                                      -b+ab-x+y>0)||                                                      (-b+a b-x>-1&&-b+a b-x+y>0)          (-x^2+2 x y-y^2)/(2 (-1+a)^3 a (-1+b) b^2)        True      My question is how show should we interpret the conditional statements? In the last line we have that `g` is equal to `(-x^2 + 2 x y - y^2)/(2 (-1 + a)^3 a (-1 + b) b^2)` if `True`. Does this means this is the value of `g` **after the first two conditionals were tested and failed** ? The output above is obtained by the code below:               g[v_, x_,y_] := (Min[(-a v + x)/(1 - a - b + a b), (-a v + y)/(       1 - a - b + a b), 1] - Max[(-b + a b - a v + x)/(       1 - a - b + a b), (-b + a b - a v + y)/(1 - a - b + a b), 0])/(a - 1)^2/b^2          A = Assuming[0 < a < 1 && 0 < b < 1 && 0 < x < 1 && 0 < y < 1, Integrate[g[v, x, y], {v, Min[x, y]/a, Max[x, y]/a}]]          Assuming[0 < a < 1 && 0 < b < 1 && 0 < x < y < 1, Refine[A]]


Why there is an extra node left behind?

I intend to add a node and an edge to a RandomGraph when clicking on one of its existing nodes and drag the newly generated node to a new position. However, there always an extra node left behind at the clicked node. What is wrong with the following codes? Please help.               DynamicModule[{ rg },      rg = RandomGraph[{5, 8}] ;      edglst = EdgeList[rg];      vlst = VertexList[rg];      VPOS = VertexCoordinates /. AbsoluteOptions[rg, VertexCoordinates];           EventHandler[        g = Dynamic@Graph[vlst, edglst, VertexCoordinates -> VPOS,          VertexSize -> {.04, .04},          VertexLabels -> "Name",          PlotRange -> 2,          EdgeStyle -> {Thick} ],       {"MouseDown" :>           (pos = MousePosition["Graphics"];           ind = Position[ VPOS, Nearest[ VPOS, pos][[1]]][[1, 1]];          vnumb = Length[vlst] + 1;          AppendTo[vlst, vnumb];          AppendTo[VPOS, pos];          AppendTo[edglst, ind <-> vnumb];          ind = vnumb; ),        "MouseDragged" :> ( VPOS [[ ind]] = MousePosition["Graphics"] )        } ,       PassEventsDown -> True         ]      ]      @ Öskå If the newly generated node is dragged to an existing node, I intend to joint the two nodes. Please note the following codes, so substitute `MouseDown` with `MouseClicked` seems not good enough in this intention.               DynamicModule[{rg}, rg = RandomGraph[{7, 10}];      edglst = EdgeList[rg];      vlst = VertexList[rg];      OVP = VPOS =         VertexCoordinates /. AbsoluteOptions[rg, VertexCoordinates];           EventHandler[g = Dynamic@Graph[vlst, edglst,          VertexCoordinates -> VPOS,          VertexSize -> {.04, .04},          VertexLabels -> "Name",          PlotRange -> 3,          EdgeStyle -> {Thick}],       {"MouseDown" :> (pos = MousePosition["Graphics"];          ind = Position[VPOS, Nearest[VPOS, pos][[1]]][[1, 1]];          tmp = ind;          vnumb = Length[vlst] + 1;          AppendTo[vlst, vnumb];          AppendTo[VPOS, pos];          AppendTo[edglst, ind <-> vnumb];          ind = vnumb;),        "MouseDragged" :> (VPOS[[ind]] = MousePosition["Graphics"]),        "MouseUp" :> (pos2 = MousePosition["Graphics"];          ind2 = Position[OVP, Nearest[OVP, pos2][[1]]][[1, 1]];          vnumb = Length[vlst] ;          vlst = Drop[vlst, -1];          VPOS = Drop[VPOS, -1];          edglst = Drop [edglst, -1];          If[! (MemberQ[edglst, tmp <-> ind2] || MemberQ[edglst, ind2 <-> tmp]),          AppendTo[edglst, tmp <-> ind2]];           )        },       PassEventsDown -> True       ]      ]


BarChart that lines up with dates in DateListPlot

I am trying to create a chart similar to the view offered by `TradingChart`, but with custom data not relating to finance.               allData = {{"2014-03-31", 91.0657, 91.5555, Null, 79.4144, 90.0735, 86.9567, 87.1578, 79},                {"2014-04-06", Null, 90.9839, 85.0053, 79.2423, 87.7565, 85.0126, Null, 108},                {"2014-04-22", 90.9086, 90.9959, Null, 78.9365, 87.5949, 86.1197, Null, 93},                {"2014-04-28", 92.3299, 92.068, Null, 79.7057, 90.187, 86.4088, Null, 98}}      I am using the first column as a date marker, the last column as a volume counter, and the remaining columns as data for the line graph. I should be clear that the size of these data sets are flexible. There may be more or fewer dates and there may be more or fewer columns for lines. I clean up the data a little then place it into a `DateListPlot` (on the actual plots I have included a legend and better markers, but that is not so important here):               temp = Drop[allData, None, {-1}];          lineData = {};     For[i = 2, i < Length @ temp[[1]], i++,         AppendTo[lineData, Transpose[{temp[[;; , 1]], temp[[;; , i]]}]]     ];          DateListPlot[lineData,          Joined -> True,         PlotStyle -> Thick,          ImageSize -> Scaled[0.75],          PlotMarkers -> Automatic ,         PlotRange -> {Automatic, {70, 100}}     ]      Here is the output: ![Graph](http://i.stack.imgur.com/umplf.jpg) As you can see the data is sporadic. Some dates have no entries at all, some columns have Null values. It seems Mma is having some trouble with the sparse data. Ideally the lines would pass straight through to the next non-null entry, so some help with doing that would be appreciated. But the main question I have is with regards to putting a bar chart underneath this that matches up with the dates and uses the last column of `allData` as the volume. It is not clear if there is any way to do this with `Histogram` or with `BarChart` and I am not so experienced with Mma to know if I have to do this with `Graphics` primitives. Eventually I would like to add some interactivity, which is what drew me to the `TradingChart`: ![CountBars](http://i.stack.imgur.com/rivFb.jpg)


Combine absolute and relative (scaled) coordinates

I am using `Inset` to add an `Epilog` to a plot. The position of the images (in my case: framed numbers) can be specified as an option of `Inset`. I would like the y-coordinate to be the same for all `Inset` elements (they are created via `Table`), relative to the plot size. Say, for example, it should be the y-coordinate of `Scaled[*,0.9]`. The x-coordinate should, for each element, be an absolute value, depending on its position in the table. While I know how to specify relative and absolute coordinates, also as functions of the table position, I can't get `Scaled` to work for only one coordinate: specifying my `Inset` coordinates via something like               {*abs. value*, Scaled[.9]}      yields the following error message:               Coordinate {*abs. value*, Scaled[0.9]} should be a pair of numbers, or a Scaled or Offset form.      Any help on this? * * * **Update:** I also tried snippets like `Scaled[*some value*,.9][[2]]` to extract the y-coordinate, but to no avail.