Windows Patches/Updates in a hosting enviornment

Question: I'm looking for a good tool besides WSUS that will allow me to update Windows 2000/2003/2008 servers that are part of a domain/in a different domain/standalone enviornment.
The current products I'm looking at are
Kaseya
Security Manager Plus
Does anyone have any experience with these tools? How do they work in your environment? Are there any other tools that someone can recommend so I can take a look at it as well?
Comment: Are you looking for something to manage OS patches only?
Comment: @JohnThePro Yes John, Patches only
Answer: Remote RebootX is good. Was free, now have to pay, except if you kept the free version.
I guess SCCM from Microsoft is not an option ?
Comment: @Rome sure it can, through certificates. Even workgroups
Comment: +1 for SCCM. Ability to schedule maintenance windows and deploy different sets of updates via different update lists is extremely handy.
Comment: @ChrisMcK can SCCM work across domains that don't have existing forests between them?
Answer: Is it out of the question to let the servers reboot themselves? I use this for a good number of our servers through Group Policy and it has never let me down. Note that these servers are only rebooted in the wee hours of the morning and their uptime during that time is of no concern.
Comment: Hi Joel, unfortunately we need the ability to control exactly when the servers go down for their reboot. If 50 servers were rebooted and 10 of them don't come up then we'd have our hands full.


Is This A Counter-Example To The Theorem by Barndorff-Nielsen-Pedersen (1968)?

Question: In the textbook "Theory of Point Estimation" 2nd Ed. by Lehmann and Casella, Theorem 6.18 states:
Suppose $X_1, ..., X_n$ are real-valued IID according to a distribution with density $f_\theta(x_i)$ with respect to Lebesgue measure, which is continuous in $x_i$ and whose support for all $\theta$ is an interval I. Suppose that for the joing density of $X = (X_1, ..., X_n)$
$p_\theta(x) = f_\theta(x_1)...f_\theta(x_n)$
there exists a continuous $k$-dimensional sufficient statistic. Then
(i) if $k=1$, there exists function $\eta_1, B$ and $h$ such that (5.1) holds;
(ii) $k > 1$, and if ......
where (5.1) is: $p_\theta(x) = h(x) \exp[\sum_{i=1}^s \eta_i(\theta) T_i(x) - B(\theta)]$.
I seem to have a simple counter-example to this.
Consider the case of $n=1$ and distribution is $N(\mu, \sigma^2)$. Then we have a "continuous 1-dimensional sufficient statistic", the data point itself.  So, in this case $k = 1$.  Per the Theorem, the PDF can be written in the exponential family with $s = 1$.  But we know that cannot be done.
What am I understanding wrong here?
Note: I want to point out one thing (even though it is irrelevant for the problem at hand). Parameters here are well-identified even with just a single data point. Maximum likelihood would not exist but that really is another problem.
Comment: Does the theorem explicitly say that $s = 1$? In my copy it merely says that $\eta_1$ exists.. not that there are no $\eta_i$ with $i > 1$.
Comment: It is my understanding that is what he meant.  Also based on the overall context around the theorem, I am reasonably sure.    I found the exposition in this text to be rather hard to follow, great as E Lehmann was.  May he rest in peace.  I wish I could have asked him directly.
Comment: I found the original 1968 paper.  I will give it a try.
Answer: OK. I glanced through the original paper, which explicitly assumed that the number of data observations is strictly bigger than the dimension of the sufficient statistic.
So the paper is OK. The Theorem in the text is poorly stated.
Also, regarding Cat's comment, the original paper indeed stated that "if k = 1, then s = 1".


Reflection along subspace

Question: A symmetric space is a Riemannian manifold M with the following property:
For every point $p \in M$ there is an isometry $\phi: M \rightarrow M$
such that $\phi(p) = p$ and $\phi_*(v_p) = -v_p \in T_pM$.
I am interested in the following property of a Riemannian manifold $M$: For
every $p \in M$ and $H \subset T_pM$ a subspace there is an isometry $\phi: M \rightarrow M$
fixing p such that $\phi_*: T_pM \rightarrow T_pM$ is the reflection through the hyperplane $H$.
Has every symmetric space the above property? (The two dimensional simply connected symmetric spaces seem to have it)
Answer: A flat torus (that is, a rectangle with opposite sides identified) would seem to be a counterexample. It is symmetric, but for a generic point there are only a few directions you can reflect across.
On the torus, geodesics from a chosen point in different directions may either meet it again or not, so there cannot be an isometry that takes an arbitrary geodesic through the point to an arbitrary other one. However for any two rays in $\mathbb R^2$ there's always a line such that reflecting in it takes one to the other.
Basically you're requiring isotropy (because any rotation of the tangent space can be made as a composition of reflections), which severely limits the manifolds that work. I think all you'll get are spheres, Euclidean spaces, and hyperbolic ones (at various scales).
Comment: Yes, among simply-connected symmetric spaces you get only the constant curvature ones, since the required property implies that the isometry group acts transitively on the orthonormal frame bundle. Once you know this, you can  rule out non-simply connected ones too, except for the real-projective space.

Reflection along subspace


TextWriter.WriteLine IO Exception - The specified network name is no longer available

Question: I am trying to write text file after reading from a large tab delimited text file in a console application. Issue is that if I run many instances of this exe concurrently on a server, it gives me runtime error at TextWriter.WriteLine and then application crashes because of unhandled exception. This happens with all the instances. I fail to understand the reason for this behavior.. Is it because I am not using StringBuilder which will use memory dynamically ?
My code is as follows :
 StreamReader sr = new StreamReader(@FilePath, System.Text.Encoding.Default);
 string mainLine = sr.ReadLine();
 string[] fileHeaders = mainLine.Split(new string[] { "\t" }, StringSplitOptions.None);
 string newLine = "";

 System.IO.StreamWriter outFileSw = new System.IO.StreamWriter(@outFile);

 while (!sr.EndOfStream)
 {
    mainLine = sr.ReadLine();
    string[] originalLine = mainLine.Split(new string[] { "\t" }, StringSplitOptions.None);

   newLine = "";
   for (int i = 0; i < fileHeaders.Length; i++)
   {
      if(fileHeaders[i].Trim() != "")
       newLine = newLine + fileHeaders[i].Trim() + "=" + originalLine[i].Trim() + "&";
   }

outFileSw.WriteLine(newLine.Remove(newLine.Length - 1));
FileInfo fileInfo = new FileInfo(@outFile);

  if (fileInfo.Length > (1.3 * 1024.0 * 1024.0 * 1024.0)) // greater than 1.3 GB
  {
          outFileSw.Close();
          outFileNumber = outFileNumber + 1;
          outFileSw = new System.IO.StreamWriter(@outFile + outFileNumber.ToString() + ".txt");
  }

}
outFileSw.Dispose();
sr.Close();
sr.Dispose();

Error details are :
Exception Message: The specified network name is no longer available.

Stack Trace:    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
 at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count)
 at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
 at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
 at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count)
 at System.IO.TextWriter.WriteLine(String value)
 at ExampleExe.ExampleProcess.FnFiles()

 Unhandled Exception: System.IO.IOException: The specified network name is no longer available.

 at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
 at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count)
 at System.IO.FileStream.FlushWrite(Boolean calledFromFinalizer)
 at System.IO.FileStream.Dispose(Boolean disposing)
 at System.IO.FileStream.Finalize()

