Electric guitar effects and amplification

Question: I want to upgrade my sound. I have two medium combo amps for my electric guitar.
I saw that there is a "combined" way to get the most out of a guitar - multi effects processors like the Axe-FX and BOSS ME. But I don't know a lot about how to setup a correct signal chain, for example I don't understand why I can't use my home stereo and speakers.
Can someone clarify things a bit for me? What is the correct way to setup a guitar signal chain?
Also, is a multi effects processor a good investment for a beginner? (I want a more "brutal" sound out of my guitar).
Answer: Who told you you can't use you home PA? Sure enough, if you just plug the guitar right in a PA, it'll sound somewhat boring, but there's no reason you could not do it anyway. In fact, such a "super-clean" sound can IMO sometimes be a pleasant alternative.
The thing is, guitar amps aren't designed to sound "good" in a HiFi sense, at all. On the contrary, they have both circuitry with strong nonlinear properties, and speakers that have a very uneven response. Depending on the details, both together form what we know as either "classic-warm", or "modern-brutal" sounds (or something in between).
With a multi-FX processor, those properties are simulated digitally. If you then plug the output into a guitar amp, you'll actually get double processing – that's normally not really desirable. So with such an FX processor, it makes in fact a lot of sense to just go directly into a PA, rather than a guitar amp. (As Matt L. remarks, digital multiprocessors usually allow you to turn off the amp&cab simulation, but that really only makes sense if you like the amp's sound as it is without extra effects.)
As to whether a multi-FX processor is a good investment – that depends strongly on what you hope to do with it. If you really say "I just want to have some fun with brutal sounds" then, yes, a digital processor is probably the most effective way to get there.
If you actually plan to play in a band, and are serious about learning guitar, then I would tend to recommend you stick with a simple analogue guitar amp. That makes it harder to get an "impressive" sound, but at least you'll properly hear what you're doing on the guitar, and you'll have an actual speaker to make it audible over a drum set (with a badly set up digital FX into a PA, you'll more likely end up with some unidentifiable muddy noise disaster).
Comment: Use a simple 1/4" instrument cable from the guitar to the FX processor, and then a pair of such cables from the processor to the PA.
Comment: If you mean a consumer stereo system (I wouldn't really call that a PA) then it'll probably have only [RCA](https://en.wikipedia.org/wiki/RCA_connector) inputs. But, yes, you can still use those, get a twin 1/4" to RCA cable, plug it into the stereo line-out of the FX processor and the AUX in of the stereo system (or whatever it's called).
Comment: A comment to your last paragraph to avoid misunderstandings: this is true if you use an amp and cab simulation in your multi-FX unit, which is usually optional. You can use a multi-effects processor just as a collection of effects (pretty much like individual pedals) in combination with a guitar amp, and there will not be any double processing. This is a very common usage of a multi-FX processor, and many of them are designed to be used in this way.
Comment: @MattL.: right, but then you need to start with a _good_ guitar amp for the "basic sound".
Comment: I'm still confused about what is the correct way to connect a device like AXE-FX or Digitech GSP. What is the most straightforward way of connecting a guitar to a multi-fx processor, what do I need to buy?
Comment: Can I use the home PA with home speakers?
Comment: @leftaroundabout while I love the simplicity of a decent guitar through a good amp, some amps aren't all that flexible when it comes to the driven sounds they can achieve - a decent clean amp and a flexible multi-FX can be a more versatile recipe. But I also agree that it's nice to have your amp onstage beside you to double as a stage monitor.
Comment: @topomorto: yes, of course simple analogue amps aren't very flexible in their range of overdriven sounds. But the point I was making is basically: too much sound-flexibility is not necessarily _helpful_ for a beginner to have – in fact it tends to distract from the playing itself, and from developing the technique necessary to get a good and versatile/dynamic sound out of the guitar itself, to start with. That's just a personal opinion of mine: all guitarists I really like are able to get a good sound even with the most minimalistic amp setup (or with an acoustic guitar).
Comment: @leftaroundabout definitely a valid point, though (again personally) I've found that having a rig that can't achieve the sound I want can be a different kind of distraction This proves your point as I'm not the kind of guitarist that can excel with a simple set-up, but I do think that being able to make gain stages and effects sing can be as valid a skill as getting the music just from wood and steel .
Answer: The guitar amps you have most likely have some "effects" on them already.  Most guitar amps allow you to select either a clean signal or a distorted overdrive signal (at living room levels).  Also, many have built in reverb or delays or other effects that can be selected.
But eventually, most guitar players end up wanting a sound they just can't get out of their amp.  So they buy a "stomp box" or pedal to add a different effect.  You can get individual boxes (aka pedals) to add things such as tremolo, chorus, delay, octaves, volume boost, fuzz and many others.
Many performing guitarist will connect several of these pedals together with short cables (chaining one to the other) and attach them to what they call a "pedal board".  Sometimes you can use more than one effect at the same time.
With a pedal board loaded with multiple effects pedals, you would plug your guitar into the first one and the signal would go through each of the other boxes in the chain and a different instrument cable will run from the last box in the chain into the guitar amplifier.
If you want to use many different effects to play at home for yourself and your friends, a multi-effects processor may be the more economical way to go.  There are many such processors on the market and for home use, you could use either a rack mount processor such as the Fractal Audio AXE FX (expensive) or a pedal/foot-switch controlled unit such as the Boss ME.
A digital multi-effects processor will allow you to plug your guitar into the unit and then run a cable from the processor to a PA (public address) system and whatever effects you select (overdrive, reverb, flanger etc.) will come through the PA speakers.  Many of these processing units should be capable of allowing you to play your guitar through your home stereo as well but I would check with tech support from the manufacturer if it is not clear from the owners manual what type of signal the unit sends.
The disadvantage of many multi-effects processors, is that to get to a certain effect, you must bank up or down (tap the up or down button or turn a knob to scroll through a menu on a tiny screen) to find the effect you want.  With a pedal board that consist of multiple single effects pedals, you just stomp the one you want and get it when you want it without scrolling through all the selections.
The biggest advantage of a multi-effects processor, is that you might get 30 or more different select-able effects. Also, many of these units offer amp cabinet emulation to make your guitar sound like you are playing through a 1965 Fender Twin Reverb or a Blues Junior or a Mesa Boogie guitar amp - only the sound is coming out of your PA speakers.
You can plug these multi effects processors into your guitar amp using a standard instrument cable and you should get excellent results.  Use your clean channel setting and play around with the EQ controls on your amp and the adjustable parameters on the effects processor to tweak the sound the way you like it.  Most units allow you to save your adjustments as a preset and then call up the preset on the menu later.
You can also plug the multi effects processor into your PA system and many of them allow you to send the signal to both a mixer to run into your PA as well as a guitar amp at the same time.
One thing that you might find extremely useful for what you want to do, is the new iRig Stomp iRig Stomp multi effects pedal  This processor is a stage ready stompbox multi effects guitar interface that works with iPod, iPhone, or iPad and most iOS guitar apps including the popular AmpliTube App.  It is inexpensive, has good reviews, and you can plug it into your guitar amp, a PA OR even your home stereo.  You might need to buy an iPod to go with it if you don't have an iPhone or iPad.
To plug the iRig Stomp into your stereo, you need a cable like the dual quarter inch L/R to dual RCA L/R pictured below. Plug the 1/4 inch plugs into the left and right output on the pedal and the RCA left and right jacks into your auxiliary input jacks on your home stereo.   Hope this helps and good luck.
Answer: You can use a stereo and speakers. The reasons people tend to use instrument amps for practice is because they are (hopefully) built to cope with an uncompressed/unEQ'd instrument signal, which will have more big level spikes at particular frequencies, in contrast to recorded music which tends to be more smoothed out (making it more obvious when you're driving the speakers way too hard), and because often the speaker has a band-limiting effect which works well with the instrument in question. (And also because you can use the same amp to play live!).
If you are emulating the amp sound using a digital processor, you can plug into a full-range monitoring system such as your home stereo, but you may also find it works well through instrument amps (with the amps set to 'clean' settings).
The general opinion is that the latest multi-fx are a good investment but you might want to canvas opinion on some sites specific to your instrument (e.g. thegearpage)  explaining exactly what you want.
Comment: @acerbus "Full range monitoring system" means any system designed to cover the full audio frequency range (like your home stereo) instead of just the limited bandwidth for a certain instrument (such as your guitar amps).  Home stereo  is optimized to play recording of the entire band to include the bass, guitar, vocals all the way up to the cymbals on the drum.
Comment: You mentioned a "full-range monitoring system", do you mean FRFR speakers? So I can use a home PA system but I need to use FR speakers with it? (are guitar cabs/speakers needed?)
Comment: As with the other comment thread i'm a bit confused what you mean by 'Home PA' - PA is public address, so by definition not really a home system.
Answer: I would say there is no right or wrong way, its just what you are trying to achieve.
Some ways, eg using the AXE-FX2 would be complex, but there are other easier ways.
For example, steve vai uses a boss chorus pedal which has a stereo output, and passes one digital delay pedal and one amp etc in both of the outputs. He gives different delay times in the two lines and combined with the chorus this give a unique sound.
Another idea might be to split the signal and pass it through the two different chains of effects, EQs and amps giving you a stereo sound where each side is uniquely different.
And when switching to solos you could add a slight msec delay between channels giving it a chorus effect.
For these you dont need anything too expensive. I would say keep your money and dont buy anything extremely expensive like an AXE-FX2 until you are sure you need it.
Cheers!
Answer: This tech video might help, you:
Comment: Could you summarize the video contents?
Answer: Running a guitar through an effect processor and a home stereo is unlikely to make you overly happy.
Particularly guitar with overdrive has high frequency content way above what a home stereo is built to deal with.  It may be defused somewhat by an amp simulator and room acoustic simulator, but then the results will lean towards the mushy.
Driving a home stereo with the same signal you would feed in a normal amp will smoke your tweeters pretty fast, at volume levels you consider surprisingly low.
Basically, you can expect to get more volume out of a 5W guitar amplifier than out of a 50W home stereo if you value your tweeters.  And of course, the typical "1200W music power" (rating for spontaneous combustion) setup will blow out quite earlier.
Comment: Ahem. So you're arguing that any music with electric guitars can not be listened to over a home stereo? — What's correct is: if you apply _power stage overdrive_ to a home stereo amplifier, it would likely not end well for the tweeters, perhaps even overheat the woofers and/or circuitry, and definitely sound horrible. But, you'd probably have to mod the amp circuit to even get there: modern amplifiers, at least professional ones, should have a limiter built-in, precisely because power-amp overload is so disastrous. OTOH, unfiltered preamp distortion sounds not _nice_, but it's pretty harmless.
Comment: user19186 - this is actually incorrect in so many ways. 1st - there is **no** high frequency content from a guitar that you can't listen to on your stereo. This is why you can listen to your favourite heavy metal bands **on your stereo** 2nd - a 50W home stereo is an awful lot louder than a 5W guitar amp. It may not sound as good for guitar (unless you have an amp sim) but it is much louder.
Comment: Is there not some truth in the idea that a 5W-rated amp could be usable at a louder volume than another amp with a much higher rated power? I've read that some amps - e.g. valve amps - can pump out a lot more than their rating (which will have been given at a certain nominal % total harmonic distortion) without sounding subjectively nasty, at least when fed with a certain type of signal...


Using Javassist to modify code in other packages?

Question: Is there a way to write a javassist program in a package other than the src folder that can modify other classes (either in the src folder or subfolders of the src folder).  I have messed around with cp.addPath("/usr/local/javalib"); and I cannot get that to work. I do not know if that is because I am not using it properly, or if that isn't even an appropriate approach to modifying java files in other packages.
Any input would be greatly appreciated. Thanks!
Answer: I was making this much more difficult than was needed. If I want to grab a class object in another package, say for example I wanted to modify a "foo.java" class in a "stuff" package. I simply use: pool.get(stuff.foo);
That's it, now I have the foo class in the classpool.


How to use NSUndoManager with a UIImageView or CGContext

Question: I have an app that uses cgcontext to draw things onto a UIImageView that the user draws using touch events, and I want to be able to undo the drawings made by the user.
Edit:

I am trying to use my touchesBegan to save theUIImage at the begining of a touch to the NSUndoManager

And then how do I use it to undo using a UIAlertView.
Meaning, I want to call a method from my UIAlertView that undo's then another that will redo, but I don't know how to accomplish this.
Please help
Answer: I write graphics software for the iPhone (http://www.layersforiphone.com/) and I spent a while trying to figure this out. The problem is, CGContexts aren't inherently "undoable." You can't unfill a rectangle or restore a portion you've drawn over. The data just isn't there. In my experience, the best bet is to create a "save" method that looks at the region being altered and saves the image data in that region to the undo stack before drawing operations are performed. Then, when you decide to undo, you can take the modified region and restore it from your saved data.
I chose to implement that approach independently of NSUndoManager in Layers because you basically need a stack of CGImageRefs and CGRects and it doesn't map well to the NSUndoManager.
Note: Technically, you could just save a copy of the entire image each time it is modified. This is a bad use of memory, though - since you may change only a small area. If you want to have a generous undo history (10+ steps), it's definitely worth your while to save and restore small subimages within your drawing space.
Hope that helps! I know it's not a great solution - you really can't do much with the built-in APIs. If you create a general solution to this problem I think a lot of people would be interested in it, though!
Comment: Well first of all if you deal with this stuff all the time then can you help me with this question: http://stackoverflow.com/questions/1943325/how-do-i-stroke-a-cgcontext-path-with-multiple-random-images, and also, all I want to do is save the Image of what I am drawing m CGContext to
Comment: @Ben : i have been making drawing application and undo/redo feature is driving me crazy.. as you wrote :"you could just save a copy of the entire image each time it is modified.." Would you please tell how  and where to store these images?? I can think of two options to save images for temporary purpose : 1) Using buffer 2) SqlLite database.
I do not know how to save image using buffer and i'm going to try second option..

If you could guide me how to save files i will appreciate your help..
Comment: Hi @Ben: I am working with a drawing project, I have an issue with eraser, can you please have a look at this link and suggest me something http://stackoverflow.com/questions/11502320/eraser-not-working-in-ios-drawing
Comment: No wonder i cant make it work with NSUndoManager. Guess back to saving the individual images in tmp folders undo1.png, undo2.png.. etc. Thanks


what does $f '(x^2)$ mean?

Question: enter image description herewhat does $f '(x^2)$ mean? does it mean calculating $f '(x)$ and then putting x=x² or first putting $x=x^2$ in $f(x)$ and then differentiating it?
Let $f(x)=x^3$ and $f'(x)=g(x)$
So $g(x)=3x^2$
$g(x^2)= 3x^4$
$f'(x^2)=3x^4$ how this is incorrect?
Comment: It means:  take the derivative of $f$ and evaluate it at $x^2$, just as you have written.
Comment: I have answered, but not in full... Just the information required...
Comment: @TheBroly you are correct
Comment: f(x^2) = x^6 , f '(x^2) =6x^5 I am confused , which one is correct
Comment: dont substitute $x$ by $x^2$ in $f(x)$!
Comment: i have an image , how to show this in comment?
Comment: @TheBroly put it in your post, not in a comment
Comment: I have posted image. Shouldn't here y'=f '(2x-1/x^2+1) ?If it is so?
Comment: @TheBroly it is. $y'=f'()$ and then derivative of whats in $()$
Comment: @TheBroly see that they substitute $f'()$ with $\sin ()^2$
Comment: for eg: if $y=f(x^4)$ then, $y'=f'(x^4)\cdot 4x^3$ i.e. derivative of $f(x^4)$ multiplied by derivative of $x^4$
Comment: f(x^2) = x^6 , f '(x^2) =6x^5 how it is incorrect? Is it f'(x^2).(2x)=(3x^4)(2x)=6x^5?
Comment: your case is different. you want $f'(x^2)$, not derivative of $f(x^2)$.  so just put $x=x^2$ in $f'(x)$, giving you $3x^4$
Comment: Thanks ,Now I understand f′(x^2) is not derivative of f(x^2)
Comment: yes! if $y=f(x^2)$ den $y'=f'(x^2)\cdot 2x$
Comment: if you want $f'(x^2)$ you need to replace $x^2$ by $t$ and take $2xdx=dt$
Comment: Proof:   $f(x^2)=x^6=f(t)=t^3$ and $2xdx=dt$. $f'(t)=3t^2dt$ So, $f'(x^2)=3x^4(2x)=6x^5$ which you got, and mistook it for $f'(x^2)$
Comment: Yes, I mistaken between f '(x^2) and (f(x^2))'
Answer: The derivative of $h(x)=f(x^2)$ should be denoted $h'(x)=\bigl(f(x^2)\bigr)'$, whereas $f'(x^2)$ is the derivative of $f$, evaluated at $x^2$. So your answer is correct.
Answer: $f'(x^2)$ means

find the derivative of $f(x)$. $f'(x)=g(x)$
evaluate the derivate at point $x^2$. $f'(x^2)=g(x^2)$
Answer: You are correct!
DON'T substitute $x=x^2$ in $f(x)$.
 $$f(x)=x^3$$
Take first derivative:
$$f'(x)=3x^2$$
 Replace $x$ by $x^2$ $$f'(x^2)=3(x^2)^2=3x^4$$
This is how you find value of $f'(x)$ for ANY $x$; just replace $x$ by that.
Who told you $3x^4$ is incorrect?

what does $f '(x^2)$ mean?


Execute complex SQL queries

Question: I need to execute these SQL instructions.
CREATE TABLE superstatistics_counter LIKE node_counter;
INSERT superstatistics_counter SELECT * FROM node_counter;

When I run the query, it runs. I expect the node_counter table to get a big table with about 100000 rows.
This is what I have tried:

With hook_schema() I have created the superstatistics_counter table
With this code I tried to copy data from the node_counter table
$sql = "SELECT * FROM `node_counter`";
$data = db_query($sql)->fetchAll();
foreach ($data as $dataObject) {
  $dataArray = array($dataObject->nid, $dataObject->totalcount, $dataObject->daycount, $dataObject->timestamp);
  $query = \Drupal::database()->insert('superstatistics_counter');
  $query->fields([
    'nid',
    'totalcount',
    'daycount',
    'timestamp'
  ]);
  $query->values($dataArray);
  $query->execute();
}

It caused the following error:

Maximum execution time of 120 seconds exceeded

So it is very slow.
When I executed it in phpMyAdmin, it output the following.

MySQL returned an empty result set (i.e. zero rows). (Query took 0.1401 seconds.)
CREATE TABLE superstatistics_counter LIKE node_counter

100000 rows inserted. (Query took 0.9567 seconds.)
      INSERT superstatistics_counter SELECT * FROM node_counter

Is there a way to just execute this query in Drupal, without using db_query() and \Drupal::database()->insert()? Can it be done on MySQL side?
Answer: The db_query function  isn't just for select queries, it will execute anything.
Just use that instead of the loop, the performance will be miles better:
db_query('INSERT INTO superstatistics_counter SELECT * FROM node_counter');

Comment: Thank you very much!
In official documentation is this: `Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.
Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.`

So it confused me and I didnt try to use db_query()....
Comment: Yeah that's a bit of a shame. The docs mean well but the information is wrong

Execute complex SQL queries


Sprite Kit: Is there a way to disable the scale mode and code what you want to happen

Question: I'm building a universal app using Sprite Kit, Objective C. This app is aimed for OS X as well as iOS platforms.
A problem that many people will have encountered is the positioning of objects on the screen as different devices have different proportions. I have read up many answers/posts online to solve this issue and have come to the conclusion that there seem to be only a few options available to the programmer when it comes to solving this which is selecting the appropriate scaling modes which are available: Aspect Fill, Aspect Fit, Fill, Resize Fill.
I have tried all 4 out, and can see that they all have numerous advantages, but all have their cons, so none of them are what I am looking for.
I have come up with my own solution for what I am looking for (the following code is from the OS X version, but the iOS version is very similar):
First, I define sceneDimension using a macro:
#define sceneDimension 1024

Then I delete the SKScene file, and create my own scene using the following line of code:
@implementation AppDelegate

@synthesize window = _window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

GameScene *scene = [[GameScene alloc] initWithSize:CGSizeMake(sceneDimension * (self.skView.bounds.size.width / MIN(self.skView.bounds.size.width, self.skView.bounds.size.height)), sceneDimension * (self.skView.bounds.size.height / MIN(self.skView.bounds.size.width, self.skView.bounds.size.height)))];

.....

}

.....

@end

This code ensures that whatever the size/proportions of the device the app is running in, the top right coordinate of the screen will always be treated as (x, 1024) if the width of the screen is larger, or (1024, y) if the height of the screen is larger.
In this way, I won't have to worry about repositioning objects as long as the scene always maintains the smaller coordinate of the top right corner to be 1024. (This is not the same as Aspect Fit, as I don't want to have letterboxing)
The problem I'm encountering is apparent when I run the app on OSX. Whenever the window is resized, a scaling mode still needs to be selected, and none were the ones which I was after.
Therefore, I wish to override whatever the program does when it scales the screen, by using the line of code:
scene.size = CGSizeMake(sceneDimension * (self.view.bounds.size.width / MIN(self.view.bounds.size.width, self.view.bounds.size.height)), sceneDimension * (self.view.bounds.size.height / MIN(self.view.bounds.size.width, self.view.bounds.size.height)))

However, I don't know where to add the line of code. I have tried using this line of code in the function didApplyConstraints: in the .m file:
@implementation

.....