Thanks,
Kanu
Comment: Do you ever close those files? `using(){}` is very useful in these cases.
Comment: Are you writing on a network path? Ideally you would want to buffer instead of writing each line, that would reduce number of raw IO. You can buffer e.g. 10MB into stringbuider or byte buffer before dumping the content to file.
Comment: Try taking a network trace and a filemon trace.
Comment: @nrodic: Yes.. I do close and dispose after processing the complete file from which I am reading. Further, the error happens when the application is trying to write the file.
Comment: @nordic: I edited the question text to show how I do Close and Dispose...
Comment: Do you write concurrently from many processes into the same file?
Comment: @nrodic: Nope.. Thing is that I run max 8 instances concurrently. All of them reading and writing different files but only from and to same folders.. and this error is also not encountered everytime. It occurs randomly. This is why it made me think that it is probably dynamic memory issue...
Comment: There is a MS KB article on this: http://support.microsoft.com/kb/961293 which mentions this can be caused by Symantec Endpoint Protection.
Comment: @loopedcode: I am reading and writing files on same network path. However, the console application is set up on another server. I was thinking that there is problem with the server where I have the exe running .... as this problem seem to happen when this server has many other processes running.
Comment: @loopedcode: I saw this article.. We don't have Symantec..
Comment: Don't `Close()` *and* `Dispose()`. Choose one or the other. Further, use `using` as per nrodic and it'll take care of the `Dispose()` for you and you'll not need to worry about either.
Comment: @JesseC.Slicer: Will do that..
Comment: The error message means that the connection to the server got broken. That is where you need to focus your investigation.
Comment: @RaymondChen : Came across [link](http://community.spiceworks.com/topic/239423-the-specified-network-name-is-no-longer-available-while-writing-to-shared-dir) .. Application server looks ok and its AVG's Resident Shield is disabled too .. Any other suggestions ?
Comment: @loopedcode : I think what you say about raw IO might be true ... I wanted to try writing to buffer before writing to a file. Could you point to a code which will help me understand how should I go about doing it ?
Comment: @kanu: I posted a sample below.
Answer: Here is a FileWriter with StringBuilder buffer. It uses a separate thread to write while main thread keeps accumulating data. Writes 10MB buffer at a time. Buffered data is kept in Queue object; writer thread removes item from this Queue and writes it out full using with File.AppendAllText method.
private Queue<StringBuilder> writeQueue;
private bool isComplete;

public void FileWriter()
{
    this.isComplete = false;
    this.writeQueue = new Queue<StringBuilder>();

    var writer = new Action<string>(this.StartWriting);
    var writerAsync = writer.BeginInvoke(@"outputfile.txt", null, null);

    using (StreamReader sr = new StreamReader(@"inputfile.txt"))
    {
        var fileHeaders = sr.ReadLine()
            .Split('\t')
            .Where(i => !string.IsNullOrEmpty(i))
            .Select(j => j.Trim())
            .ToList();

        var buffer = new StringBuilder();
        while (!sr.EndOfStream)
        {
            var originalLine = sr.ReadLine()
                .Split('\t')
                .Where(i => !string.IsNullOrEmpty(i))
                .Select(j => j.Trim())
                .ToList();

            var line = new StringBuilder();
            //Must have same number of items
            if (originalLine.Count == fileHeaders.Count)
            {
                for (int i = 0; i < fileHeaders.Count(); i++)
                {
                    line.AppendFormat("{0}={1}&", fileHeaders[i], originalLine[i]);
                }
                line.AppendLine();
            }

            buffer.AppendLine(line.ToString());
            if (buffer.Length > 1024 * 1024 * 10)//approx 10MB
            {
                lock (this.writeQueue)
                {
                    this.writeQueue.Enqueue(buffer);
                }
                buffer = new StringBuilder();
            }
        }
        //Queue any final remaining data
        if (buffer.Length>0) lock (this.writeQueue)
        {
            this.writeQueue.Enqueue(buffer);
        }
    }
    this.isComplete = true;
    writer.EndInvoke(writerAsync);
}

private void StartWriting(string outFilePath)
{
    while (!this.isComplete || this.writeQueue.Count > 0)
    {
        StringBuilder queuedItem;
        if (this.writeQueue.Count > 0)
        {
            lock (this.writeQueue)
            {
                queuedItem = this.writeQueue.Dequeue();
            }
            File.AppendAllText(outFilePath, queuedItem.ToString());
        }
        System.Threading.Thread.Sleep(5000); //Sleep 5sec
    }
}

Comment: Number of threads would be limited by CPU time and resources. You will have to test whats optimal with different numbers to see whats optimal. Try with 2 and move up until you don't see any more performance gain. But ultimately you will be bottle-necked by network traffic for your remote file write to complete. And also, if you would be using this, then accept this as answer and vote up.
Comment: One more question ... even though I use buffer, there still will be limitation to the number of threads I run concurrently depending on a server ?


Create custom clipboardData property for ClipboardEvent

Question: In my Karma-Jasmine tests I have to test my onPaste method.
onPaste method:
onPaste(event: any): void {
  const pastedText = event.clipboardData.getData('text/plain');
  // some stuff
}

My unit test:
it('should do something', () => {
  const queryField = fixture.debugElement.query(By.css('input[type="search"]')).nativeElement;
  queryField.dispatchEvent(new ClipboardEvent('paste', {
    dataType: 'text/plain',
    data: '325435956\r325435956',
  }));
  // some stuff
})

And I use Chrome to run the tests but new ClipboardEvent() in Chrome creates ClipboardEvent object where clipboardData is null and event.clipboardData.getData('text/plain') throws an error:
Uncaught TypeError: Cannot read property 'getData' of null

It doesn't happen in Firefox, so if I use karma-firefox-launcher it works fine, but I have to use Chrome. So, I had some ideas how to solve it.
The first idea was to create ClipboardEvent object and override clipboardData property:
const pasteEvent = new ClipboardEvent('paste', {
  dataType: 'text/plain',
  data: '325435956\r325435956',
});

pasteEvent.clipboardData = {
  getData() {
    return this.data;
  }
};

But I can't do it because clipboardData is a read-only property.
The second idea was to create fake ClipboardEvent object:
function FakePasteEvent(options) {
  this.clipboardData = {
    dataType: options.dataType,
    data: options.data,
    getData() {
      return this.data;
    }
  };
}
const pasteEvent = new FakePasteEvent({
  dataType: 'text/plain',
  data: '325435956\r325435956',
});

console.log(pasteEvent.clipboardData.getData()) // returns what I need

But I can't pass it to dispatchEvent because the type of pasteEvent is not Event. Then I thought I can specify prototype object for my FakePasteEvent:
Object.setPrototypeOf(pasteEvent, ClipboardEvent);

But anyway I've got an error:
TypeError: Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'
Can you help me to solve this problem? ;)
Code example here http://jsbin.com/puqilivalo/1/edit?html,js,console,output
Answer: Quite interestingly, I am currently struggling on who is right between chrome and Firefox on this, I still can't figure out what the specs tell when they say

dictionary ClipboardEventInit : EventInit {
 DataTransfer? clipboardData = null;
};

and

[Constructor (DOMString type, optional ClipboardEventInit eventInitDict), Exposed=Window]
 interface ClipboardEvent : Event {
 readonly attribute DataTransfer? clipboardData;
};

I would tend to say that Chrome is right when it returns null for the clipboardData property, but then the very next example makes FF behavior correct:

Example 3
  var pasteEvent = new ClipboardEvent('paste');
  pasteEvent.clipboardData.items.add('My string', 'text/plain');
  document.dispatchEvent(pasteEvent);

But anyway, Chrome does support (partially) the DataTransfer contructor, whereas FF still doesn't. And you can then construct your event with this DataTransfer object in chrome too:

var dT = null;
try{ dT = new DataTransfer();} catch(e){}
var evt = new ClipboardEvent('paste', {clipboardData: dT});
console.log('clipboardData available: ', !!evt.clipboardData);
evt.clipboardData.setData('text/plain', 'Hello world');

document.onpaste = function(e){
  console.log('onpaste: ', e.clipboardData.getData('text/plain'));
};
document.dispatchEvent(evt);
Comment: @artiek I edited with full procedure and here is an update to your jsbin: http://jsbin.com/xahaquxodo/2/edit?html,js,console,output
Comment: Firefox started supporting the `DataTransfer` constructor after this answer was written, so it can now work without the try/catch and be simplified to just `new ClipboardEvent('paste', {clipboardData: new DataTransfer()});`


How to access the source code for an imported class in Java?

Question: In some code I'm looking at, there was this import statement.
import husaynhakeem.io.facedetector.models.FaceBounds
How do I find the code in this FaceBounds class? I have tried looking on the user's github but I have not been able to find the actual class. The only classes I find are Facing.kt, Orientation.kt and models.kt but not the Facebounds class.  https://github.com/husaynhakeem/android-face-detector/tree/master/facedetector/src/main/java/husaynhakeem/io/facedetector/models
Answer: data class FaceBounds(val id: Int, val box: Rect)
It's in models.kt


Violin Pickup that will sound like natural violin?

Question: I have been looking for years for a violin piezo pickup (or any other that is feedback-safe guaranteed), that won't ruin the violin sound.
All the PUs I've been experimented with over the last decade (some more, some less) were nasal, nylonish, and ruined the original violin sound.
I am looking for either:

A pickup that will truly pickup the violin sound
A pedal/appliance that recreates the PUed sound so it sounds like original (or makes it even better by choosing preset patches, e.g., it should sound like Stradivari, Guarneri, etc.)
Comment: This question seems reasonable... Equipment questions __ARE__ on-topic, and I feel this is constructed in a way that lends itself to good answers with a minimum of subjectivity.
Comment: I wouldn't say it's off-topic since the forum is called "Practice and Performance" this question is really about a performance issue me and zillion other violinists have, and is a board for that special one and only violinist that bumped into that feedback resistant piezo PU willing to share his surprise with other people. So no one looks for promotion, if there is a good thing, we should know about it, not because we promote the brand but because we deserve it! Anyway, if that said and you still think this is off-topic, please tell me and I'll go ahead an delete this question.
Comment: As this question is currently written, it's a [shopping recommendation](http://meta.music.stackexchange.com/questions/125/are-shopping-list-questions-on-topic) and off-topic. Possibly rewrite so the question is asking what qualities to look for in a pickup? (And, BTW, except for the feedback-proof part, there is such a pickup. It's called a microphone.)
Comment: This question is similar to this one: http://music.stackexchange.com/questions/1734/how-do-i-find-a-good-reverb-pedal-for-a-huge-soul-filling-sound/1736#1736. I think it's okay, he's not asking a "whats the best piezo pickup ever?" kind of question. You could change the question to be: "What are some attributes of a natural sounding violin pickup and how do I select a good one?" and it'd probably get more nods.
Comment: I largely agree with neilfein. Something along the lines of "How can I record a violin so that it sounds natural?" would be a better question. I think it will be closed unless you rewrite it.
Comment: "violin piezo pickup ... but all of them were nasal"  Were you using a preamp?  Piezo pickups *require* a very high input impedance preamp, or they will roll-off the low end.  The output impedance of a piezo will be [something like 1 MΩ](http://www.wolframalpha.com/input/?i=1%2F%282*pi*680+pF*196+Hz%29+to+M%CE%A9) at the G string's fundamental, so the input impedance of the preamp should be at least 10 MΩ.
Comment: @endolith, Yes, my question was about the signal after having it passed via an active DI box / preamp.
Answer: I don't know much about violin, but I do know a thing or two about pickups :). Piezoelectric pickups are nothing like a standard electric guitar pickup in that no magnetic field is induced while you are playing--which makes them suitable for applications such as violin and classical guitar where no metal is involved. Due to their construction they have much higher output impedance than an average passive pickup and consequently use an output buffer to properly drive the line. Unfortunately, this combination of features will never result in a completely natural violin sound. Output buffers tend to be very simple to make, and they almost always color the tone of your instrument because they are designed to boost some frequencies and attenuate others in the name of controlling clipping. There are some that have been manufactured to have a flatter frequency response (David Barber's B-Buff comes to mind) but I haven't seen any of those incorporated into a piezoelectric pickup, and they are large and bulky due to the higher quality components required to build them than a standard JFET/OpAmp buffer.
So, with this in mind were I you I would simply continue experimenting until I found a pickup that I was completely happy with. A piezo will never sound as lush or natural as a nice ribbon microphone or even a lower end condenser due to the reasons discussed above, but when looking for a good piezoelectric pickup consider the following features:

Controllable EQ. If you can control which frequencies are attenuated/boosted from the pickup then you'll have better success dialing in a sound you like. You can also achieve this by running the line from the Piezo into a pedal such as the L.R. Baggs paracoustic DI and controlling it from there.
Higher quality or transparent buffer/pre-amplifier. This will control the tone coloring I discussed earlier. It will never be perfect, but you can get very close with nicer components.

All things said the best tone from your violin will come from a nice microphone, but like all situations similar to this it's the musicians plight to compromise and find the best trade off of practical application to tone. Don't be a perfectionist unless you need to be. Studio musicians and people who play in symphonies will almost always choose a ribbon or high quality condenser microphone over a pickup, but touring fiddle players with a country band might live with a piezo and EQ it to their liking. Find the right compromise for your application.
Comment: As I said, if you want the true tone then you're best option is to mike it. There isn't a Piezo that exists that will reproduce it perfectly. Make the best trade off based on your application.
Comment: A transducer won't be "100% feedback resistant" either, and a sufficiently focussed mic might well be resistant enough for feedback.
Comment: I wonder whether an additional approach would be to place multiple soundboard transducers, to pick up frequencies from various parts of the board; then mix and EQ the outputs to taste.
Comment: You have to know the the violin-tone structure is much more sophisticated and complicated than the guitar's tone. a bowed tone is very rich and complex compared to a plucked tone. here is where all (is there an exception?) violin piezos completely ruin the violin sound. I know this is tweakable, but still far from expected original signal.
Comment: A mike is not an option in my case. I need a %100 feedback resistant microphone, which turns out that the only option is a piezo, unless you know something I don't. Anyway, what among the various violin PUs you've tried would sound mostly "violin" rather than the famous nasal violin piezo sound?
Comment: ... also bear in mind that when the sound levels are so loud that feedback is a real problem, people's ears and brains are too overloaded to appreciate subtleties of tone in any case. Sorry about the multiple comments. Lots to say that's not quite good enough to put into an answer.
Comment: "which makes them suitable for applications such as violin and classical guitar where no metal is involved" Magnetic pickups would work fine with violin since the strings are ferromagnetic steel. The pickups would be bulky though.  "Output buffers ... almost always color the tone of your instrument because they are designed to boost some frequencies and attenuate others in the name of controlling clipping." I think this is the opposite of the problem.  Do you have a reference? The reason they have a bad sound is because they have a naturally flat response, while the violin does not.
Answer: I have also tried several kinds of piezo-pickup to record myself and amplify sound in certain situations, even tried a cello bridge with cell inside a leg and various other systems for violin and viola. For the time being I am not using any kind of piezo but using a BASIK external pickup from SCHERTLER because it fits my own criteria:

Not ridiculously high price for an amateur.
Picks the table vibrations, with a sufficiently good signal in the bass register. I feel (but I cannot prove) that the sound I get from it has a richness I like and do not overrepresent high frequencies.
When trying it first I did not feel I had to change things in my technique in order to produce a good result. But I did change my technique once I had the occasion of listening carefully my recordings, with the help of other people who could listen to performance and reproduction.
External (pasted on the table) so I can have only one system for my different instruments (but you have to test what it gives on your varnish first, of course)
I have not noticed an essential change between the violin unfitted and the violin fitted
1.5V preamp fits the kind of thing I do most of the time (recording) and my equipment but there is also a Phantom Alim preamp.
The same company makes other (a lot more expensive) recording and amplification systems so this is not an isolated product, but an entry level one by a serious house.

This is certainly not the only choice and I do not know about the availability and price in most countries.
Drawbacks :