- (void)didApplyConstraints {

    scene.size = CGSizeMake(sceneDimension * (self.view.bounds.size.width / MIN(self.view.bounds.size.width, self.view.bounds.size.height)), sceneDimension * (self.view.bounds.size.height / MIN(self.view.bounds.size.width, self.view.bounds.size.height)))
}

@end

And this gives the desired result mostly. However, during the dragging of the mouse, it can still be seen that the scene is being scaled using one of the previously mentioned scaling mode, rather than my new function. I also read that didApplyConstraints: is called every frame, which is what I don't want to happen - I want it to be called whenever the size of the window changes.
Is there a more appropriate function instead of didApplyConstraints: which does this? didChangeSize: does not work either, since the program ends up in an infinite loop since I change the size inside the function.
Thanks!
Answer: It sounds like what you are trying to attempt is .AspectFill,  but with a twist.  You want to fill up your screen, but keep your coordinate system the same on the x axis for all devices.
When you are doing your math, you need to take the aspect ratio into consideration.
We are only going to talk about portrait mode here.
We have an iPhone 5 that has an aspect ratio of 9:16.
We want our x to always be 1024.
This means that we want our y to be 1820 (1820.4444~ to be exact)
Now we have an iPhone 4 that has an aspect ratio of 2:3.
This means that we want our y to be 1536
So, to get these numbers, you take (1024 * height) / width
We can now again talk about both portrait and landscape.
Here is how you would apply the math:
let w = sceneDimension
let h = (w * UIScreen.mainScreen().bounds.size.height) / UIScreen.mainScreen().bounds.size.width)
scene.size = CGSizeMake(w,h)

This now means that regardless of orientation,  when the scene is created,  the bottom left most point is (0,0), the bottom right most point is (1024,0).
Aspect Fill will now fill up the entire screen, leaving no letter boxes, and no loss on your edges
Comment: Yes, but I need to make the scene resize itself properly whenever the window changes size.
Comment: you resize your scene doing the same math when a size changes.
Comment: my answer is in iOS,  I do not know how to grab a window size in OS X,  but  place the windows height and width where I have screen
Comment: Yes but I don't know **where** to put that math when the size changes. Which function...
Comment: well I am sure you can look that up
Comment: I have, and cannot find it. Why do you think I am posting this question?
Comment: no, that is an entirely different question with a really easy answer that can be easily searched.  Look at the first link here https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=xcode%20os%20x%20window%20resize%20notification
Comment: It's not just window resizing (although this is the main problem I need to solve). Sure this solution works for OS X, but then what about iOS when the scene needs to resize too?
Comment: why would the scene ever resize
Comment: Are the scaling modes not used outside of the initial set up?
Comment: on iOS the resolution will never change other than switching from portrait to landscape.  If you are worried about having a view that is somehow sizable inside of a master view, then instead of grabbing the screen size, you override the view size property, and apply the math in the `didSet` method
Comment: There is almost never a need to change the scaling mode once set up.  How you want to think about it is you have a box,  what do you want to do to make this box fit the screen,  and the choices are you can stretch the box unequally in both axis (.Fill) stretch the equally box till it hits the nearest borders (.AspectFit) stretch the box equally till it hits the furthest borders (.AspectFill) or just give the box more surface area till the screen is full (.ResizeFill).  After you determine how this box is laid out,  you shouldn't design it to change its state.  This will screw your math up.
Comment: I took way too long to find this answer, thank you so much.
Comment: @JoshSchellenberger What are you doing?  This answer is probably way too old
Comment: I used your answer to make a constant width no matter the size when I am loading my scene initially. Unfortunately, this didn't work when calling the scene again (not through the view controller). I have laid out my entire problem here: https://stackoverflow.com/questions/56689691/how-to-navigate-objective-c-app-programmatically-without-using-only-storyboard


Dúvida com função recursiva em C

Question: Boa noite, pessoal!
Estou realizando uma atividade cujo objetivo é usar uma função recursiva para realizar uma divisão inteira apenas através de subtrações sucessivas.
Fiz um laço usando while e somente ele (que rodei em um código a parte) deu certo. O problema está em usá-lo na função recursiva. Consegui fazê-lo compilar, mas o resultado não está correto.
Olhando o código ainda não encontrei o problema (pensei que fosse o return i na função, mas o resultado não foi alterado, ou talvez na declaração das variáveis - mas ainda não sei dizer)... Comecei a aprender funções recursivas há pouco tempo, caso alguém possa ajudar, agradeço muito a ajuda!
Laço que dá certo sozinho:
#include <stdio.h>

int main (){

    int a, b, i = 0;

    printf ("Digite o dividendo (numero que será dividido):");
    scanf ("%d", &a);

    printf ("Digite o divisor:");
    scanf ("%d", &b);

while (a > 0 && a >= b){
    a = a - b;
    i++;
}

    printf ("O resultado da divisao e: %d", i);

    return 0;
}

Função recursiva que dá errado:
#include <stdio.h>

int main (){
    int a,b;

    printf ("Digite o dividendo (numero que será dividido): ");
    scanf ("%d", &a);
    printf ("Digite o divisor: ");
    scanf ("%d", &b);

    printf ("O resultado da divisao e: %d. \n", divide(a,b));

    return 0;
}

int divide (a,b){

    int i = 0;

    while (a > 0 && a >= b){
    a = a - b;
    i++;

    return i;
    }

}

Answer: Erro do programa
O erro da sua função está na posição do return, nesse trecho:
while (a > 0 && a >= b){
    a = a - b;
    i++;

    return i;
}

O comando return tem duas funcionalidades:

Encerra uma função
Encerra uma função devolvendo um valor

Com base nisso nota-se que quando o while é ativado ocorre essas três instruções:

O valor de a é subtraido
i é incrementado em 1
A função é encerrada devolvendo o valor de i

Se a função é encerrada logo após o valor de i aumentar em 1 então o loop que o while faz não ocorrerá e isso gera o resultado inesperado.
Solução
Para resolver este problema basta deixar o comando return fora da do loop, desta forma:
while (a > 0 && a >= b){
    a = a - b;
    i++;
}

return i;

Assim a função só será encerrada quando o loop terminar.
Recursividade
Mesmo depois de resolver o problema essa função não é recursiva.
Uma função recursiva é uma função que chama a se própria. Exemplo:
int funcao(int a) {
    // Alguns codigos

    funcao(a); // funcao chamando a si mesma

    // Mais codigos

    return a;
}

O trecho acima é um rascunho do que seria uma função recursiva. Uma observação é que devemos ter cuidado ao usar a recursividade para não criar um loop infinito.
Trasnformando sua função em uma função recursiva
Para que sua função seja recursiva é preciso que ela chame-se a si mesma. Exemplo:
int divide_recursivo(int a, int b) {
    int i = 0;

    if (a > 0 && a >= b) {
        a = a - b;
        i++;
        i += divide_recursivo(a, b); // a funcao chamando a si mesma
    }

    return i;
}

Na sua lógica usando o while o valor de i era incrementado ´n´ vezes dependendo desta expressão: a > 0 && a >= b. Se o loop iria repetir 10 vezes, então a função recursiva precisa ser chamada 10 vezes. A expressão a > 0 && a >= b é quem garante isso. Caso não tenha ficado muito claro eu recomendo você fazer o teste de mesa.
Veja seu código funcionando aqui.
Answer: Acredito que para você usar a recursividade teria que chamar o método dentro dele mesmo, por exemplo:
int divide (a,b){

    int i = 0;

    while (a > 0 && a >= b){
    a = a - b;
    i++;

    return divide(a, b);
    }

}

Comment: Oi Bruno, agradeço a resposta! No entanto se eu uso o return divide(a, b), o resultado ainda permanece o mesmo de antes... Também percebi que na maior parte das vezes o valor de i acaba sendo igual ao valor de b (não sei se ele acabou fazendo o cálculo errado ou se deu algum conflito entre as variáveis).

Dúvida com função recursiva em C


Is this a safe way to set values in a DataFrame? Why does this work?

Question: I'm using .loc to filter my DataFrame and set values from another column. Here's a short example, first setting up a simple DataFrame:
df = pd.DataFrame({
    'name': ['Steve', 'Julie', 'Dan', 'Mary'],
    'nickname': ['Steve-o', 'Jules', '', '']
})

#     name  nickname
# 0  Steve   Steve-o
# 1  Julie     Jules
# 2    Dan
# 3   Mary

Next I replace the missing values using .loc like this:
df.loc[df['nickname'] == '', 'nickname'] = df['name']

#     name  nickname
# 0  Steve   Steve-o
# 1  Julie     Jules
# 2    Dan       Dan
# 3   Mary      Mary

Why does this even work? I'm assigning a series of a different length, how does it know to only match the items with the same index number? Why doesn't it throw an error about the series being different lengths? This just seems very magical to me and it makes me nervous.
After lots of searching, I can't find any examples of this approach in the official documentation. I have seen a few rare examples of this out in the wild, but with no explanation or reassurance that it's a correct approach.
Comment: pandas aligns everything based on the index, before doing any computation. that's a fundamental approach of the library. so your code above makes sense. You can give it a try and flip the indices of `df[name]` when reassigning. if none of the indices match, then it should raise an error. Of course, you can disable index alignment by passing an array instead
Comment: I tried to recreate this behavior by working with two Series objects, but when I tried to do an assignment using a slice or something, I get an error about them being different lengths. So I guess I was just having a hard time understanding how when I use `.loc` suddenly that no longer is an issue. Thank you for the reassurance though!
Answer: It's because Pandas sets the values by the corresponding index. The index of the name is 0 1 2 3, but the located rows (loc) indexes are 2 and 3, so it would reindex the original name column to only the 2 and 3 index.
Here is a proof:
If we were to assign to a completely different index:
>>> df['name'].set_axis(['a', 'b', 'c', 'd'])
a    Steve
b    Julie
c      Dan
d     Mary
Name: name, dtype: object
>>>

It wouldn't work, example:
>>> df.loc[df['nickname'] == '', 'nickname'] = df['name'].set_axis(['a', 'b', 'c', 'd'])
>>> df
    name nickname
0  Steve  Steve-o
1  Julie    Jules
2    Dan      NaN
3   Mary      NaN
>>>

There is the proof! loc assignment is based on row indexes, in this case None of the indexes matched, so it gave missing values (NaN).
If you use a list or array which doesn't have indexes, this wouldn't work.
This is the "magic" of Pandas.
Do not think that indexes are nothing, Pandas assigns everything based on the indexes.

Performance-wise I prefer to use:
df.loc[df['nickname'] == '', 'nickname'] = df.loc[df['nickname'] == '', 'name']

To make Pandas not need to do the extra work of matching the indexes.
For some cases with big DataFrames:
df.loc[df['nickname'] == '', 'nickname'] = df['name']

Would give an MemoryError, but:
df.loc[df['nickname'] == '', 'nickname'] = df.loc[df['nickname'] == '', 'name']

Wouldn't, because the number of rows of the assignment are less.
Comment: Thank you for the explanation. I was considering using the example you gave where you're using `.iloc` on both sides of the assignment, as I felt more comfortable with that since it is so explicit about what it is doing.
Comment: @Glenn Yeah! Pandas is magical :)


tensor product of two algebras

Question: As an $\mathbb{F}_{2}$-algebra, is $\mathbb{F}_{q} \otimes_{\mathbb{F}_{2}} \mathbb{F}_{2^2} $ isomorphic to $\mathbb{F}_{q}^2$, where $q = 2^k$ for $k$ is even?
Please give me some idea and some reference.
Answer: Writing $\mathbb{F}_{2^2} = \mathbb{F}_2[X] / (X^2 + X + 1),$ it follows that $$\mathbb{F}_q \otimes_{\mathbb{F}_2} \mathbb{F}_{2^2} \cong \mathbb{F}_q[X] / (X^2 + X + 1) \cong \mathbb{F}_q^2,$$ since $X^2 + X + 1$ splits in $\mathbb{F}_{2^k}$ whenever $k$ is even.

tensor product of two algebras


GTK function call messes up completely unrelated char* value

Question: I have similar code (but in a greater scope) in a GTK application:
#include <stdio.h>

struct TStruct {
    char *string;
}

void func(struct TStruct *tstruct) {
    char chara[8];
    sprintf(chara, "%.*s", 4, "testing");
    tstruct->string = chara;
}

int  main() {
    struct TStruct tstruct;
    tstruct.string = NULL;
    func(&tstruct);
    printf("%s", tstruct.string);
    return 0;
}

This snippet by itself works fine. However, in the GTK application, creating a GTK object anywhere after the snippet corrupts the value for tstruct.string. Why could that be? Is the above snippet not the best way to assign strings?
Changing tstruct->string = chara to tstruct->string = g_strdup(chara) fixes the issue. I can kind of guess that that was the problem, but can someone explain how that works?
Answer: You need to pay attention on what you are doing. You are allocating an array of char in the stack, since it is local to the func function, and them you are assigning it to a member of the struct that you are passing as a parameter. You have some options to solve your problem. One is to use an array of char instead of a pointer to char and copying the array entirely:
#include <stdio.h>
#include <string.h>

#define STRING_SIZE 8

struct TStruct {
    char string[STRING_SIZE];
};

void func(struct TStruct *tstruct) {
    char chara[STRING_SIZE];
    sprintf(chara, "%.*s", 4, "testing");
    strncpy( tstruct->string, chara, STRING_SIZE );
}

int main() {
    struct TStruct tstruct = {0};
    func(&tstruct);
    printf("%s", tstruct.string);
    return 0;
}

Another one is allocating the memory dinamically and them freeing it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STRING_SIZE 8

struct TStruct {
    char *string;
};

void func(struct TStruct *tstruct) {
    char *chara = (char*) malloc( STRING_SIZE * sizeof(char) );
    sprintf(chara, "%.*s", 4, "testing");
    tstruct->string = chara;
}

void freeTStruct( struct TStruct *tstruct ) {
    free( tstruct->string );
}

int main() {
    struct TStruct tstruct = {0};
    func(&tstruct);
    printf("%s", tstruct.string);
    freeTStruct(&tstruct);
    return 0;
}

And finally, I would implement something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct MyType {
    char *string;
    size_t stringLength;
} MyType;

MyType newMyType( const char* string ) {

    MyType new = {
        .string = NULL,
        .stringLength = strlen(string)
    };

    new.string = (char*) malloc( (new.stringLength+1) * sizeof(char) );
    strncpy( new.string, string, new.stringLength+1 );

    return new;

}

void freeMyType( MyType *myType ) {
    free( myType->string );
}

int main() {
    MyType foo = newMyType( "bar" );
    printf( "string: \"%s\", length: %d", foo.string, foo.stringLength );
    freeMyType( &foo );
    return 0;
}

Answer:
This snippet by itself works fine.

No it doesn't. It has undefined behavior due to accessing an object after its lifetime has ended.
void func(struct TStruct *tstruct) {
    char chara[8];
    tstruct->string = chara;
}

This code (with or without the sprintf) stores a pointer that points to the first element of the local array chara. After the function returns, the lifetime of chara ends, and later access using
printf("%s", tstruct.string)

is accessing an object after its lifetime has ended. This is undefined behavior.
Calling any strdup type functions allocates a new string in the free store (in most implementations, the heap),whose lifetime persists until explicitly freed, making the behavior well-defined. And you should free the string to avoid memory leak.
Comment: Mostly yes. In pratice it usually means the memory can be reused and overwritten, but undefined behavior is more than that, the compiler for example can choose to skip the memory access at all as an optimization.
Comment: Yeah, as suspected huh. Thanks for the answer. Just to be sure, "end of lifetime" means the string exists in memory but that memory is "overwriteable" by the OS, right?


Where does drush store the different module versions for a multisite installation?

Question: I wonder where the different module versions are kept on a multisite installation.
Before I (re)discovered drush, I had several more sites sharing the core code
 and sites/all/modules a symlink to a common modules dir.
On upgrading core I set that link in the new sites/all dir.
And then I started using drush. So when I do drush up in the sites/my1stsite dir and it updates the modules, how can the other my2ndsite still have the old modules? (and be able to drush up-date itself?)
Answer: If you are using a multisite installation with shared modules stored in sites/all/modules, then Drush pm-update will also put the new modules in this same shared directory.  This means that you must also run updatedb on all of the other sites that share the same module code, as all of the sites will need to be upgraded at the same time.
It is far more convenient to use a single-site installation, and give every site their own complete copy of Drupal core + contrib modules, as you will then be able to update each site independently.  Fortunately, splitting up a multisite install is as easy as cloning your Drupal files, and changing your web server virtual hosts configuration file to point at the new site's location.
Comment: Meanwhile I put sites/mysite a module folder for some sites, I will consider to separate core too. thx.
Comment: If you move your modules, be sure to run the registry rebuild tool: http://drupal.org/project/registry_rebuild


Intergal of non negative measurable function on measurable set.

Question: Let $(X,M,\mu)$ is measure space
$f$ is non negative  measurable function .
E is measurable set in M .
then $\int_E f=\int \chi_E f$
My Attempt: $\int f=\sup_{0\leq \phi \leq f }{\int \phi }$ where $\phi$ is simple function
$\int_E f=\sup_{0\leq \phi \leq f }{\int \phi }=\sup_{0\leq \chi_E\phi \leq \chi_E f }{\int \phi }$ =$\int \chi_E f$
I have doubt that is above correct? Actually I had proved charactersitics function of type $\chi_E\phi $ but definition required supremum over all possible simple  function
Any Help will be appreciated
Comment: $\int_E f=\sup_{0\leq \phi \leq f }{\int_E \phi }$
Comment: What is $\int_{XE}f$?
Comment: What is your _definition_ of $\int_E f$? The usual definition is $\int_E f=\int\chi_E f$.
Comment: Dear Sir , I had mentioned definition in my attempt:
Answer: Note that $\psi$ is a simple function such that $0 \leqslant \psi \leqslant f\chi_E$ on $X$ if and only if $\psi = \phi\chi_E$ where $\phi $ is a simple function such that $0 \leqslant \phi \leqslant f$ on $E$.
Thus,
$$\int_E f = \sup_{0 \leqslant \phi \leqslant f}\int_E\phi = \sup_{0 \leqslant \phi \leqslant f}\int_X\phi\chi_E = \sup_{0 \leqslant \phi\chi_E \leqslant f\chi_E}\int_X\phi\chi_E = \sup_{0 \leqslant \psi \leqslant f\chi_E}\int_X\psi = \int_X f\chi_E$$


How to sort a massiv array along innermost dimension?

Question: I have an Array r Ix2 a such that (Manifest r Ix2 a, Ord a). I'd like to sort this array on its innermost dimension - that is, sort each row internally, but not across rows. According to this, massiv doesn't have any sorting implemented at all. Would I have to roll my own, or can I re-use something that already exists for Vectors (such as vector-algorithms for example)?
Answer: Of course, it would be better to roll out your own sorting and submit a PR to massiv library ;) But there is a way to fall back onto vector-algorithms package. I was curious how I'd do it efficiently and here it is, along with automatic parallelization of sorting each row:
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
module Examples.SortRows where

import           Data.Massiv.Array                 as A
import           Data.Massiv.Array.Manifest.Vector as A
import           Data.Massiv.Core.Scheduler
import           Data.Typeable
import           Data.Vector.Algorithms.Merge
import           Data.Vector.Generic               as VG
import           Data.Vector.Generic.Mutable       as VGM
import           System.IO.Unsafe

sortRows ::
     forall r e v.
     (Ord e, Typeable v, A.Mutable r Ix2 e, VG.Vector v e, ARepr v ~ r, VRepr r ~ v)
  => Array r Ix2 e
  -> Array r Ix2 e
sortRows arr = unsafePerformIO $ do
  mv :: VG.Mutable v RealWorld e <- VG.thaw (A.toVector arr :: v e)
  let comp = getComp arr
      sz@(m :. n) = size arr
  case comp of
    Seq -> do
      loopM_ 0 (< m) (+ 1) $ \i -> sort $ VGM.slice (toLinearIndex sz (i :. 0)) n mv
    ParOn wIds ->
      withScheduler_ wIds $ \scheduler -> do
        loopM_ 0 (< m) (+ 1) $ \i ->
          scheduleWork scheduler $ sort $ VGM.slice (toLinearIndex sz (i :. 0)) n mv
  v :: v e <- VG.unsafeFreeze mv
  return $ A.fromVector comp sz v

I did add this to examples in massiv in this commit together with a simple property test.


My clarinet is playing flat - how can I fix it?

Question: First of all I understand that most people's first (and very reasonable) place to look to improve intonation is at the technique of the player: embouchure quality and technique, air support, maybe quality of reed, etc. I have been following this advice for a couple of years now and it hasn't improved the general flatness of most pitches, especially "throat" pitches I think they're called.
For some background, I mostly play brass instruments with some traditional jazz bands, and have been working for a few years on the clarinet to "bring it out of the closet" eventually. I mostly play clarinet with myself for practice and this feels comfortable. But when I play with a backing track, or at jams with others, it is obvious that I have to play much sharper than I do in my own practice without a pitch reference, and I am constantly "lipping up" every pitch to try to be in tune, often "breaking" entirely when playing with others. I can lip up some pitches to be in tune, but nearly half of them, no matter what I do, cannot get any sharper without breaking/squeaking.
At this point I'm convinced that, though I may not have perfect technique, that there is something mechanical at work that cannot be overcome with technique alone. I think the instrument is just playing flat for whatever reason(s). Having done some research it seems a good number of things can affect pitch, from mouthpiece, barrel, and the tapers of things.
I don't live in a big city, and I don't think there's any place in my area where I can go in and try out different mouthpieces and barrels to try to figure out what might help. Nor is there anyone that works on clarinets in my area that I know of who I could speak with.
As far as specs go, I'm playing a