I have to be very careful about the way I plug wires, and the alimentation, and take the instrument because I can easily knot myself in them if I do not it orderly (it is more my problem than the system's.). I have to think of dressing with clothes with pockets because it is easier that way.
The amplification is certainly colored in various ways and using the same sensor for both a violin and a cello is not ideal.  I would need a very good recording installation to make a safe evaluation of that.
Pasting/repasting when changing instruments induce a lack of consistency and variety (but this is a drawback of having only one sensor)
Comment: thanks for your helpful response. I've never had the chance to try out their products. 1) How is it on VERY load stages? is it completely feedback resistent? 2) Price range (the BASIK and the PROs +)
Comment: @Shimmy: I have no experience for very loaded stages or loud feedback. In this case a sensor on the bridge might be the best (the table can easily vibrate to other instruments'sound, the bridge less so). For the price range, I bought mine a few years ago for around one hundred euros. A simple web search should help you for the current prices.
Answer: The "natural sound" of a violin occurs in interaction with the acoustic space around it.  A pickup, as opposed to a microphone, does not capture that.  Forget about the natural sound: the pickup is the starting point for building an electronic instrument.  Now part of a natural instrument is how it transmits (and not transmits) frequencies to space, so if you are going for kind of a natural sound, you'll likely need to EQ the heck out of what your pickup gives you (and likely add some minimal reverb as well), and that's assuming that the pickup gives you an accurate rendition of the body's vibrations.  Even then, you'll end up not with the natural sound of your violin but something approaching violin sound in general.
Answer: In my experience the best way of reproducing the natural sound is actually to not use a dedicated pickup at all, but to use a clip on mic such as the ATM350. I've had good results with this personally, it's small, discreet, easily clips on the chin rest and produces a much more natural, airy violin sound than a dedicated pickup. I've found that unless stage levels are ridiculous, they also do a rather good job of rejecting background noise too.
They do sell at around £150, so they're not ridiculously cheap - but not completely out of the range for most people either.


Given the result, follow de sequence

Question: I am trying to figure out several sequences about simple numbers.
Given simple sequences following x^2 T times.
2^2(6 times) =>
002 004 008 016 032 064
3^2(5 times) =>
003 009 027 081 243
Then, I have to transform it into a sequence of sums of the previous numbers.
2 4 8 16 32 64
become
2 6 14 30 62 126
My question is: Given a sum of a sequence and the T(times), how to I figure out(GENERIC WAY) the x from x^2?
Example:
Given 126 as the sum of the sequence, knowing it was interacted 6 times, what is the x^2 6 times in sequence, and then summed all the number, gives as result 126.
Answer: 2.
Times:
1 2 3 4 5 6 7
Sequence 2^2 7 times:
2 4 8 16 32 64
Sum:
2 + 4 + 8 + 16 + 32 + 64 => 126
Comment: Nice question! Do you know anything about "geometric series" (geometric sequences, geometric progressions)? If not, look them up, and see if you can work out how they relate to your question.
Comment: "Sequence 2^2 6 times" doesn't make sense. You mean either "Sequence of 6 iterates of the function $x\mapsto2x$" or "First 6 terms of the sequence 2^n".
Answer: Your question is, given $n$ and also $$k=a+a^2+...+a^n,$$ find the value of the initial term $a$.
The sum on the right is $$k=\frac{a^{n+1}-a}{a-1},$$ so that you seek the solution(s) to
$$a^{n+1}-(k+1)a+k=0.$$
If the given $n$ is 2 or more this is at least a cubic equation, and somewhat difficult to solve directly.
Provided the sequences are integers, you could use that $a$ is a factor of $k$, and so search for the solution $a$ among the factors of $k$.
EDIT: Actually 1 is a solution of the equation, and you could rule that out easily since if $a=1$ then $n=k$. On factoring out $x-a$ one just arrives back at the original equation $$k=a+a^2+...+a^n,$$ which is of degree $n$ and also difficult to solve directly.

Given the result, follow de sequence


Erro ao conectar cadastro formulário , com Banco de dados

Question: Abaixo print do erro Cannot invoke "String.trim()" because "in" is null:
`Erro no Netbeans:Deployment error: Error during incremental deploy: java.io.IOException: C:/Terçou/wildfly-26.0.1.Final/standalone/deployments/website.war
See the server log for details.
BUILD FAILED (total time: 43 seconds).

<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <%
                //1)Receber os dados vindo do formulário CadastrarProdutos.html
                int codigo;
                String nome, marca;
                double preco;
                codigo = Integer.parseInt(request.getParameter("codigo"));
                nome = request.getParameter("nome");
                marca = request.getParameter("marca");
                preco = Double.parseDouble(request.getParameter("PRECO"));

                try {
                    //2)Conectar com o Banco de dados

                    Class.forName("com.mysql.jdbc.Driver");
                    Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost:3306/bancoterca", "root", "1234");

                    //3)Enviar os dados para a tabela do banco de dados
                    PreparedStatement st = conexao.prepareStatement("INSERT INTO produtos VALUES(?, ?, ?, ?)");
                    st.setInt(1, codigo);
                    st.setString(2, nome);
                    st.setString(3, marca);
                    st.setDouble(4, preco);
                    st.executeUpdate(); // executa o INSERT na tabela do BD
                    out.print("
Dados salvos com sucesso
");

                    //4)Desconectar do banco de dados
                      conexao.close();

            } catch (ClassNotFoundException x) {
                out.print("Você não colocou o driver JDBC no projeto " + x.getMessage());
            } catch (SQLException x) {
                if(x.getErrorCode()==1062){ //Tentativa de duplicação de chave primária (código)
                    out.print("Este código de produto já está cadastrado");
                }else{
                    out.println("Erro número:" + x.getErrorCode());
                    out.println("Entre em contato com o administrador do sistema");
                }
            }
        %>

<!DOCTYPE html>

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <form method="post" action="CadastrarProduto.jsp">

                 Código:*
                <input type="text" name="codigo" size="20" maxlength="20" id="codigo" required>

                 Nome do produto:*
                <input type="text" name="nome" size="50" maxlength="50" id="nome" required>

                 Marca:
                <input type="text" name="marca" size="30" maxlength="30" id="marca">

                 Preço:
               <input type="text" name="preco" id="preco" pattern="[0-9]{1,9}\,[0-9]{1,2}$">

                <input type="submit" value="Salvar">

        </form>

Answer: Vi numa das imagens que existe um outro erro sobre o in não conseguir ser resolvido pelo String.trim() por estar null. Acho que pode ser outro problema
Voltando um passo atrás, para o build: Você tem o Maven instalado? Poderia informar que erro ocorre ao rodar o comando mvn clean install?
Eu particularmente não gosto de utilizar deploys incrementais.
Executo o comando de build acima e arrasto o .war para a pasta de deployments, e só aí ligo server


Ruby on rails: start_form_tag method

Question: I'm trying to learn ruby on rails.  I've been going through a tutorial, but I've gotten stuck.
It has me using start_form_tag and end_form_tag around an input form.  However, when I access the page, I get undefined method 'start_form_tag' for #<ActionView::Base:0x2556020>
In the tutorial, they explain that these two lines are translated into <form action="/book/create" method="post"> and </form>.   As such, I tried putting those instead.  The form out come up, but when I submitted the form, I get this error: ActionController::InvalidAuthenticityToken in BookController#create
So,

What do I have to do to get start_form_tag to translate correctly?
Is this causing the InvalidAuthenticityToken error?
Answer: I had the same problem when I started learning Rails. You have tutorial for old Rails version. start_form_tag is no longer used. I think the best place to learn Rails is Rails Guides
So, your question now. You can add form like this:
<% form_for @book do |f| %>
  <%= f.label :title %>
  <%= f.text_filed :title %>
  ...
  <%= f.submit 'Create' %>
<% end %>

Answer: The tutorial you're reading is outdated. Forms are now built using form_for blocks.
You can find a more up-to-date (and official) guide here. You can probably use it to complete the tutorial you're doing now.
Answer: Try this:

Add new book

<%= form_tag :action => 'create' %>

Title:
<%= text_field 'book','title' %>

Price:
<%= text_field 'book','price'%>

Subject:
<%= collection_select(:book,:subject_id,@subjects,:id,:name)%>

Description

<%= text_area 'book','description'%>

<%= submit_tag "Create"%>
<%= link_to 'Back',{:action=>'list'}%>

Ruby on rails: start_form_tag method


Suppose you have a 500x500 grid, you need to form squares of size 20x20. How many such squares can you form in the grid, with a step (stride) of 5?

Question: If the step was 1, one could say the answer is (500-20+1)^2. But with this step of 5, how do  calculate?
Comment: Can you be more specific on what you mean by "step size"?
Comment: Should've called as just 'step'. Also called stride.
Answer: If I understand what you mean by 'stride' correctly, you could just "scale down" by a factor of $5$; the grid size would then be $100 \times 100$, the squares would be $4 \times 4$, and the stride would be size $1$. Then use the same formula you used before to get $\,(100-4+1)^2\,$.
More generally, in an $\,n \times n\,$ grid, forming $\,m \times m\,$ squares with a stride size of $\,k,\,$ the number of squares would be
$$\left(\left\lfloor{\frac{n-m}{k}}\right\rfloor + 1\right)^2$$
Comment: Thank you so much! I couldn't frame the question accurately, so apologies.


Loop não retorna os valores na tela

Question: Olá, estou desenvolvendo um calculo de custo de compra e venda utilizando JS e PHP.
O JS me retorna os valores corretamente, porém não envia para os campos, se alguém puder me iluminar ficarei agradecido.
Segue o JS:
$(document).ready(function() {
          $('.calc').change(function() {
            calculaCustoCompra();
          })
          insira o código aqui
        }

        function calculaCustoCompra() {
          var i;
          for (i = 1; i < 7; i++) {
            var parametros = {
              tipo: $('#custoProdutoTipoCompra' + i).val(),
              preco: $('#custoProdutoProCompra').val(),
              perc: $('#custoProdutoPercentualCompra' + i).val(),
              valor: $('#custoProdutoValorCompra' + i).val(),
            };

            $.ajax({
              url: urlBase + '/custosProdutos/calculaCustoCompra',
              type: "POST",
              data: parametros,
              beforeSend: function() {
                waitingDialog.show('Calculando', {
                  dialogSize: 'sm'
                });
              },
              success: function(data) {
                data = jQuery.parseJSON(data);
                $('#custoProdutoTotal').val(data.custoTotalCompra);
                $('#custoProdutoValorCompra' + i).val(data.valor);
                $('#custoProdutoPercentualCompra' + i).val(data.perc);

                waitingDialog.hide();

              },
              error: function(error) {
                alert(error);
                waitingDialog.hide();
              }
            });

          }

        }

HTML:

          ICMS

            <select name="data[custoProduto][TipoCompra1]" class="form-control form-control-sm calc" id="custoProdutoTipoCompra1">
              <option value="1">Somar</option>
              <option value="2" selected="selected">Subtrair</option>
            </select>

<input name="data[custoProduto][PercentualCompra1]" value="18,00" style="width:60%;" class="form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoPercentualCompra1">

<input name="data[custoProduto][ValorCompra1]" style="width:60%;" value="0,00" class=" form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoValorCompra1">

          IPI

            <select name="data[custoProduto][TipoCompra2]" class="form-control form-control-sm calc" id="custoProdutoTipoCompra2">
              <option value="1" selected="selected">Somar</option>
              <option value="2">Subtrair</option>
            </select>

<input name="data[custoProduto][PercentualCompra2]" value="0,00" style="width:60%;" class="form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoPercentualCompra2">

<input name="data[custoProduto][ValorCompra2]" style="width:60%;" value="0,00" class=" form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoValorCompra2">

          ISS

            <select name="data[custoProduto][TipoCompra3]" class="form-control form-control-sm calc" id="custoProdutoTipoCompra3">
              <option value="1" selected="selected">Somar</option>
              <option value="2">Subtrair</option>
            </select>

<input name="data[custoProduto][PercentualCompra3]" value="0,00" style="width:60%;" class="form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoPercentualCompra3">

<input name="data[custoProduto][ValorCompra3]" style="width:60%;" value="0,00" class=" form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoValorCompra3">

          PIS

            <select name="data[custoProduto][TipoCompra4]" class="form-control form-control-sm calc" id="custoProdutoTipoCompra4">
              <option value="1" selected="selected">Somar</option>
              <option value="2">Subtrair</option>
            </select>

<input name="data[custoProduto][PercentualCompra4]" value="2,00" style="width:60%;" class="form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoPercentualCompra4">

<input name="data[custoProduto][ValorCompra4]" style="width:60%;" value="0,00" class=" form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoValorCompra4">

          COFINS

            <select name="data[custoProduto][TipoCompra5]" class="form-control form-control-sm calc" id="custoProdutoTipoCompra5">
              <option value="1" selected="selected">Somar</option>
              <option value="2">Subtrair</option>
            </select>

<input name="data[custoProduto][PercentualCompra5]" value="0,00" style="width:60%;" class="form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoPercentualCompra5">

<input name="data[custoProduto][ValorCompra5]" style="width:60%;" value="0,00" class=" form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoValorCompra5">

          FRETE/SEGURO

            <select name="data[custoProduto][TipoCompra6]" class="form-control form-control-sm calc" id="custoProdutoTipoCompra6">
              <option value="1" selected="selected">Somar</option>
              <option value="2">Subtrair</option>
            </select>

<input name="data[custoProduto][PercentualCompra6]" value="10,00" style="width:60%;" class="form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoPercentualCompra6">

<input name="data[custoProduto][ValorCompra6]" style="width:60%;" value="0,00" class=" form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoValorCompra6">

          II

            <select name="data[custoProduto][TipoCompra7]" class="form-control form-control-sm calc" id="custoProdutoTipoCompra7">
              <option value="1" selected="selected">Somar</option>
              <option value="2">Subtrair</option>
            </select>

<input name="data[custoProduto][PercentualCompra7]" value="1,60" style="width:60%;" class="form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoPercentualCompra7">

<input name="data[custoProduto][ValorCompra7]" style="width:60%;" value="0,00" class=" form-control form-control-sm valor calc" onkeypress="return SomenteNumero(event)" type="text" id="custoProdutoValorCompra7">

Os elementos estão me retornando o calculo corretamente, por exemplo:

{"custoTotalCompra":"17,6400","valor":"3,36","perc":"16,00"}
  {"custoTotalCompra":"23,1000","valor":"2,10","perc":"10,00"}

Mas os campos não estão sendo preenchidos com os valores informados.
Comment: Bota o código HTML renderizado, fica melhor pra simular.
Comment: Opa, coloquei ele
Comment: Seu console está mostrando algum erro?
Comment: nenhum, mas eu mantive o alert('i'); pra conferir, e ele aparece apenas o numero 7 varias vezes, deveria mostrar, 1,2,3,4,5,6 nao?
Answer: Consegui resolver o problema com a seguinte solução:
function calculaCustoCompra(){
for(var i = 1;i < 10;i++){
    (function(){
        var id = i;
        var parametros = {
            tipo: $('#custoProdutoTipoCompra'+id).val(),
            preco: $('#custoProdutoProCompra').val(),
            perc: $('#custoProdutoPercentualCompra'+id).val(),
            valor: $('#custoProdutoValorCompra'+id).val(),
        };

            $.ajax({
                url: urlBase + '/custosProdutos/calculaCustoCompra',
                type: "POST",
                data: parametros,
                beforeSend: function(){
                    waitingDialog.show('Calculando',{dialogSize: 'sm'});
                },
                success: function (data) {
                    data = jQuery.parseJSON(data);
                    $('#custoProdutoTotal').val(data.custoTotalCompra);
                    $('#custoProdutoValorCompra'+id).val(data.valor);
                    $('#custoProdutoPercentualCompra'+id).val(data.perc);
                    alert(id);
                    console.log(data);

                    waitingDialog.hide();

                },
                error: function (error) {
                    alert(error);
                    waitingDialog.hide();
                }
            });
    }) ();
};

}
adicionando o function(){
for(var i = 1;i < 10;i++){
        (function(){
Answer: Opa, vamos tentar resolver o seu problema.
Tente trocar o código:
  $('#custoProdutoTotal').val(data.custoTotalCompra);

Por:
  $('#custoProdutoTotal').html(data.custoTotalCompra);

Comment: Sem efeito, com .val() aparece o ultimo numero total "gerado", porem com html nem isso.
Comment: Faça um `console.log(data)` e mostre a saída.
Comment: `Object { custoTotalCompra: "21,0000", valor: "0,00", perc: "0,00" }`
custosProdutos.js:97:29
`Object { custoTotalCompra: "21,4200", valor: "0,42", perc: "2,00" }`
custosProdutos.js:97:29
`Object { custoTotalCompra: "21,0000", valor: "0,00", perc: "0,00" }`
custosProdutos.js:97:29
`Object { custoTotalCompra: "18,9000", valor: "2,10", perc: "10,00" }`
custosProdutos.js:97:29
`Object { custoTotalCompra: "21,0000", valor: "0,00", perc: "0,00" }`
custosProdutos.js:97:29
`Object { custoTotalCompra: "21,0000", valor: "0,00", perc: "0,00" }`
custosProdutos.js:97:29

Loop não retorna os valores na tela


Proper steps for updating Apache conf on production server?

Question: I usually:

Update my local near-replica ( ServerName directive and Logs will obviously be different ) of the production conf file and make my changes for things like rewrite rules.
/etc/init.d/apache2 restart or graceful locally and ensure it's working
scp the conf file to the production server
apache2ctl configtest
apache2ctl graceful

I never really followed any sort of guide, just picked up some commands. Is this usually the way it's done? I almost always use graceful on the production server since I don't want to lose clients with a full restart - graceful restarting is fairly common, right? Are there any circumstances where graceful isn't sufficient and I need to do a full restart?
Answer: It depends on the scale you're at -- you've got the basic steps down, the main differences would be in how the config file is propagated to the production servers (bigger sites would involve things like checking it into revision control and waiting for or forcing Puppet, Chef, CfEngine, etc. to propagate the change out) and the degree of automation that is used (again, bigger sites hopefully have more automated procedures, since they'll be dealing with more than one server).
AS for graceful versus hard restart -- in the graceful, the "main" Apache parent process doesn't exit, just the worker child processes. I've seen circumstances where the primary process had some sort of cached state -- old DNS, whatever -- that didn't get flushed with a graceful, only a full stop/start cycle.
Comment: so would you recommend using graceful? would it help invoking graceful multiple times regarding the caching issue?
Comment: if you're just putting a new config in place, graceful will be sufficient. you can save the full bore stop/start cycle for troubleshooting strange happenings. 8^)


Authcache: Getting user_link to work in template.php

Question: Problem
I'm trying to set-up an Authcache customised menu.
The first way of doing it would be to create 3 menus, one for each of my roles and one for anon then create a custom tpl.php for each using the user_link and user_name variables.
(These variables are provided by the user example module in authcache to all templates.)
Block logic would then give the correct user the correct menu.
It seems a little clumsy.
Is it possible to grab the links inside template.php and use user_link and user_name variables there because I can't find a function which has the links available.
Or how has anyone else solved this problem?
Answer: Ok so here is my solution.
Menu's are themed in MYTHEME_preprocess_page, the menu data is also still structured here unlike in MYTHEME_preprocess_menu_tree.
I enabled the memcached example module, this enables the variables user_link and user_name in the preprocess. Then I created a third variable user_account just copying from the other two and altered the cookie so it stores uid not name.
This is because I wanted the "My Account" link to link to "user/x/edit" and I didn't need the name.
I then added the following chunk to my page preprocess.
function MYTHEME_preprocess_page (&$vars) {
  $user_account = $vars['user_account'];
    if (array_key_exists('menu-xxxx', $vars['secondary_menu'])) {
      $vars['secondary_menu']['menu-xxxx']['href'] = $user_account;
    }

The secondary menu in this case is my user menu and My Account is always labelled menu-xxxx in the array. (xxxx will be numbers).
Answer: In the context of a preprocess hook, yes:
function MYTHEME_preprocess_foo(&$vars) {
  $user_link = $vars['user_link'];
}

Outside of that context I guess you could invoke authcache_usercookie_preprocess() manually:
$vars = array('user' => $GLOBALS['user']);
authcache_usercookie_preprocess($vars, NULL);
$user_link = $vars['user_link'];

Comment: Cheers Clive. I'd been trying to use MYTHEME_preprocess_menu_tree which I couldn't get to work for some reason.
Comment: Hmm so in my arrogance I may have prematurely posted my answer. I thought changing the href in the MYTHEME_preprocess_page would change the rendered HTML, but it doesn't. I thought preprocess_page happened before theming? Am I missing something obvious?
Comment: Yes I was, I'd been outputting the menu as a block, as opposed to a variable from page.tpl.php. Apparently 4 months I couldn't get enough of blocks.


dropdown value can not get to next page using ajax

Question: Have a form ajax.php contains one dropdown and one textarea.One for employee name which is fetching from database.I need to display details of employee while changing the dropdown item.Here is my code

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

<?php
  $con=  mysqli_connect("localhost", "root", "", "process");
  if(!$con){
    echo 'not connected';
  }
?>
Assignee

<select name="emp" id="demo" class="form-control1">
<?php
  $sql=mysqli_query($con,"select * from employee");
  while($name=mysqli_fetch_array($sql)) {
?>
  <option value="<?php echo $name['id'];?>"><?php echo $name['empname'];?></option>
<?php } ?>
</select>

description <textarea id="desc"></textarea>
<input type="submit" name="sub" value="click" id="bt">

And my next page ie.display.php contains following code,
<?php

  $con=  mysqli_connect("localhost", "root", "", "process");
  if(!$con){
    echo 'not connected';
  }
  if( $_REQUEST["data"] ){
   $name = $_REQUEST['data'];
   $sql=mysqli_query($con,"select * from employee where id='$empname'");
   $name=mysqli_fetch_array($sql);
   echo $name['empname'];
 }

Comment: [How To Write Unmaintainable Code](https://www.thc.org/root/phun/unmaintain.html) -> Never Beautify: fulfilled
Comment: @Andreas Yeah, I only prettyfied the JS, not the PHP part
Answer: Issue is that you are passing data in empname and retriving using data change it:
display.php
<?php

$con=  mysqli_connect("localhost", "root", "", "process");
if(!$con){
    echo 'not connected';
}
if( $_REQUEST["empname"] ){ //change here

   $empname= $_REQUEST['empname'];//change here
   $sql=mysqli_query($con,"select * from employee where id='$empname'");
   $name=mysqli_fetch_array($sql);
   echo $name['empname'];
}

Comment: Wouldn't it be $_REQUEST["$empname"] ? Or  I'm just confused because he is passing $empname


M-M relationship in MVC and Entity Framework works only in debugger mode

Question: I am doing some project for school and have encountered a strange thing. Situation is like this:
In my SQL Server db I have 3 tables: Product, Ingredient and ProductIngredient. The last one is PJT between the first two.
I have this in a controller:
public ActionResult Index()
        {
            List<Product> products;
            using (FastfoodConnection conn = new FastfoodConnection())
            {
                products = conn.Products.ToList();

            }
            TestModel tM = new TestModel();
            tM.Products = products;
            return View(tM);
        }

and here is my view:

@foreach (var product in Model.Products)
{

         @product.Name
         @product.Description

        Ingredients

           @foreach (var ingredient in product.Ingredients)
           {

@ingredient.IngredientName

           }

}

Now - when I set the breakpoint in controller and debug the code, step by step, everything works fine and result shows as I want it to. However, when I try to run the code (without debugging) I get ObjectDisposedException with description "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection." Apparently this regards to
product.Ingredients list which is null.
My question is: What could be the problem and how can it be solved?
Answer: You need to eager load the Ingredients. EF won't try to fetch those from the database until you need them, which is called Lazy Loading. Because you try to access them after you disposed your context, EF can't query the database for the Ingredients and you get an exception.
Eager loading tells EF it should also fetch those entities in the same run when it gets the Products. It's always a good idea to use eager loading when you know beforehand you will need the entities. This avoids multiple db calls since everything gets fetched in one query. It can be invoked through the Include(...) method:
public ActionResult Index()
    {
        List<Product> products;
        using (FastfoodConnection conn = new FastfoodConnection())
        {
            products = conn.Products.Include(p => p.Ingredients).ToList();

        }
        TestModel tM = new TestModel();
        tM.Products = products;
        return View(tM);
    }

This should resolve your problem. Also make sure you have the collection of Ingredients marked as virtual in your product model, which enables lazy/eager loading, but since it works in debugging mode I guess that will be alright.
Comment: Apparently it was the problem, although it did not work with `products = conn.Products.Include(p => p.Ingredients).ToList();` I had to use    `products = conn.Products.Select(p=>p).Include(p => p.Ingredients).ToList();`  instead. Anyway - you solved my problem - thank you


Show $a_n=\Big(\frac{n^2+8n-1}{n^2-4n-5}\Big)^n$ converges to $e^{12}$

Question:
Show $$
a_n=\left(\frac{n^2+8n-1}{n^2-4n-5}\right)^n
$$
  converges to $e^{12}$

My progress:
$$
\frac{n^2+8n-1}{n^2-4n-5}=1+\frac{12n+4}{(n+1)(n-5)}
$$
Comment: $$ a_{n} =\left[ \left(1+\frac{12n+4}{(n+1)(n-5)}\right)^{\frac{(n+1)(n-5)}{12n+4}}\right]^{\frac{n(12n+4)}{(n+1)(n-5)}}$$
Comment: How does this help?
Comment: @SlavikEgorov If you are ok, you can set as solved. Thanks!
Answer: by asymptotic analysis
$$a_n = (b_n) ^n$$
$$b_n =\frac{n^2+8n-1}{n^2-4n-5}=1+\frac{12n+4}{(n+1)(n-5)}\sim 1+\frac{12}{n}$$
$$a_n \sim \left(1+\frac{12}{n}\right)^n \to e^{12}$$
or with little-o notation:
$$b_n = 1+\frac{12}{n}+o\left(\frac{1}{n}\right)$$
$$a_n=\left(1+\frac{12}{n}+o\left(\frac{1}{n}\right)\right)^n=e^{n\log {1+\frac{12}{n}+o\left(\frac{1}{n}\right)}}=e^{n \left({\frac{12}{n}+o\left(\frac{1}{n}\right)}\right)}=e^{12+o(1)}\to e^{12}$$
Comment: What do you mean by ~?
Comment: @SlavikEgorov it means asymptotic equivalent i.e.$$ \frac{b_n}{1+\frac{12}{n}}\to 1$$ https://en.wikipedia.org/wiki/Asymptotic_analysis


Finding the range of the given function

Question: I am to find the range of the function,
f(x)=1/√x-5
What I have done is:
f(x)=1/√x-5
=>  y=√x-5
=> x-5=1/y²
=> x=(1/y²)+5
In my book the solution is given as, Rf=(0,∞).
But shouldn't the range be R-{0} ?
Because y² ≠ 0 in the denominator, and hence y≠0.
Comment: [How to use MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: I assume you meant to write $f(x) = \frac{1}{\sqrt{x - 5}} \implies y = \frac{1}{\sqrt{x - 5}}$.
Answer: The answer from your book is correct. Note that $y=\frac1{\sqrt{x-5}}\implies y>0$. Therefore, $R_f\subset(0,\infty)$. In fact, $R_f=(0,\infty)$, because if $y\in(0,\infty)$ then\begin{align}y=f(x)&\iff y=\frac1{\sqrt{x-5}}\\&\iff y^2=\frac1{x-5}\text{ (since $y,\sqrt{x-5}\geqslant0$)}\\&\iff x=\frac1{y^2}+5.\end{align}
Comment: oops..I made a terrible mistake in my post, the function was actually f(x)=1/√x-5. Really sorry. I have corrected it now.
Comment: Then the answer from your book is correct. I will edit my answer.
Comment: It is done. What do you think now?
Comment: I see..but is it not true that y≠0 in the denominator, to prevent infinity from creeping in?
Comment: I don't understand your comment. Infinity is not a number and therefore it could not possibly creep in.
Comment: I mean to say that if y=0 in the denominator, then wouldn't 1/y result in infinity? And in that case, x will not be real anymore.
Comment: The number $y$ cannot be $0$ simply because the equation $\frac1{\sqrt{x-5}}=0$ has no solutions. And it has no solutions because if $x\leqslant5$, then $\frac1{\sqrt{x-5}}$ is meaningless and if $x>5$, then $\frac1{\sqrt{x-5}}>0$.

Finding the range of the given function


setTimeout() - what's going on in IE6?

Question: IE6 has got me again!  I can write
slideSuccess.show();

and all will be fine.  When I replace that very line with
setTimeout(function() { slideSuccess.show(); }, 1000);

then, after 1 sec, my slide shows up garbled.
(slideSuccess is a jQuery object if that matters.)
Does anyone have any ideas what is going on here?
Thanks.
Answer: Instead of using a setTimeout(), which won't queue the show until 1 second from now, put the timeout in the queue using .delay(), like this:
slideSuccess.delay(1000).show();

Otherwise you're not showing then animating, you're animating and running a .show() during it, whatever animation is executing in the queue...instead you can delay the queue from starting overall, with .delay().
Comment: Thanks.  You sure about this?  When I do this, the slide shows up instantly (bad) but well formed (good)...  And this happens in ALL browsers.
Comment: @Ollie2893 - Perhaps I misunderstood what your intended, what do you *want* to happen? You can do `.show('fast')` for example or `.fadeIn()` (with duration as well) if you want the show in the animation queue as well.
Comment: I do not want any effects - which is also the reason the delay() does not work.  Delay() only works in jQuerry effect queues.  I simply want the slide to show after a set interval.  That's all.  The setTimeout code works in all browsers bar IE.  What do I need to do to the code so that IE falls in line?
Comment: @Ollie2893 - What other animations are you running? Where are they kicked off?  You need to start those after the show, as a callback to the show for example then you can use `setTimeout()` as well.  You can also do the hacky-ish `.show(1)` to queue a 1 frame show animation.
Comment: No other animations at all.  This is test code.  It consists of little more than the one line that I quoted.  Obviously there's some code to create the slides but that code works in IE too - just so long as I call it outside the timeout handler.  The question specifically relates to the difference in environments between a call outside and inside a timeout handler.  There's clearly something that I need to do to help IE.  But what?
Comment: @Ollie2893 - Where's the code creating the slides?  It has to be doing *something* to mess up the slides, probably a race condition.
Comment: There's no race condition since there's only a single line.  I have totally reskinned the plugin I am writing on and the problem's still there.  In fact, I am writing this stuff to deal with AJAX submissions where a slide "Saving..." will (hopefully) be superceeded by a slide "Success" when the AJAX calls finishes successfully.  I dropped the code into the app and I get the exact same misbehaviour in IE in the AJAX callback as I get in the timeout() callback.  It seems that it struggles in every event handler.
Comment: The problem may not be the event handlers but the composition of the slides.  Specifically, they comprise some text and an IMG.  The slides collapse because the IMG does not show.  I have run repeated tests in my rig and every so often, I get a good slide (including the icon).  The images are GIF and PNG and should be in cache in the real app - yet in the real app I have never so far managed to get a good image.  It's still odd that this only becomes a problem when inside event handling code...
Comment: To clarify, the slides are all pre-loaded.  I am not assigning the SRC attribute inside the event handler.  I am merely giving .show() on the DIV that comprises the slide.
Comment: Ok - just confirmed that it is definitely an IMG pre-loading problem of some kind.  When I open one of these slides before any event handling occurs, then the slides displays correctly AND all the event handlers will subsequently also display the slide correctly.  I may have to restate my question...
Comment: The problem may be that I am giving .hide() before the pre-load has completed, somehow aborting that loading which is then subsequently presumed to have occurred.  Strange...

setTimeout() - what's going on in IE6?


How do I invoke web services?

Question: I am working on a site, and I want to integrate my site with an external site; for that, I need to use web services to get data from the external server. I don't know the technology used by the server.
I have to work as client. Can any one please tell me hoe to call web services from my site? Please write any code if it is required. Will drupal_http_request() help me?
I am using Drupal 6.
Answer: You should have a look at the Services module. You can use XMLRPC and/or REST server (and many more) to communicate with your remote server. Link to the documentation.

A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.
Comment: I had gone through services module, But I dont know how to use that for my purpose. Services module is used if we want to act as server, Am I right?
Comment: yes, you're right. But, that is not only what services can do. You can watch [services inside out](http://denver2012.drupal.org/program/sessions/services-inside-and-out).
Comment: Thankyou for sharing the link of video BTW I had seen it already. But still dont know what to do. Can you please tell me it step by step.
Answer: The Alternate solution is Views . Install Views module and Json document Views module. With this you can get data from your site in many ways. Have a try

How do I invoke web services?


Why do these two methods of calculating the probability of winning a best-of-7 series give the same answer?

Question: I was having a discussion with a friend about the probability, and we came up with very different methods to solve it that lead to the same answer. The problem is pretty simple: you have two teams A and B playing a best of 7 series where wins are independent and the probability that team B wins is .35. What's the probability of team B winning th series? Friend says, "this is just a binomal random variable $X$ with $n=7$ and $p=.35$ and we are looking for $P(X\geq 4)$, which according to my TI-83 here is .1998".
I was rather convinced that this must be wrong. If we think of the series as a sequence of A's and B's, then we are looking for the probability of obtaining a sequence of length $n=4,5,6,7$ with 4 B's and the last element is a B. I was sure that his method will include the probability of obtaining, say, {B,A,B,B,B,A,A}, which we are not interested in and in fact couldn't even ever occur. So I figure that what we really want for a sequence of length $n$ is the probability of obtaining a sequence of length $n-1$ with exactly 3 B's, and then tacking a B onto the end. So for a sequence of length $n$, the probability should be $\binom{n-1}{3}.35^4 .65 ^{n-4}$, and then the answer should be $\sum_{n=4}^{7}\binom{n-1}{3}.35^4 .65 ^{n-4}$. I was confident that I was right and he was wrong, but then I plugged that into Wolfram Alpha and got... .1998.
What's going on here? Is it a coincidence?
Comment: Once team B wins 4 games the series is over.
Comment: To make more money, the league has decided that the series will go $7$ games, but the usual rules for determining the winner (first to win $4$) apply. Then Team B wins the modified series iff it wins the real series.
Comment: Why do you say that {B,A,B,B,B,A,A} could not ever occur? This looks like a valid sequence of wins to me...
Comment: See David Spencer's answer below.
Answer: He is correct. Although this does include series that would be over after fewer than $7$ games "in real life", they would still all result in team B winning, no matter what happens after team B gets $4$ wins.
In your example, the probability that one of
{B,A,B,B,B,A,A}
{B,A,B,B,B,A,B}
{B,A,B,B,B,B,A}
{B,A,B,B,B,B,B}
happening without terminating series after four wins is equivalent to the probability of
{B,A,B,B,B} happening across the first five games because later events do not affect anything.
Answer: This is not a coincidence, you are looking at the same problem in two different ways. The situation {B,A,B,B,B,A,A} is irrelevant in your friend's argument, because you are not counting the number of different possible sequences of events.
Rather, you are attempting to estimate the probability of at least $n$ successes in $k$ trials, which is exactly what the binomial distribution does.
In your second approach, you are essentially estimating the number of possible legal sequences terminating in a victory condition, and then computing the total fraction out of all possible sequences.
Both approaches are equivalent. One is a little easier to implement ;)


Why can't Google Tag Manager be installed within another HTML element under the body?

Question: The instructions for Google Tag Manager insists installing Google Tag Manager code immediately after the opening body tag. However, this is not always possible for some websites (without a ton of modification).
Trouble is, you can install Google Tag Manager elsewhere within a page and the tags appear to fire. However, if you check the installation with Google Tag Assistant, it fires a critical issue:

"Error:  tag must not be included in a
"

When you click on the error message, you're directed to Google's lean documentation
:

Google Tag Manager Tag should be placed immediately after the opening  tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.
  Tags added via Google Tag Manager may not fire.
  Please make sure to place the GTM snippet immediately after the opening  tag.

Which sorts of tags won't fire?
Is it only for certain browsers?
Will it cause other issues?
Answer: This guideline is trying to help avoid some specific problems with using appendChild on unclosed ancestor elements in older versions of IE:
http://support.microsoft.com/kb/927917 (archive)
http://blogs.msdn.com/b/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx (archive)
You can avoid these problems by always placing your GTM snippet directly inside the body tag, not wrapped in any other elements (e.g.
 or ).
Answer: For practical purposes we need to dig deeper to have the instruction easier to implement.
Firstly to differentiate between the  block and the  block components in the GTM Snippet
For a particular client I'm seeing their IE 6 & 7 traffic to be insignificant and dropping.
We therefore need not take those browser versions into account
Also their site is near impossible to use without JavaScript.
For other clients, their GTM container may have no tags that will function without JavaScript.
In such cases it seems quite safe to dispense with the  block and implement the bootstrap code in the .
While I've done this on occasion and got desired results, I will not claim to have tested it thoroughly.
We would benefit greatly from Brian or other GTM team members providing more in depth information on this problem


How to give permission for a role for editing help text for fields of custom types?

Question: I want role "RoleFoo" to have only the permission to edit the Help Text of all fields of  specific content types (contentypefoo1 and contentypefoo2).
How to do this?
Answer: The Field help helper module seems to be a good fit for this. some more details about it (from its project page, which is also here the image originates from):

The Field help helper module adds a link to entity configurable fields so that users with the appropriate permissions may easily edit the help text and label for a field in context of where the field displays.
Once a user's role is given the Edit field help text permission any user with that permission will be able to edit the help text or label of a configurable field without having access to administer fields.

Extra bonus: comes wth an official release for both D7 and D8 ...
Comment: Please verify the edited version of your answer. Feel free to rollback or to further enhance it (and check the revision noticed I added to explain the reason for my edit ...). Apart from that: +1 !


variance of minimum of squared exponential random variable

Question: Given $Y_1 $ to $Y_n$  are  exponential r.v's with mean $\theta$ find $\operatorname{var}[\min(Y^2 )]$ with the help of gamma distribution.
attempt:
$\min(Y) $ is exponential with $(\text{mean} = \theta/n)$
i know that sum of $n$ exponentials is gamma with $\alpha = n$ and $\beta = \text{mean}$
The squared of $Y$ is throwing me off. Thanks for help
Comment: to clarify Im trying to solve in a way that does not involve computing the 4th raw moment.
Answer: Hints;

For every nonnegative random variable $Z$,
$$
E(Z)=\int_0^\infty P(Z\geqslant z)\,\mathrm dz,\qquad E(Z^2)=\int_0^\infty 2z\,P(Z\geqslant z)\,\mathrm dz.
$$
For every independent random variables $(Z_k)_{1\leqslant k\leqslant n}$, the random variable $Z=\min\{Z_k\mid1\leqslant k\leqslant n\}$ is such that, for every $z$,
$$
[Z\geqslant z]=\bigcap_{k=1}^n[Z_k\geqslant z],
$$
hence, if furthermore the random variables $(Z_k)_{1\leqslant k\leqslant n}$ are identically distributed,
$$
P(Z\geqslant z)=P(Z_1\geqslant z)^n.
$$
For every nonnegative random variable $Y$ and every nonnegative $z$,
$$
[Y^2\geqslant z]=[Y\geqslant\sqrt{z}].
$$
If $Y$ is exponential with mean $\theta$, then, for every nonnegative $y$,
$$
P(Y\geqslant y)=\mathrm e^{-y/\theta}.
$$

Applying these facts to $Z=\min\{Y^2_k\mid1\leqslant k\leqslant n\}$ with $(Y_k)_{1\leqslant k\leqslant n}$ i.i.d. exponential with mean $\theta$, one gets for example
$$
E(Z^2)=\int_0^\infty 2z\,\mathrm e^{-n\sqrt{z}/\theta}\,\mathrm dz.
$$
The change of variable $z=\theta^2t^2/n^2$ yields
$$
E(Z^2)=\frac{4\theta^4}{n^4}\int_0^\infty t^3\,\mathrm e^{-t}\,\mathrm dt=\frac{24\theta^4}{n^4}.
$$


Left/right positioning takes border size into account

Question: My goal is to be able to dynamically position a DIV so that it is visually precisely underneath it's parent - i.e. so that it is the same width as it's parent, and begins 0 pixels from the bottom of the parent's left border.
Essentially, the end result should be something like this:
http://jsfiddle.net/cvz3gvbs/
Here I simply use a relatively positioned parent DIV, and an absolutely positioned child DIV.  I then simply use the left and top positioning attributes to move the child DIV into place.
However, you'll notice in that fiddle that in order to make this happen, I had to set left: -10px on the child DIV.  The reason is that if I don't, this happens:
http://jsfiddle.net/cvz3gvbs/1/
Here, the child DIV is not directly centered underneath the parent.  The reason seems to be that the left and right position values take into account the border of the parent, so that left: 0px means positioned directly to the right of where the parent border ends.
So I have to compensate for this with a negative left value.  That's fine, except if I want to be able to do this dynamically with Javascript, I might not know in advance the thickness of the parent border - (or even if the parent even has a border).  So I can't simply hardcode a negative pixel value in the style sheet.  I'd have to use Javascript to dynamically query the computed styles of the parent element and determine the border width of the parent, which is a bit cumbersome.
Question: Is there some way to do this without using Javascript to discover the border width?
I thought this might have something to do with the W3C box model, since left was taking into account the border of the parent.  So, I tried using the box-sizing: border-box property so that the browser would include the border-width in the box size - but this had no effect.  A left value of 0px still means positioned directly to the right of the parent element's border.
Comment: No, `box-sizing` will not fix this issue; the reference points for absolute positioning are determined by the _containing block_ of the element, and that includes padding and borders of the relative positioned parent element. But depending on what you are actually trying to achieve here there might be other ways to solve this, but this minimal example leaves that quite ambiguous – so an example closer to what the actual end result and behavior is supposed to be might be helpful.
Comment: Using a proper `reset css`(or for this example setting `html` and `body` padding to 0) and placing the containers next to each other [works just fine](http://jsfiddle.net/cvz3gvbs/2/). Styling containers to exceed their parent is btw. always a bad idea (except when using `overflow:hidden/scroll` on the parent).
Comment: Possibly adding moz-box-sizing: border-box; for mozilla might resolve the issue, since the box-sizing is what you're looking for as far as I can tell.
Comment: I'm using chrome, so I don't think it's a mozilla problem
Answer: Is it a necessisty that .bar be inside .foo? You could make them siblings and wrap them in a container set to relative like so. You don't even need to set the width on each of them, just on their parent:
HTML

CSS
.container{
  width: 200px;
  position: relative;
}

.foo {
  border: 10px solid #000000;
  height: 45px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
}

.bar {
  box-sizing: border-box;
  position: absolute;
  top: 35px;
  left: 0;
  right: 0;
  border: 1px solid #000000;
  height: 500px;
}

FIDDLE
Answer: You should add them in a container like this example

http://jsfiddle.net/cvz3gvbs/6/
and you can remove the position of the class bar


output jsonArray on php side, and decode on android

Question: I have this php code:
if ($merchant_rows > 0){
    while($r=mysql_fetch_array($get_merchant)){
        $merchant_id = $r['merchant_id'];
    }

$sql = "SELECT quest_id, quest_title, quest_price, quest_points FROM quests WHERE merchant_id = '$merchant_id'";
$number = mysql_query($sql);
$rows = mysql_num_rows($number);

if ($rows > 0){
    while($result=mysql_fetch_array($number)){
        print(json_encode($result));
    }
}

and on the android side, after making an http post:
String res=response.toString();
jObject = new JSONObject(res);
                    JSONArray sessions = jObject.getJSONArray(res);
                for (int i = 0; i < sessions.length(); i++) {
                JSONObject session = sessions.getJSONObject(i);
                Quests quest = new Quests();
                quest.quest_id = session.getString("quest_id");
                quest.title = session.getString("quest_title");
                String price = session.getString("quest_price");
                quest.dollar_price = "$"+price;
                String points = session.getString("quest_points");
                quest.pts = points + "pts";
                quests.add(quest);  }

My problem is that im trying to "getJSONArray" but I believe I'm not outputting the json as an array on the php side?
Answer: use
    mysql_fetch_array($result, MYSQL_ASSOC)
or
    mysql_fetch_assoc()
when retrieve from assoiative keys else retrive from numeric keys..
if ($merchant_rows > 0){
    while($r=mysql_fetch_assoc($get_merchant)){
    $merchant_id = $r['merchant_id'];
}

$sql = "SELECT quest_id, quest_title, quest_price, quest_points FROM quests WHERE
merchant_id = '".$merchant_id."'";
$number = mysql_query($sql);
$rows = mysql_num_rows($number);
$values = array();
if ($rows > 0){
    while($result=mysql_fetch_assoc($number)){
        array_push($values,  $result);}}

print json_encode($values);

Comment: I want to output this array as "results"...so {"results": {}}


Sql query solution needed

Question: I have a table in the following format
ID    class       indicator
1      A              Y
1      B              N
1      C(recent)      N
2      X              N
2      K(recent)      N

if a particular ID has its recent class indicator as N then search if it was Y somewhere before that recent entry if yes then answer should be that class if not then the recent entry is the answer.
Example: for ID 1 the recent entry was C but we got a Y at A also so we have to return A but in ID 2, K is the recent entry and we don't have any Y indicator before that so we should return Y.
Comment: A solution is "needed" but what have you discovered or attempted? What efforts have you made?
Comment: I think rather than finding a sql solution for this, you should seriously consider modifying that data structure, because it's not a good one. You should not be including "recent" in the class column. You should be using some date column or some other identifier in a different column.
Answer: One approach is to sort the entries for each ID according to this logic, assign a number to each with row_number() and take just the first:
SELECT id, class, indicator
FROM   (SELECT id, class, indicator,
               ROW_NUMBER() OVER (PARTITION BY id
                                  ORDER BY indicator DESC,
                                           CASE WHEN class LIKE '%(recent)'  THEN 0
                                                                             ELSE 1
                                           END ASC) AS rn
        FROM mytable) t
WHERE   rn = 1

Comment: why did you not mention that in your question ? You have us all look for something else than what you want now
Comment: if i add dates instead of class then how should i proceed?
Comment: @NewBie I don't understand this question. Can you perhaps clarify with an example?
Answer: in your comment with Mureinik's answer you mention you want to use a datetime column in stead of recentin the class column.
One way to do this is like below, but this will not perform great if you have really many records
your table would look sometimes like this in that case :
ID  Class   Indicator   IndicatorDate
--  -----   ---------   -------------
1   A       Y           31/03/2018 12:59:18
1   B       N            1/04/2018 12:59:18
1   C       N            3/04/2018 12:59:18
2   X       N            3/04/2018 12:59:18
2   K       N            2/04/2018 12:59:18

and a possible solution would be this
declare @table table (ID int, Class varchar(1), Indicator varchar(1), IndicatorDate datetime)

insert into @Table(ID, Class, Indicator, IndicatorDate)
values (1, 'A', 'Y', getdate() - 3), (1, 'B', 'N', getdate() - 2), (1,  'C', 'N', getdate()), (2, 'X', 'N', getdate()), (2, 'K', 'N', getdate() - 1)

select td.ID,
       (select top 1 t2.Class from @table t2 where t2.ID = td.ID order by t2.Indicator desc, t2.IndicatorDate desc) as selectedClass,
       (select top 1 t2.Indicator from @table t2 where t2.ID = td.ID order by t2.Indicator desc, t2.IndicatorDate desc) as selectedIndicator
from
(  select distinct t.ID
   from   @table t
) td

which would return this
ID  selectedClass   selectedIndicator
--  -------------   -----------------
1   A               Y
2   X               N

HOWEVER:
This depends on if the endresult of this query is really what you are looking for, its still not entirely clear to me

Sql query solution needed


How to update table using rank function

Question: create table test(
e_id NUMBER(10),
code NUMBER(10),
active NUMBER(1)
);

INSERT INTO test VALUES(11,0,NULL);
INSERT INTO test VALUES(11,0,NULL);
INSERT INTO test VALUES(11,3,NULL);
INSERT INTO test VALUES(12,1,NULL);
INSERT INTO test VALUES(12,3,NULL);
INSERT INTO test VALUES(12,4,NULL);

DB version: Oracle 18c

I need to find the minimum  code from the table  test grouping e_id. If we have same values after finding the minimum one then need to update the  active column to 1. Basically, need to find out the minimum  code value and update the first record to 1 in active column.
My attempt:
SELECT e_id, code, rnk FROM (
SELECT t.*,
RANK() OVER (PARTITION BY e_id ORDER BY code ASC) AS rnk
FROM test t
);

This will give me the rank of the rows and if I filter based rnk=1 then will give the result but how to update the table in this scenario?
Expected output:
+------+------+--------+--+
| E_ID | CODE | ACTIVE |  |
+------+------+--------+--+
|   11 |    0 | 1      |  |
|   11 |    0 | NULL   |  |
|   11 |    3 | NULL   |  |
|   12 |    1 | 1      |  |
|   12 |    3 | NULL   |  |
|   12 |    4 | NULL   |  |
+------+------+--------+--+

Answer: Here's one option; row_number is better in this case because rank will "mark" all duplicate rows with 1, but you need only one.
Before:
SQL> select * from test order by e_id, code;

      E_ID       CODE     ACTIVE
---------- ---------- ----------
        11          0
        11          0
        11          3
        12          1
        12          3
        12          4

6 rows selected.

Update (actually, merge):
SQL> merge into test a
  2    using (select s.rid
  3           from (select rowid rid,
  4                        row_number() over (partition by t.e_id order by t.code) rnk
  5                 from test t
  6                ) s
  7           where s.rnk = 1
  8          ) x
  9    on (x.rid = a.rowid)
 10  when matched then update set
 11    a.active = 1;

2 rows merged.

After:
SQL> select * from test order by e_id, code;

      E_ID       CODE     ACTIVE
---------- ---------- ----------
        11          0          1
        11          0
        11          3
        12          1          1
        12          3
        12          4

6 rows selected.

SQL>

Comment: ROWID is here so that you'd know which row to update (as there's no unique identifier in the table). RANK returns "duplicates" - in your example, the first two rows for E_ID = 11, whose CODE = 0, would have RANK = 1 but you want to update only one. So, you'd then have to choose which one of these to update, and that's some more coding you don't really want - ROW_NUMBER - in this case - is a better option.
Comment: Thanks for this. Could you please let me know why we have used rowid and row number? Can't we achieve this using rank function?

How to update table using rank function


Objects as default values in c++

Question: is there a way to have a default Object for parameters in C++ functions? I tried
void func(SomeClass param = new SomeClass(4));

and it worked. However how would I am I supposed to know wheter I have to free the allocated memory in the end? I would like to do the same without pointers, just an Object on the stack. is that possible?
Comment: I don't see any explicit pointer here
Comment: @CashCow or worse, a `SomeClass( void * )` There's a train-wreck waiting to happen.
Comment: to avoid pointers, memory allocation and so on, you can use this: `void func(SomeClass param = SomeClass(4));`. Your function will receive SomeClass object by value and will destroy it automatically after the function call
Comment: Does SomeClass have an implicit constructor from SomeClass* ?
Comment: how does it worked ? `new SomeClass(4)` returning a pointer to SomeClass while the function expect an instance. but without the `new` there is no problem. +1 since I never thought of trying this before.
Comment: This code generally does not work. A full working example would have been better.
Comment: Guys thank you ;) I habe a lot to learn, I know :-)
Answer: void func(SomeClass param = new SomeClass(4));

This can't work because new returns a pointer
void func(SomeClass param = SomeClass(4));

should work and the object doesn't need to be freed.
Comment: It can work if `SomeClass` has a constructor that takes `SomeClass*`. I admit that is unlikely, and I use the word "work" very loosely.
Comment: @BenjaminLindley: Nice addition, a bit scary.
Answer: You almost had it but you don't need the new keyword.
void func(SomeClass param = SomeClass(4));

This method has the advantage over using new in that it will be automatically deleted at the end of a call so no memory management is needed.
An alternative is to use shared pointers.
Answer: You could use overloading:
void func(const SomeClass&) const;
void func() const {
  SomeClass* param = new SomeClass(4);
  func(param);
  delete param;
}

Comment: At least use pointers and delete afterwards, if you want this approach
Comment: `SomeClass param = new SomeClass(4);` does not work as `new` returns a pointer.

Objects as default values in c++