Buffet Crampon R13 Bb
B 660 barrel (66mm)
Vandoren B40 mouthpiece
All reeds I've tried have no effect on the issue

I've most recently considered buying a 65mm or 64mm barrel to see if this would help, but I understand that this does not affect all notes equally. And the barrels are not cheap ($170-190).
I'm wondering what you smart folks would recommend I do, check, or consider.
--- UPDATE ---
As for the actual pitch, I've confirmed with a tuner that most notes in what seems to me to be the most free-blowing resonant focused tone are between 10 and 30 cents flat. This is less towards the bottom of the instrument with more holes covered.
I've uploaded a video to youtube trying to demonstrate the issue. Bear in mind that I'm not trying to get the greatest constant tone here. I'm trying to demonstrate the tone quality at a lower pitch compared to the choked deadened quality that results from trying to play at the proper pitch. It also demonstrates that the sharpest I can manage to play on most notes, is still under proper pitch, and I couldn't play sharp on purpose if I wanted to. It also demonstrates that the flat effect is worse with fewer holes covered, and is progressively more accurate with more holes covered. In the higher register the cracking is a result of trying to play "up" or lip up the pitch to be more accurate and it is very tense and pretty awful to play and hear. When the horn has its most resonnant natural tone, it's quite flat.

Also please be kind, I'm not an expert. Just trying to figure out why my sound comes out 10-30 cents below proper pitch.
Thanks!
Comment: Do you know any well-trained clarinet players who could test it out to see if they have the same trouble with it?
Comment: Another possibility is that while most modern instruments are generally tuned to A440, some instruments may be tuned to a different A, ranging from 400 to 450 Hz before it was standardized in 1939.  Note that it's not just older instruments that may be tuned differently, but even modern instruments may be custom built to play older music in a different tuning.
Comment: R13 is a pretty serious instrument for someone just playing occasionally. Did you get it used? Any idea how old it is? I'm not sure but that might be a factor. You could just be playing flat normally, so you have a tuner you can play with to get an objective sense? (What if the others are playing sharp?) If you're really flat across the board, a shorter barrel may help. You should already be experiencing some notes being flatter than others, so not affecting all notes equally is just par for the course. You have to intonate each note of the clarinet anyway, right?
Comment: @PiedPiper I just added a video that might help
Comment: What hardness reed are you using? I can easily reproduce what's happening in the video by putting on a 2.5 reed (I normally play 3.5+) and dropping my tongue way down in my mouth and then trying to use my lower lip to control the intonation. That gets me both closer to the tone you have and also the behavior of the sound choking when I try to bring up the pitch. I suggest stiffer reed and very high tongue position, unless you're already doing that. To really match your tone I have to have very little mouthpiece in my mouth. I suggest moving your lower lip down the reed.
Comment: I gather you already have the mouthpiece pushed as far in as possible?
Comment: @Aaron yes I push everything in as far as it will go.
Comment: Also if you know another clarinet player they may have a shorter barrel you can try.  I don't recall the length of mine, but it's not the factory issue length.
Comment: Stupid question: have you checked it with a tuner? What is your method of tuning ?
Comment: To start diagnosing your problem: check the pitch on the second register long C and tell us exactly how much that note is flat (played mf with a normal embouchure and full, resonant tone).
Comment: @DarrelHoffman The Buffet R13 wasn't designed until 1955, well after the pitch standardization in 1939. Even in the highly unlikely event that a modern instrument had been built to the pitch standard for historically correct performance of classical music, A=430, it would be a lot flatter than 10-30 cents.
Comment: @PiedPiper I'm not trying to create a stable pitch here. I'm trying to demonstrate the tone quality differences that result from trying to play up to proper pitch with a flat horn compared to where it sits "naturally".
Comment: The Ab and G starting around 0:50 both sound better and are less flat. Many of the other notes sound more like an alto sax than a clarinet, which is not right. I don't think a shorter barrel is going to help. The A at about 1:33 says it all: it sounds much better and is basically in tune. You should be able to get at least that tone quality out of every single note with the correct embouchure.
Comment: I was using a 2 Legere synthetic reed, and indeed, when I moved up to the 2.75 the pitch went up as well. It forces me to use a slightly different embouchure (one that is probably better technique). That said, I think the reed was exacerbating an issue in the instrument. Changing the reed moves my pitch up about 15 cents, which is a huge improvement. That said, I think I should be able to play in tune on a variety of reeds, so I'll be experimenting with some mouthpieces and barrels. I read this recently from a guy who seems much more experienced than me (next comment):
Comment: "The B45 is much more focused for me. I had to use extremely short barrels on my clarinet when playing the Vandoren mouthpieces. .... The Lakeys are wonderful - focused, very strong, and on pitch. I use Fibracell Synthetic reeds (#1 1/2 or sanded-down #2) - a perfect match for me. FWIW, I play them on a Buffet RC Prestige, R-13, E-11, Silver King, C-Albert, Bb Conn Albert, and a Yamaha YCL 457 German System clarinet. https://www.saxontheweb.net/threads/vandoren-5jb-vs-7jb-profile-88-vs-traditional.244963/
Answer: The first thing to try is playing another clarinet.  If that's flat as well, it's you.   If not, start looking for mechanical solutions.  But it seems unlikely that what seems to be a standard, reasonable quality instrument would be 'built flat'.
Comment: I added a video link to the post that might help clarify the situation
Comment: I disagree. With an R13 the **first** thing to try would be adjusting the reed and embouchure.
Comment: He's convinced himself that embouchure isn't the problem.   First job - demonstrate that it IS.   (Or confirm otherwise.)
Answer: With an instrument that is consistently playing flat, the first thing to try would be a new barrel. Your 66mm barrel is the standard, but you can easily find a 65mm or 64mm to try. The shorter barrel will shorten the instrument and make it play sharper.
Comment: I added a video link to the post that might help clarify the situation
Comment: I disagree. With an R13 the **first** thing to try would be adjusting the reed and embouchure.
Answer: Even if you are "out in the boonies," I strongly recommend getting an expert to evaluate your axe.  This may entail mailing it off to some clarinet repairman and waiting for him to return it with a report, but that's the best way to determine for sure whether it's the instrument or your technique that is at fault.
By the way, are you absolutely 100% sure you bought a Bb and not an A clarinet?
Comment: I appreciate this advice. I can make to a larger city sometime, and try to arrange a meeting. I'm pretty sure it's a Bb, but not exactly clear on how to check, except for the pitch. The number on the back says 532278. I guess I could look that up. I bought it from a friend whose relative passed away who was a player. It's a good horn, and having played music for 30 years I didn't bother to start on a student model, since that held me back on violin and guitar in the past, as they were harder and less enjoyable to play.
Comment: I added a video link to the post that might help clarify the situation
Comment: An A clarinet would be close to 100 cents flat, not 10-30.
Comment: @pixelearth You can get a remote lesson with a teacher who should be able to help even over a laptop microphone.
Answer: Edit - additional info
I created a video of me trying to re-create the tone and intonation problems that you have and I think I succeeded:

Then I changed to my normal setup and embouchure and recorded a little more:

If you're not familiar with strobe tuners, when the blue bars on the screen are going up, the note is sharp, when they are going down, the note is flat. There's also a display of cents sharp/flat.

Original post
I'm sorry to have to say this but both the tone you have in the video as well as your clear ability to lip the notes into tune suggest that it might  not be your clarinet, it might be you. Your embouchure seems off to me. Your tone seems quite reedy and not round.
I wish I could tell you simply what to change, but it could be so many things, and is probably a combination. Before buying anything I would take a one hour lesson with a good teacher. At least they should be able to confirm for certain whether it's you or the clarinet.
As for things to try, could be too little mouthpiece in your mouth, not a firm enough embouchure, air too slow, tongue not high enough, chin not pointed properly, and of course all of these interact with each other. I would start by trying to get as much mouthpiece in your mouth as possible, with your lower lip halfway between the tip of the reed and the top of the ligature. You will probably have to adjust your tongue position. It should be convex towards the roof of your mouth, with the tip of your tongue just off the end of the reed and pointed slightly down. The closer you can get your tongue to the contour of the top of your mouth without touching the better. Make sure your lower lip is firm and the face of your chin is flat.
Also support should be solid, breathing might benefit from some work. If you're playing softer than a 3.0 that could be contributing, especially if it's a synthetic reed.
An R13 should be able to create a very rich, round, woody tone across its entire range. If you don't sound like a pro in a major city symphony, it's not because of the instrument. Even on a softer reed a correct embouchure should sound very nice on that clarinet. The only possible exception might be if it is an old R13 that might be damaged or have a bad bore in some way, but even then I'd expect a better tone.
A good one hour lesson should cost much less than a barrel. Invest in one to double check whether I'm right. I can only bend notes like you do in the video if my embouchure is way off, so that's my strong suspicion. If I'm right (or wrong), a decent teacher will be able to tell in maybe ten seconds of you playing.
Oh yeah, make sure your reed is high on the mouthpiece. And make sure your ligature is in the correct spot. With your lip halfway down the read and a nice firm embouchure, you can feel when the reed is in the right place. When you have it right the notes just jump out and sound surprisingly warm and round. If you're fighting for every note it could be a bad reed or it could be too low or two high. Placing the reed takes practice.
Comment: Hey @Todd thanks for taking the time to make these videos. I appreciate the spirit of sharing! I'm getting this pretty late at night, so I won't have time to respond until tomorrow. I am indeed using a synthetic legere reed and it's quite thin. I think it was a 2.5 jazz cut, and it plays like a 2 probably. I definitely play in a similar location to you, not up near the opening and my reed generally flush with the tip or just under. I have played the 3 and 3.5 reeds and they were not significantly sharper, but they did make it harder to shape and bend notes as is common in early jazz styles.
Comment: I'll experiment tomorrow with cane and do more measurements and maybe make another video. I should probably make one with my normal tone so it's clear that I'm not actually all over the place, lol.
Answer: Try smiling a little more while you are playing. The warmer your instrument gets the sharper it will be, blow warm air into it before you play. Blow more air into you instrument, even if you are playing quietly.
Comment: To clarify, not simply "more" air, but faster air. High tongue position.
Comment: Smiling is a very bad idea.
Comment: The best advice to give to students is to NOT smile when playing. Doing a smile will widen your mouth and make your lips thinner -- quite the opposite of what you want when playing. I know, it is a sort of "natural" tendency when you get tired, but it will only make for a this tone.


How does string gauge affect intonation?

Question: I have a problem with intonation adjustment on my g-string on my Epiphone Les Paul. It's correct now but the bridge saddle cannot be adjusted any farther in range.
I need to change strings but I don't know what strings I have now and worry that I might have problems with intonation if I buy the wrong strings.
So how does string gauge affect intonation? Do I need to buy thicker or thinner strings?
Answer: You have asked two questions.
First
"What is the measurement of the G-string that you should use on your Epiphone Les Paul guitar?"
The correct technical term for what you call the "width" or "thickness" or "diameter" of the string is its gauge.
Take your guitar to a qualified guitar technician or luthier, or at least to your local music store, and have them examine the guitar. They can use a measuring device to tell you the exact gauge of strings that are on the guitar, or they can simply estimate it by looking at the strings. They can recommend what set of six strings you should purchase to replace the strings that are on your guitar now. They can also sell you individual strings if you don't need to replace all six.
Epiphone Les Pauls usually ship from the factory with a "set of 10s", which is to say a set of strings where the highest string is 0.010 inches in diameter, and the other five strings make up a matched set of gauges that work well with the 0.010-inch string.
Different sets of strings sold by different manufacturers will vary in the gauge of each individual string, but typically an Epiphone Les Paul would come from the factory with a G-string that is unwound and is 0.017 inches in diameter.
For example, below, I have provided a screen shot of a chart showing the standard string gauge specifications in a set of Gibson Brite Wires nickel-plated steel round-wound strings. This is a popular set of string gauges for a Les Paul-style guitar.

Second
you asked "So how does string gauge affect intonation?"
It is not so much a question of the string gauge affecting the intonation. Rather, it is that a guitar requires several different types of adjustment in calibration to work correctly if you decide that you would rather play with heavier strings or lighter strings. Adjusting the position of the bridge saddles is only one of these types of calibration.
Doing this requires a professional setup (a topic I have written about many times on this site, and something that beginning guitarists seem not to be aware of). If you want to use heavier or lighter-gauge strings on your guitar, you need to take it to a professional guitar technician and pay them (usually between $50 and $150 in the USA, in my experience) to change the calibration of several parts of the guitar, interactively, to work correctly with the heavier or lighter strings to produce proper intonation, to make sure all notes sound clearly, and to make the guitar easy to play (so that the height of the strings from the fingerboard and frets is neither too high nor too low). Adjustments and calibrations need to be made to the nut, the neck's truss rod, to the calibration and position of several mechanical parts in the bridge (particularly if it is a tremolo bridge like a Fender or Floyd Rose), and in extreme cases the frets or the fingerboard may need to be modified.
In short, you are correct that it is simpler to keep the same gauge of strings that are already on the guitar. Going to heavier or lighter-gauge strings would probably throw the guitar out of its proper calibration to the extent that it would be wise to pay for a professional setup. However, be advised that from time to time your guitar could benefit from professional maintenance and a setup even if you keep using new sets of the same gauge of strings. This is because, like any precision mechanical device, guitars and their necks can go out-of-calibration and change their shape or angle due to changes in humidity or temperature or the wear and tear of your playing the instrument over the years.
Comment: There's not a recommended gauge per guitar, it's all up to the player.  On a floating bridge you have balance issues, but the ELP is a fixed bridge, so it's really down to tone vs playability.  Thick gagues sound fuller, but are harder to play on at speed.
Comment: I would disagree about "Needing to take your guitar to a professional guitar technician". I'd agree it's important to be aware of this but there;s no harm in just trying it. It's entirely possible, even likely (depending on guitar), that changing string gauges will just work. That's always been my experience.
Answer: If your out-of-range saddle is under a plain string, you will probably be okay if you change string gauge (without changing action). If the out-of-range saddle is under a wound string, then it could go either way.
Ideally speaking, gauge does not affect the intonation of unwound strings which are made of the same material and tuned to the same note in the same string position of the same guitar. This is because although there is more tension in a thicker string, the stress is the same. A string which has twice the cross area has twice the mass, and so it needs twice the tension to get to the same pitch. The result is that the stress (force per unit cross-sectional area) is the same. Stress is measured in the same units as pressure: Pascals.
If the action is also the same, then it means that the elongation of the two strings is also the same due to the same geometry of the situation: when we fret either one at the same fret, we are elongating it by the same amount. Fractional elongation of a material is called strain. We are adding the same amount of strain to the thicker or thinner string, and the change in stress depends only on the strain and the material's elastic modulus.
Intuitively, if the string has, say, twice the cross-sectional area, then it's somewhat as if you had two strings of the original size in parallel.  Now there are going to be factors that creep in that will make some small difference, like neck relief changing under stress, the fact that the string is not an ideal string but actually a long skinny bar (and so a string with twice the area perhaps does not require exactly twice the tension to get to the same pitch), and material differences.
Material makes a difference because different materials require more or less tension to stretch the same amount (that elastic modulus thing again). For instance nylon strings for classical guitars have a low elastic modulus. They strain easily under low stress and so their pitch does not change much when they are fretted. For the same reason they do not respond to string bending very well.
If the unwound string is made of two materials (like via plating applied to a core) that also creates the possibility that the intonation will change, since their ratio will probably  be different in the different diameter.
Things are far less clear with the wound strings. The winding contributes to mass, thereby lowering pitch, but does not contribute much to the string tension, which is carried almost entirely by the core. Intonation almost certainly will change with a change of unwound gauge, or from change from plain to wound or vice versa because the thickness of the core as well as the amount of mass added from windings are changing simultaneously, and so the stress in the plain core will certainly be different at pitch, even if it is exactly the same material. Since the proportionality of mass and tension is not maintained, the intonation could go either way.
So if you're changing gauges without changing action, and keeping three plain strings plain, then you can expect not to have to do much, if anything, in regard to the three plain strings if they are the same "series" from the same manufacturer (same material). The saddles for the wound ones will likely need more adjustment.
I have found this to be approximately the case in actual experience, when changing among .009, .010 and .011. The theory, of course, goes out the window if you adjust action and/or neck relief.
Comment: Brilliant answer. It helped me understand some points, but I've played for 50+ years. It goes way beyond what I think the O.P. needed, but there again,loads (hopefully) of others will read this and be enlightened.I'm really glad the question was reinstated.What mileage is there in frightening newcomers away from this very useful (and thought-provoking) site?
Comment: This is a most interesting post. I'd like to add that (from the point of view of explaining one of the reasons why longer pianos have a better bass tone) the thicker the string is, the more off-pitch (skewed to high) the overtones are. (Guitars are probably too short for this to be a factor.) The reason is that the overtones derive from simultaneous vibration of the string in fractions of its length. For example, the string vibrates in halves, each half going in opposite directions, which produces an overtone an octave higher than the fundamental. (more)
Comment: So, the point at which the string changes direction (the "node") has a diameter, meaning that the part of the string that vibrates the overtone is slightly shorter than half the length of the string.  The thicker the string is, the bigger this node is, the relatively shorter the part of the string that vibrates to create the overtone is, and the more off-pitch the overtone is.  If you look, you will notice that upright pianos have thicker bass strings than 9-foot concert grands.  You will also find that the bass sounds "muddier" in the shorter pianos.
Comment: @Tim Thanks. I had most of this stuff figured out by the time I was 15. At around that time, the burning question I had was: how much harder is it to actually press/pend heavier gauge strings, in terms of pressure on the skin rather than absolute force? It's worse than linear because the contact area grows with the diameter, but the string tension (hence force required) grows with diameter squared. Thicker strings concentrate more force per area of your finger's skin. That's probably why even a small increase can be so uncomfortable: rising pressure above/beyond the extra force.
Comment: That's why on most of my guitars I use 008/010/012 strings for top three. Some say I lose tone, but I'm past caring !!
Comment: @Tim  If thin strings are bad, then burn all the classical fiddle records. :) The tone of light strings is just, different. There is a sound you can get from a .008 string that you won't get from a .011 at the same pitch (and vice versa). You still **have** a .011 in that light set; it's just, ahem, down-tuned by a perfect 4th from E to B!
Answer: On some Gibsons/Epiphones, the saddles are triangular in section, as in a right-angled triangle. This means that it is possible to take off the saddle and turn it through 180 degrees, and the point of contact for the string will move back or forwards enough to get the extra adjustment for intonation you require.
Answer: Yes, string gauge DOES affect intonation. If your bridge saddles are as far back as they can go (or a fixed bridge) and your intonation is still a couple of cents sharp, use a .001 or .002 Thinner gauge string to flatten the intonation. Conversely, use a thicker gauge string to automatically Sharpen intonation without moving the saddle(s).
2nd, don't listen to the hogwash above about wound strings having more mass than an equal diameter (gauge) plain string. The Wound string of the same gauge actually has Less Mass than the plain string. The reason is the core string plus the winding around it leaves space, which lowers the net mass of the same gauge wound string.
To prove it for yourself, Try changing a plain .018 string to a wound .018 and you will instantly see that the wound string is Way flat on intonation.
First check, or intonate as accurately as you can, with a Good Tuner. If you are flat on a fixed acoustic saddle, use a slightly thicker string to sharpen it up, and vice versa.
IOW, you can really fine tune intonation with string gauge. You can also make a cheap acoustic sound really good.
The same goes for moveable saddles on electric guitars. If the saddle is as far back as it can go and you're Still sharp, install a slightly smaller gauge string to flatten it a bit. This is for Tweak Freaks who want everything Dead Nuts On.
Then order yourself a custom gauge string set from Guitarstringsonline or somebody like that for replacements. The custom set will cost the same as off-the-shelf sets and your guitar will sing.
Remember, Thinner flattens, Thicker sharpens. And also remember that it's mathematically impossible to perfectly intonate a fretted instrument at every fret on every string. There will always be some dissonance.

Back before the '50's, almost all G strings (3rd) were wound. When electrics became popular, lead players liked to stretch the strings a lot, causing the very thin windings to break on the frets.
The solution was to go to a plain G string, but this required a lot more intonation. That's why you still see wound G's on acoustics with fixed bridge saddles, and why the saddle of a plain G on an electric is much farther back. The plain string of equal gauge has more mass, requiring more compensation.
If you're primarily a lead player and you stretch your strings, use the plain string and accept the intonation and tone penalty. If you're primarily a rhythm player, use a wound G for better tone and intonation. If you're using an acoustic with a fixed bridge saddle, definitely use a wound G.
If you change your electric from a plain to a wound G string you'll need to re-intonate the G saddle by moving it forward almost to the B string saddle. The smallest wound strings are .017 and .018 for electrics, from Ball or Daddario. You don't want to go smaller than that anyway because the outer windings are too thin and fragile.
But once intonated, your wound G will be much better in tune up the neck and the tone will be great. Full and partial chords will be sweet.
Daddario has a regular gauge set with an .018 wound 3rd, EXL 110W, or you can buy individual strings and use your normal gauge set for the rest. -Or just buy a custom set online for the same price.
As you might guess, the whole string gauge/type thing gets really involved with a 12 string. That's also another story.  Another tweak requires nut compensation, which is also a whole 'nother ball game in itself. Enjoy.
Answer: Epiphones electrics have a known problem with intonation on the G string.
I am an acoustic player mostly, and it drives me up the friggin' wall.  Most electric guitar players cannot hear it because they play with high gain, but if you finger pick, you can hear it.
The problem is:  the G string intonates fine at open and 12th fret. But play an "A" at the 2nd fret and it is off- noticeably.
So, my solution was to replace the unwound G string with a wound G string.  Problem solved!  As a mainly acoustic player, this does not bother me in the least. YMMV.
I don't know the technical reasons behind this fix.  I just know it works for me - and it's simple.
Comment: If the wound string is denser, i.e. heavier, the speaking length would be different from that of the plain string. Instead of changing the intonation, you've put the appropriate gauge of string on for the saddle position.
Answer: So... First i would like to address using heaver strings then what was issued with your eppi... Laced up and tuned puts approximately 160 pounds pull on the guitar. Going heavier is going to stress everything including your fingers. "Jimi" went as low as 8's... On a 24.75 scale gibson or chinese Eppi. could be 24,5/8 - 24, 11/16 or 24, 3/4. depending on where it came from... I own a chinese Eppi and it is fine. Changing the saddle is going to change the first fret also. The simplest correction is to tune the g string 15 cents flat (the little triangle on your chromatic tuner). Another tuning option is to set your tuner to 432 and give that a whirl (-15)... The problem is a at the first fret. A problem that is a flaw in the instrument. The guitar is a compromise with strings. The way to correct the problem would be to step the fret on the G at the first fret towards the nut. Has been done. Creates something else to contend with. Tune fifteen flat. Adjust the saddle's - fretting at the twelve. Back the tension off between adjustments. Always tune up. String height is personal. 20 Thousands of an inch of relief in the centre of the scoop (finger board) works good. I hope that this helps.
Answer: To answer the question the OP asked, in most cases heavier gauge strings require moving the saddles away from the nut for proper intonation. So if your saddles are already as far as they will go, you should stick with the same gauge or go to lighter gauge.
Comment: In my experience there is a larger issue in that the saddles should always have room to move either direction if the guitar is constructed correctly and the intonation is done correctly.
Comment: True... unless you are swapping out the neck or bridge hardware, or maybe the guitar was not constructed correctly. I'm presently relocating the bridge by 1/8" on one such ebay mix-n-match myself :P.


Has_Many_Through & Active_Record_Collection_Proxy ERROR

Question: I am new to rails and am working on my first little project
I have 3 models in my rails app :
Restaurant <- (master model)
Menu <- (relates directly to restaurant, restaurant can only have 1 menu)
Items <- (relates directly to menu, menu has many items)
I am having trouble setting up associations & just can't seem to get it right. My Models are as follows :
<code> class Restaurant < ApplicationRecord
  has_one :menu
  has_many :items, through: :menus

class Menu < ApplicationRecord
  belongs_to :restaurant
  has_many :items

class Item < ApplicationRecord
  belongs_to :menu
</code>
When I try to render a partial view on the page by calling the classes I get
"

undefined method `items' for #
  Menu::ActiveRecord_Associations_CollectionProxy:0x3a74d08>

Which I'm doing by :
<code>        <%= render @menus%>
        <%= render @items %>
</code>
I have success displaying the MENU partial, but displaying the items throws up the undefined method error.
Here is my restaurant controller :
<code>  def show
    @menus = Menu.where(:restaurant_id => @restaurant.id)
    @items = Item.where(:menu_id => @menus.id)
  end
</code>
I have spent a lot of time trying to adjust the associations with no luck. Thank you.
Comment: might be in your if statement.  You are calling `@menus` but you want to only be calling one `@menu` to get the items for that specific menu. If you actually have multiple `menus` then you should loop over those and then call `.items` for each instance of `menu`. In this scenario, your `render @items` should probably be `render @menu.items` because from this it doesn't look like `@items` is defined.
Comment: Restaurant Controller = def show @menus = Menu.where(:restaurant_id => @restaurant.id) end
Answer: Try :menu instead of :menus
<code>class Restaurant < ApplicationRecord
  has_one :menu
  has_many :items, through: :menu
</code>


Spring boot Java heap space for downloading large files

Question: I am trying to write a REST api to allow users to download large files (ie > 2GB) on Spring boot. I am hitting with "Java Heap outOfMemoryException". I tried to triage the issue, i see that HttpServetResponse object is of type : ContentCachingResponseWrapper.
This class caches all content written to the output stream and when cached data size becomes around 258MB, i get OutOfMemoryException. Why at 248 MB, because JVM has 256 MB of heap memory.
The default flushBuffer() method in ContentCachingResponseWrapper is empty. If i try to call copyBodyToResponse(), which is used to copy data from cache to stream, it works fine, but it closes the stream as well. This leads to only sending first chunk of data to client.
any suggestions ?
public void myDownloader(HttpServletRequest request, HttpServletResponse response) {
             //response.getClass() is: ContentCachingResponseWrapper
             byte[] buffer = new byte[1048576];  // 1 MB Chunks
             FileInputStream inputStream = new FileInputStream(PATH_TO_SOME_VALID_FILE);
             int bytesRead= 0;
             ServletOutputStream outputStream = response.getOutputStream();

             while ((bytesRead = inputStream.read(buffer)) != -1) {
                 outputStream.write(buffer, 0, bytesRead);
                 outputStream.flush();
                 response.flushBuffer();
               }
}

I get following error:
Caused by: java.lang.OutOfMemoryError: Java heap space
    at org.springframework.util.FastByteArrayOutputStream.addBuffer(FastByteArrayOutputStream.java:303) ~[spring-core-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
    at org.springframework.util.FastByteArrayOutputStream.write(FastByteArrayOutputStream.java:118) ~[spring-core-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
    at org.springframework.web.util.ContentCachingResponseWrapper$ResponseServletOutputStream.write(ContentCachingResponseWrapper.java:239) ~[spring-web-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]

Comment: It's Spring - return a `Resource` and let Spring deal with it. Why are you handling this yourself?
Comment: @borisTheSpider Thanks. Do you mean ResponseEntity, will Spring chunk the resource and send to client ?
Answer: This is a very basic way to download the file, but if you call it from a browser, the browser will display it on screen, and may spin forever (browser problem if you ask me):
@RequestMapping(path = "/downloadLargeFile", method = RequestMethod.GET)
public ResponseEntity<Resource> downloadLargeFile() {
    final File file = new File("c:/large.bin");
    final FileSystemResource resource = new FileSystemResource(file);
    return ResponseEntity.ok().body(resource);
}

So you can include some headers with info about the file, and the browser downloads it to a file in your Downloads directory, and does not spin:
@RequestMapping(path = "/downloadLargeFile2", method = RequestMethod.GET)
public ResponseEntity<Resource> downloadLargeFile2() {
    final HttpHeaders httpHeaders = new HttpHeaders();
    final File file = new File("c:/large.bin");
    final FileSystemResource resource = new FileSystemResource(file);
    httpHeaders.set(HttpHeaders.LAST_MODIFIED, String.valueOf(file.lastModified()));
    httpHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
    httpHeaders.set(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
    return ResponseEntity.ok()
        .headers(httpHeaders)
        .contentLength(file.length())
        .contentType(MediaType.APPLICATION_OCTET_STREAM)
        .body(resource);
}

To chunk the response, use InputStreamResource, and apparently Spring closes the InputStream:
@RequestMapping(path = "/pub/storage/downloadLargeFile4", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadLargeFile4()
    throws Exception {
    final HttpHeaders httpHeaders = new HttpHeaders();
    final File file = new File("c:/large.bin");
    final InputStream inputStream = new FileInputStream(file);
    final InputStreamResource resource = new InputStreamResource(inputStream);
    httpHeaders.set(HttpHeaders.LAST_MODIFIED, String.valueOf(file.lastModified()));
    httpHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
    httpHeaders.set(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
    return ResponseEntity.ok()
        .headers(httpHeaders)
        .contentLength(file.length())
        .contentType(MediaType.APPLICATION_OCTET_STREAM)
        .body(resource);
}

Imports:
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

I also find this thread to be useful:
download a file from Spring boot rest service
Answer: To resolve this issue a better choice is to return ResponseEntity<StreamingResponseBody>, StreamingResponseBodyReturnValueHandler will handle the OutOfMemoryError caused by ShallowEtagHeaderFilter, eg.
@PostMapping("downloadLargeFile")
public ResponseEntity<StreamingResponseBody> test3(HttpServletRequest request, HttpServletResponse response) throws RDOException, FileNotFoundException {
    final HttpHeaders httpHeaders = new HttpHeaders();
    final File file = new File("C:/var/largeFile.zip");
    final InputStream inputStream = new FileInputStream(file);
    httpHeaders.set(HttpHeaders.LAST_MODIFIED, String.valueOf(file.lastModified()));
    httpHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
    httpHeaders.set(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));

    StreamingResponseBody responseBody = outputStream -> {

        int numberOfBytesToWrite;
        byte[] data = new byte[64 * 1024];
        while ((numberOfBytesToWrite = inputStream.read(data, 0, data.length)) != -1) {
            outputStream.write(data, 0, numberOfBytesToWrite);
        }

        inputStream.close();
    };

    return ResponseEntity.ok()
            .headers(httpHeaders)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(responseBody);
}

Answer: I just bumped into a similar issue.
Despite the fact that my controller was returning a FileSystemResource (as shown in the code snippet in the accepted answer from ShortPasta), the whole file was still copied to memory first.
For large files, this caused an OutOfMemory exception.
In my case, it was caused by the ShallowEtagHeaderFilter I'm using to add Etags to my responses. Despite a custom isEligibleForEtag implementation that would return false for the requests for large files, the contents was still written to memory.
The fix was to also replace the doFilterInternal method to indicate for the file download requests that there isn't a need for an Etag and hence also not for content caching:
    ShallowEtagHeaderFilter filter = new ShallowEtagHeaderFilter() {
      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //When not using etag, disable content caching
        if(!shouldUseEtag(request, response)){
          ShallowEtagHeaderFilter.disableContentCaching(request);
        }
        super.doFilterInternal(request, response, filterChain);
      }

      @Override
      protected boolean isEligibleForEtag(
          HttpServletRequest request,
          HttpServletResponse response,
          int responseStatusCode,
          InputStream inputStream
      ) {
        return shouldUseEtag(request,response)
      }

      private boolean shouldUseEtag(HttpServletRequest request,
                                    HttpServletResponse response){
        return !isLargeFileDownload(request);
      }
    };


How to add a link in a menu with query parameters in paths

Question: I want to add this link : resources?field_resources_type_tid_i18n[0]=130 in the main menu
that point to a view with exposed filter.
But When I save my link I just find resources without query parameter
Answer: There are multiple ways to solve this problem.

Use the absolute URL of the page, instead of the Drupal path.
Write a module that provides a menu item via hook_menu(), e.g. for the path resources/field_resources_type_tid_i18n/130. The page callback for the menu item would either redirect to resources?field_resources_type_tid_i18n[0]=130 or serve the desired page directly.
Add a rewrite rule to the webserver configuration, the translates resources/field_resources_type_tid_i18n/130 into index.php?q=resources&field_resources_type_tid_i18n[0]=130 and add resources/field_resources_type_tid_i18n/130 to the menu.

Solution 1 is the most simple, but not very flexible. You need to touch the menu links database table if the absolute URL of the site changes. Adapting the link to the currently used scheme (http:// or https://) is not possible.
I prefer Solution 2, but it requires knowledge about Drupal module development.
I do not like to rely on URL rewriting to provide essential functionality, so I do not recommend Solution 3.
Answer: Case: you have an existing menu block in your structure.
You can add query parameters to existing menu link paths by adding the query option.
(see url())
function (your_module_name)_block_view_alter(&$data, $block) {
  if ($block->delta == "main-menu") {
    $data['content'][601]['#localized_options']['query'] = array('yourqueryparameter' => 'parameters value');
  }
}

For more dynamic code:
... if ($block->delta == "main-menu") {
foreach ($data['content'] as $menu_link){
  if (isset($menu_link['#href']) && $menu_link['#href'] == "Link_of_your_menu_item" ){
    $data['content'][$menu_link['#original_link']['mlid']]['#localized_options']['query'] = array('yourqueryparameter' => 'parameters value');
  }
}


Double counting proof: The number of streets that direct to or away from a place $o$ is $s(o)$

Question: On a map there are $n$ places, that are connected with streets. Every street connects exactly $2$ places. The number of streets that direct to or away from a place $o$ is $s(o)$.
How can one find out the number of streets via Double counting?
Here's what I thought of:
We define the following:
$n$ places, $m$ streets, $O$ is the set of places and $M$ the set of streets.
$$(o,m) \Leftrightarrow m \text{ is on o}  $$
$$s(o*) = \text{Number of streets at one place} = 2$$
$$r(m*) = \text{Number of places at one street} = 2$$
$$\sum_{o* \in O } s(o*) = n \cdot s(o) = n s(o)$$
$$\sum_{m* \in M } r(m*) = m \cdot 2 = 2m$$
$\Rightarrow 2m = n s(o)$
$\Rightarrow m = \frac{ns(o)}{2}$
Is this correct?
Comment: I assume $s(0)$ is the number of streets connected specifically to place $o$ ... and that for different $o$'s you can have different values for $s(o)$. So, you just need to sum the different $s(0)$'s and divide by $2$, rather than assume that $s(o)$ is the same value for all places.
Answer: I assume $s(0)$ is the number of streets connected specifically to place $o$ ... and that for different $o$'s you can have different values for $s(o)$. So, you just need to sum the different $s(0)$'s and divide by $2$, rather than assume that $s(o)$ is the same value for all places. Thus, you get:
$$m = \frac{\sum_{o \in O} s(o)}{2}$$
Answer: If you like graph theory, which this question suggests you might, use a handshaking approach as the indegree + outdegree = degree of a vertex where we are double counting streets.
Or just at each place count all streets add it up and divide by two.


Help with the rhythm of Chopin's C major prelude

Question:

The time signature is 2/8, and the piece is played with triplets but then at bar 17 the top triplet is replaced with a quintuplet with stretto marked above.
I am a bit confused how to play this.
What type of polyrhythm is this? and what does the stretto marking mean in this situation?
Thanks
Answer: TL;DR: This is a 6:5 (left-hand against right-hand) polyrhythm, intended to create rhythmic and metric tension. The stretto reinforces this.

For illustration, here is m. 18:

(IMAGE SOURCE: IMSLP, Mikuli Edition)
The "5" refers to the entire right-hand part, which should be played as five sixteenth notes across the two-beat bar. The notation shown in the video edition is incorrect, which is what makes it confusing.
The effect of the five-tuplet is to create a "slow-motion" feel compared to the double-triplet feel of the preceding measures. There is a sense of rhythmic or metric stretching or delay, and this is strengthened by the stretto marking. Chopin is saying to make these measures a particularly tense or emotionally fraught portion of the Prelude.
NOTE: The left-hand part should remain a triplet. This also assists in creating tension by "arguing" with the right-hand part, trying to pull it forward rhythmically.
The way to know it remains a triplet is the note grouping: 3 sixteenths followed by an eighth rest (two sixteenths). If a five-tuplet were intended, the grouping would follow the right hand's two sixteenths, then three sixteenths (two sixteenths, one sixteenth, eighth rest [or two sixteenth rests, perhaps, for clarity]).


Definite integral with derivative of Heaviside function

Question: I'm working on a problem I have been dealing with unsuccessfully for months now, so any help is greatly appreciated!
The context
I have to solve an integral of the form
$$\begin{align}
 \int_0^{\infty}dy \; \psi\left(\frac{y}{q}\right)\phi(y) \int_{-\infty}^{\infty}\frac{dp}{\sqrt{2\pi}} p^{\gamma} e^{-ip(y-x)}\;,
\end{align}$$
where $\psi$ is square-integrable and $\phi$ is undefined. When $\gamma \in \mathbb{N}$, we can write
$$\begin{align}
 \int_0^{\infty}dy \; \psi\left(\frac{y}{q}\right)\phi(y) \int_{-\infty}^{\infty}\frac{dp}{\sqrt{2\pi}} (-i)^{-\gamma}\partial_{y}^{\gamma} \left[ e^{-ip(y-x)} \right]\;,
\end{align}$$
and we obtain a Dirac delta which, upon integration by parts and discarding the surface terms thanks to $\psi$, helps us getting rid of the integral over $y$ and obtaining an analytic expression in terms of $\phi(x)$, $\psi(x/q)$ and their derivatives. I now want to do the same for $\gamma$ real. For this, I suppose that $\gamma = \nu-\rho$, with $\nu \in \mathbb{N}$ and $0<\rho<1$, because I can express the Fourier transform as
$$\begin{align}
\int_{-\infty}^{\infty}\frac{dp}{\sqrt{2\pi}} p^{\nu-\rho} e^{-ip(y-x)} &= \int_{-\infty}^{\infty}\frac{dp}{\sqrt{2\pi}} p^{-\rho} (-i)^{-\nu} \partial_{y}^{\nu}\left[e^{-ip(y-x)}\right] = i^{\nu}\partial_{y}^{\nu} \left[\int_{-\infty}^{\infty}\frac{dp}{\sqrt{2\pi}} p^{-\rho}  e^{-ip(y-x)}\right] \\
&= i^{\nu-\rho} \partial_{y}^{\nu} \left[ \frac{\sqrt{2\pi}}{\Gamma(\rho)} \frac{H(y-x)}{(y-x)^{1-\rho}} \right] \;,
\end{align}$$
where $H$ is the Heaviside function.
The problem
The trouble starts now, which is why I consider $\nu=1$ for simplicity, so that I have to evaluate an integral of the form
$$\begin{align}
 \int_0^{\infty}dy \;  \psi\left(\frac{y}{q}\right)\phi(y)  \times \partial_y \left[\frac{H(y-x)}{(y-x)^{1-\rho}}\right]\;.
\end{align}$$
Deriving, I obtain
$$ \begin{align}
 \int_0^{\infty} dy \;  \psi\left(\frac{y}{q}\right)\phi(y)  \times \left[\frac{\delta(y-x)}{(y-x)^{1-\rho}} - (1-\rho)\frac{H(y-x)}{(y-x)^{2-\rho}}\right]\;,
\end{align}$$
in which the first term is singular and the second is another Heaviside function. Amazingly, if I define $\psi$ and $\phi$, Mathematica is able to return a function of $x$, even in the presence of this singular term (I have tried with $\phi$ being a polynomial or an exponential), which convinced me that this integral should be solvable somehow (though I have asked a similar question on MathematicaSE here).
Does anybody know how I could get rid of the integral? Also, if somebody knows of an alternative way to treat this problem, that would be awesome!
Many thanks!
Answer: Hint:
I would try to replace the Heaviside function with one of its analytic
approximations
$$
\eqalign{
  & H(x) = \mathop {\lim }\limits_{\varepsilon  \to 0} {1 \over 2}\left( {1 + {x \over {\sqrt {x^{\,2}  + \varepsilon ^{\,2} } }}} \right)  \cr
  & H(x) = \mathop {\lim }\limits_{\varepsilon  \to 0} {1 \over {1 + e^{\, - \,2\,x/\varepsilon } }} \cr}
$$
Putting
$$
{\partial  \over {\partial y}}\left( {{{H(y - x)} \over {\left( {y - x} \right)^{\,1 - r} }}} \right)
 = \left. {{\partial  \over {\partial z}}\left( {{{H\left( z \right)} \over {z^{\,1 - r} }}} \right)}
 \right|_{\,z = y - x}
$$
the first expression would give
$$
\eqalign{
  & \mathop {\lim }\limits_{\varepsilon  \to 0} {\partial  \over {\partial z}}\left( {{{H\left( z \right)}
 \over {z^{\,1 - r} }}} \right) =   \cr
  &  = {{z^{\,r - 1} } \over {2\left( {\sqrt {z^{\,2} } } \right)^3 }}\left( {z + \sqrt {z^{\,2} } } \right)
\left( {\left( {r - 2} \right)z + \sqrt {z^{\,2} } } \right) =   \cr
  &  = {1 \over 2}\left( {\sqrt {z^{\,2} } } \right)^{\,r - 4} \left( {z + \sqrt {z^{\,2} } } \right)
\left( {\left( {r - 2} \right)z + \sqrt {z^{\,2} } } \right) =   \cr
  &  = \left( {r - 1} \right)z^{\,r - 2} H\left( z \right) \cr}
$$
Alternative hint:
Consider that
$$
\eqalign{
  & \int_{y = 0}^\infty  {f(y){{\delta \left( {y - x} \right)} \over {\left( {y - x} \right)^{\,1 - \rho } }}dy}
 \quad  \Rightarrow \quad \mathop {\lim }\limits_{y \to x} {{f(y)} \over {\left( {y - x} \right)^{\,1 - \rho } }}
 \;\left| {\,0 < x} \right.  \cr
  & \int_{y = 0}^\infty  {f(y){{H\left( {y - x} \right)} \over {\left( {y - x} \right)^{\,2 - \rho } }}dy}
 \quad  \Rightarrow \quad \int_{y = x}^\infty  {{{f(y)} \over {\left( {y - x} \right)^{\,2 - \rho } }}}
 \;\left| {\,0 < x} \right. \cr}
$$
with a lot of cautions about formal aspects , obligatory when dealing with distributions.
In particular in the first line there might be the introduction of a $1/2$ factor, depending on the definition of the Heaviside ...
The result of the limit depends on $\rho$ : most probably you are having that both terms $ \to \infty$ and whether their subtraction
leads to a finite result will depend on $f$.