range of notes that can be handled by any symphonic instrument

Question: What range of notes (pitches) can be handled by any instrument in a symphonic orchestra (excluding percussions, of course)?
EDIT:
In other words, I am asking about that core part of instruments' ranges where all of them overlap. I am not even sure if such core part exists. Most likely, piccolo and tuba don't share any notes (pitches) in common.
Comment: It would help people trying to answer, if you can explain _why_ you are asking this question?  What are you hoping to do with an answer?
Comment: @Tim, brilliant: that chart is wrong.  It is trivial to find tuba music that extends well above C4 (middle C).
Comment: Go to Boss TU-12H manual and there is a chart showing just what you ask.
Comment: Well, unsurprisingly, _middle_ C is more or less the point of overlap. If you have no particular reason, middle C is a good enough point to satisfy curiosity.
Comment: Are you asking for a list of ranges for each instrument? If so, the question is likely to be closed.
Comment: @Tim - No. I am asking about that core part of ranges where all the instruments' ranges overlap. I am not even sure if such core part exists. Most likely, piccolo and tuba don't share any notes in common.
Comment: @Tim- Thank you!. I found it here: https://data2.manualslib.com/pdf2/50/4991/499089-boss/tu12h_instruction_manual.pdf?05087de1909aaca2a827a713748162b2   (page 5). So it looks like the common range is, in fact, only one note: A3#, which is the highest for tuba and the lowest for oboe. That, sadly, will exclude flutes (unless a flutist manages to go that low).
Comment: @ElementsinSpace - It's been long my point of curiosity to find out how many pitches all those instruments in a symphonic orchestra share together, but I never got to asking a question about it. Finally, I did it!
Comment: @phoog, the chart is referring to a BBb tuba, not an Eb or F tuba.
Comment: @ElementsinSpace at https://olemiss.edu/lowbrass/studio/routines/instrument/bbbtubalevel2.pdf (pdf) you will find a daily exercise set for university-level BB♭ tuba players that extends up to F4.
Comment: "curiosity to find out how many pitches all those instruments in a symphonic orchestra share together" that just re-states your question. _Why_ do you want to know, why are you curious? It's hard to see a _practical_ value in the overlapping ranges. Sure, such overlaps allow for playing in close position, unisons, thirds, etc. But if you want to do that for various types - wind, brass, string - you can _already_ do that with appropriate choices. Why does it matter that a tuba can't double a piccolo in the same octave, when you can double between octaves or just use unison trumpet and flute.
Comment: @MichaelCurtis - "that just re-states your question" - But that's all I have. Just curiosity without any further practical implementation. It was just that my grandpa once in my childhood took me to a symphonic orchestra concert and, seeing how mesmerized I was by all those various instruments and sounds, said to me that they all have different ranges. At that time I thought to myself that it wouldn't hurt to find out one day if they all yet had at least some notes in common.
Comment: @ElementsinSpace  Have you ever heard the range (high) Maynard Ferguson reaches?  I have no doubt that some wacked-out tuba player could achieve similar ranges
Answer: The answer, if there is one, will depend on how wide a net you cast with the phrase "any symphonic instrument."  If you include the most common instrumentation in a classical orchestra, there may be a small overlap, but many compositions and orchestras include less-common or more-modern instruments that extend the range up and down.
For reference, look at the chart on Wikipedia at Range (music) § Typical ranges.
You can see that it's even possible to have a single section of the orchestra with little-to-no overlap, for example the octocontrabass clarinet and the sopranino clarinet have no overlap.  (Of course it's probably rare to have both of these in the same piece.)  The contrabassoon and oboe have only a couple notes worth of overlap.
Answer: Well, quite obviously there are instruments that do not have overlapping ranges, which is kind of the idea behind having different ranges. To make Mr. Phoog happy here is an example of such: The highest instrument of the typical symphonic orchestra is the piccolo flute, which cannot go lower than a C5. The lowest common instrument would the contrabassoon, whose range is usually considered to go up to C4.
Of course possible way to counter this is by transposing in octaves. This does make a lot of sense as with a change in register you also get changes of colour, dynamic expressibility and such. While it would technically be possible to play a piccolo part on the bass tuba it will not sound good together. Or more reasonably: The bass clarinet can play a lot of clarinet stuff in the original octave, but it will sound differently.
If we were to talk about the individual ranges it is quite safe to assume that most professional instruments have at least a range of 2-2.5 octaves. Of course this then depends: There are instruments such as percussive instruments and keyboard instruments that do have a very specific set of pitches. You do have string instruments where the range is limited above by the length of the fingerboard (although technically you can do harmonics to get more range upwards). You get brass instrument where the range is limited by above only by what you can achieve on your mouthpiece using lip tension. And there are woodwinds, where the upper limits depends on how many overtones you can overblow.
So while brass and woodwinds theoretically do have no upper limits, going higher on these instruments gets really hard quickly. (Also strings do have not theoretical upper limit, using harmonics.)
So we see that most instruments do have a hard lower limit and some sort of soft upper limit, which can be pushed up by technique. This means that technically this "shared range" is only limited by the instrument with the highest lower limit, which would be piccolo. But this is not really reasonable.
Comment: the lowest note on a piccolo flute is D5
Comment: Thank you for this input. Can you, please, explain to me what you mean by "doing harmonics" (or "using harmonics")? It looks like you are talking about some special technique that can produce some very high-pitched sounds, which are normally not produced on a given instrument.
Comment: @brilliant Playing harmonics or *flagolett* on a stringed instrument means playing while touching the string at a node of some harmonic overtone, blocking all but mupltiples of this harmonic. Thus at the middle you get the octave, at a third you get the fifth above the octave, at 1/4 you get two octaves, at 1/5 you get two octaves and a major third, at 1/6 you get two octaves and a fifth, at 1/7 you get two octaves and a natural seventh, at 1/8 you get three octaves, at 1/9 three octaves and a big wholetone and so on. Of course the higher you go the less energy will be there.
Comment: This answer would be improved by naming a specific pair of instruments and specifying their non-overlapping ranges.  As it is, it cannot be verified.
Comment: @phoog What would be the use of that, considering the OP himself gave an example in the question?
Comment: @phoog I've added an example. Happy now?
Comment: @ElementsinSpace Not exactly. Commonly the piccolo flute in C goes down to D5, but there are some models which go down to C5. A low C in the piccolo is called for by Verdi, Mahler, Schönberg, Britten or Strauss, to name a few.
Answer: The range of a bass tuba extends to G4:
https://www.vsl.co.at/en/Bass_tuba/Range
If you consider that a piccolo part can always be required to double (full-sized) flute, then you can write unison passages for your full orchestra in the range C4 to G4.
Comment: This answer does not exactly answer the question. Also the bass tuba is not the lowest common instrument in a symphonic orchestra (unless using pedal tone. The tuba is quite flexible).
Comment: Thank you for this answer. Can you, please, explain what "to double the flute" means? Does it mean to play the exact part, except one octave higher?
Comment: @brilliant "doubling" often means "play the same notes as," whether in the same octave or another or even at some other interval. Here it refers to playing more than one instrument in a single piece. The player's part will specify which instrument to play at which point. See e.g. https://en.wikipedia.org/wiki/Woodwind_doubler and https://www.local802afm.org/allegro/articles/as-a-classical-musician-do-you-know-what-union-scale-really-pays/ ("Doubling: A premium of 20% is paid for the first double, and 10% for each add'l... There are some exclusions, such as: A, Bb and C clarinets, trumpets...")
Comment: @brilliant also e.g. https://en.wikipedia.org/wiki/Symphony_No._6_(Tchaikovsky)#Instrumentation ("3 flutes, the third doubling piccolo").


XStreamAsAttribute not adding as attribute - xstream

Question: I wrote a class which will be converted by xstream into xml .
I added @XStreamAsAttribute to add xmlns as an attribute . But it got added as a nested tag in  the output
My class file is as follows
@XStreamAlias("GetConfigurationParametersResponse")
public class GetConfigurationParametersResponse
    extends BaseResponse
{
    @XStreamAlias("xmlns")
    @XStreamAsAttribute
    final String xmlns = "http://www.collab.net/teamforge/integratedapp";

    @XStreamAlias("xmlns:ns2")
    @XStreamAsAttribute
    final String ns2="http://www.collab.net/teamforge/integratedapp";

    @XStreamImplicit(itemFieldName="ConfigurationParameter")
    protected List<ConfigurationParameter> configurationParameter;

    public List<ConfigurationParameter> getConfigurationParameter() {
        if (configurationParameter == null) {
            configurationParameter = new ArrayList<ConfigurationParameter>();
        }
        return this.configurationParameter;
    }

}

The output for this is as follows
<com.collabnet.teamforge.ia.GetConfigurationParametersResponse>
<xmlns>http://www.collab.net/teamforge/integratedapp</xmlns>
<ns2>http://www.collab.net/teamforge/integratedapp</ns2>
</com.collabnet.teamforge.ia.GetConfigurationParametersResponse>

But I need output as
<com.collabnet.teamforge.ia.GetConfigurationParametersResponse xmlns="http://www.collab.net/teamforge/integratedapp" xmlns:ns2="http://www.collab.net/teamforge/integratedapp">
</com.collabnet.teamforge.ia.GetConfigurationParametersResponse>

Please help in finding out where I am going wrong .
I followed this tutorial http://x-stream.github.io/annotations-tutorial.html
Answer: You probably need to do the following:
xstream.processAnnotations(GetConfigurationParametersResponse.class);

If only the following is being called:
 xstream.processAnnotations(BaseResponse.class);

Then you could use the @XStreamInclude annotation on BaseResponse as follows:
@XStreamInclude({GetConfigurationParametersResponse.class})
public class BaseResponse {
}

Comment: How can you apply `xstream.processAnnotations` in a Restlet application? First how do you get that `xstream` instant out of the configured converters?
Comment: Also, maybe you can share some idea with this Restlet issue: https://stackoverflow.com/questions/66794041/using-xstream-extension-with-swagger-instead-of-jackson
Answer: What worked for me was:
xstream.autodetectAnnotations(true);


storing arrays into database

Question: How do we store arrays in database?
What I am doing is the following:
// $data is an array
$v = base64_encode(json_encode($data));

$todo = 'INSERT INTO table (data) VALUES("' . $v . '")';
$sql = mysql_query($todo);

Also why do I have to call base64_encode before I store the array in the database?
Comment: Who said you had to use `base64_encode` to store it in the database? What's wrong with just doing a `json_encode`, or even `serialize`?
Comment: Generally is not good to store array into database. What are you looking after?
Answer: What you are doing is possibly wrong. There are many decisions you have made that are not by any means necessary, and they may also not be appropriate.
For one thing, storing "frozen" arrays in the database is usually a bad idea because you cannot do anything with them other than get them back (you cannot modify them or query based on their contents). Solutions that "fix" this issue are database-oriented and include changing your table schema. I don't know what you are trying to do so I won't go in more detail.
Then, if you do want to serialize arrays in your database (there are legitimate use cases) (edit: and only intend to access them through PHP code -- as was very correctly pointed out!), the only thing you should be using is the serialize function -- not json_encode or anything else. This is the very reason that function exists. When you get the values back from the database, use deserialize to get the array back.
Finally, when injecting a variable into an SQL query, you need to escape it with mysql_real_escape_string (which you are not doing).
So it would be much better to do:
$sql = sprintf('INSERT INTO table (data) VALUES(\'%s\')',
               mysql_real_escape_string(serialize($data)));
$result = mysql_query($sql);

Comment: @yi_H: I do say "usually" and "there are legitimate use cases".
Comment: It's not necessarily wrong, it's fine if you don't want to retrieve/search individual values in the array.
Comment: I'm not sure I agree with that.  Without knowing the purpose behind what he's doing, saying this way is much better may not be accurate.  Maybe what is really needed is a `split()` of the array, and storing data elements into rows.
Comment: why do you think serialize is superior? At least json doesn't tie you to a PHP backend.
Comment: @JeremyHolovacs: I believe the first paragraph covers exactly that.
Comment: @yi_H: That's totally correct, I was assuming that there is only going to be the PHP backend. Edited the question to point that out. Thank you.
Comment: Serializing as XML would usually be my first choice, but JSON is a little more lightweight.
Comment: @Jon, my issue was with your first paragraph, specifically "wrong on many levels"... it may be, and I don't disagree that there are some attractive alternatives, but it could be that it isn't wrong at all, just ugly and non-performant.
Comment: @JeremyHolovacs: Fair enough. Edited; this should be an improvement.
Answer: You don't have to call base64_encode, but you have to escape the value with mysql_real_escape_string.
Answer: You don't need to call base64_encode().  json_encode() will already be a string... of course you are limited to UTF-8 encoded values in $data.
This is a legitimate way to store an array, although you could consider a table to be an array and store one value per row.  Additionally, you could store your data as an XML string, or even CSV/ TSV if your data contents didn't interefere with the delimiters.
Bottom line, it really depends on the situation you're in.  From the code you've presented, this will work, but if you want it to work well/ better, more information will definitely be needed.
NOTE: Sanitize your data before inputting into the database!
Answer: Naturally you don't store arrays in a relational database.
Getting a base64 from your array seems to be a trick so that you can store a string in the database.
Comment: There are legitimate reasons to store arrays in a database. Not many, but they do exist.
Comment: @George Cummins I didn't say that there a reasons against it. However databases usually don't directly support array field types.
Comment: Indeed, tables *are* arrays of data (rows), and that tends to get a bit "meta" when querying.  However, if the data is just to be stored and not queried against, it is a legitimate use case.

storing arrays into database


Why does my pattern extractor code return false positives?

Question: My goal was to extract the sequence of "Antimicrobial Peptides" from the NCBI Database using keywords such as "Antimicrobial Peptides, AMPs" and also specifying its length.
I have written a code to extract the sequences of Antimicrobial Peptides (AMPs) from the NCBI protein database using the Biopython library.
The Code
from Bio import Entrez
from Bio import SeqIO

def scrape_fasta_sequence(keywords):
    # Provide your email address to NCBI
    Entrez.email = 'firstname.lastname@example.com'

    # Create the query string with filters
    query = f'{keywords} AND srcdb_refseq[PROP] AND 7:50[SLEN] '

    # Search for protein IDs that match the query
    handle = Entrez.esearch(db='protein', term=query)
    record = Entrez.read(handle)
    id_list = record['IdList']

    # Use the protein IDs to fetch the sequences
    fasta_sequences = []
    for protein_id in id_list:
        handle = Entrez.efetch(db='protein', id=protein_id, rettype='fasta', retmode='text')
        fasta_sequence = SeqIO.read(handle, 'fasta')
        fasta_sequences.append(fasta_sequence)
        handle.close()

    return fasta_sequences

# Example usage
keywords = 'Antimicrobial Peptides OR AMPs'
fasta_sequences = scrape_fasta_sequence(keywords)
for fasta_sequence in fasta_sequences:
    print(fasta_sequence)

Output
Output was not specific to the Antimicrobial Peptides. It provided me with other proteins which were not needed.
output snippet
Kindly help, if code can be modified to add precision only towards antimicrobial peptides.
Comment: Please avoid attaching output as images, use code blocks instead.
Comment: [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551)
Answer: You might want to add a more specific filter to target Antimicrobial Peptides (AMPs). One way to do this is by specifying the source organism or using a specific keyword related to AMPs.
Here's an updated version of your code with an added filter for the source organism (bacteria, for example) and a specific keyword related to AMPs:
from Bio import Entrez
from Bio import SeqIO

def scrape_fasta_sequence(keywords):
    # Provide your email address to NCBI
    Entrez.email = 'email@example.com'

    # Create the query string with filters
    query = f'{keywords} AND srcdb_refseq[PROP] AND 7:50[SLEN] AND bacteria[ORGN]'

    # Search for protein IDs that match the query
    handle = Entrez.esearch(db='protein', term=query)
    record = Entrez.read(handle)
    id_list = record['IdList']

    # Use the protein IDs to fetch the sequences
    fasta_sequences = []
    for protein_id in id_list:
        handle = Entrez.efetch(db='protein', id=protein_id, rettype='fasta', retmode='text')
        fasta_sequence = SeqIO.read(handle, 'fasta')
        fasta_sequences.append(fasta_sequence)
        handle.close()

    return fasta_sequences

# Example usage
keywords = 'Antimicrobial Peptides OR AMPs'
fasta_sequences = scrape_fasta_sequence(keywords)
for fasta_sequence in fasta_sequences:
    print(fasta_sequence)

So output will be
ID: WP_328102937.1
Name: WP_328102937.1
Description: WP_328102937.1 acinetodin/klebsidin/J25 family lasso peptide, partial [Escherichia marmotae]
Number of features: 0
Seq('IFHLLKEDYINKKSASQLTKGGEVHVPEYFAGIGTPISFCG')
ID: WP_328101564.1
Name: WP_328101564.1
Description: WP_328101564.1 acinetodin/klebsidin/J25 family lasso peptide, partial [Escherichia marmotae]
Number of features: 0
Seq('KKSASQLTKGGEVHVPEYFAGIGTPISFCG')
....
....
and so on


Usando uma prop de um objeto como key em outro objeto em TS

Question: Estou tentando exportar um objeto com meus tipos válidos e criar um type baseado nisso. Até aí tudo bem, o problema é a interface que espera uma string mas não está aceitando a prop do objeto (que é uma string) como válida.
export const SortValues = {
  NEWER: 'NEWER',
  OLDER: 'OLDER',
  NAME_ASC: 'NAME_ASC',
  NAME_DESC: 'NAME_DESC',
}

interface Option<T = string> {
  key: T;
  value: string;
}

type SortValuesType = keyof typeof SortValues;

// type SortValuesType = 'NEWER' | 'OLDER' | 'NAME_ASC' | 'NAME_DESC'; // Não funciona também.

export const options: Array<Option<SortValuesType>> = [
  { key: SortValues.NEWER, value: 'Mais novos' },
  { key: SortValues.OLDER, value: 'Mais antigos' },
  { key: SortValues.NAME_ASC, value: 'A - Z' },
  { key: SortValues.NAME_DESC, value: 'Z - A' },
];

Estou recebendo o erro "Type 'string' is not assignable to type '"NEWER" | "OLDER" | "NAME_ASC" | "NAME_DESC"'." na propriedade key das options.
Funciona se eu declarar SortValues como um enum, portém isso está me causando problemas em outros lugares, então eu queria mesmo exportar as opções válidas como um objeto.
Aqui está um snippet com o código em questão.
https://codesandbox.io/s/fqide
Comment: Bem vindo ao Stack Overflow em Português. Por favor, clique em [editar](https://pt.stackoverflow.com/posts/418963/edit) e traduza a pergunta.
Comment: @LuizAugusto Feito, vacilei na hora de postar. Não reparei que estava no pt-br. Mal aê.
Answer: O problema é que você está declarando SortValues como objeto em linha e está tentando utilizar suas propriedades como se fossem tipos.
Eu acho que o que você está procurando é uma enumeração, documentada aqui e aqui.
Na documentação está escrito:

...quando todos os membros de uma enumeração têm valores literais, uma
  semântica especial é aplicada.
A primeira é que os membros da enum também se tornam tipos! Por
  exemplo, podemos dizer que determinados membros podem ter apenas o
  valor de um membro enum...

Que ao meu ver se encaixa com que está tentando fazer.
// Não é mais um objeto agora é uma enumeração
export enum SortValues {
  NEWER = 'NEWER',
  OLDER = 'OLDER',
  NAME_ASC ='NAME_ASC',
  NAME_DESC = 'NAME_DESC',
}

// A chave teve o tipo adequado para enumeração
interface Option<T = SortValues> {
  key: T;
  value: string;
}

type SortValuesType = keyof typeof SortValues;

//Agora as chaves podem ser valoradas de acordo com os membros da enumeração SortValues
export const options: Array<Option<SortValuesType>> = [
  { key: SortValues.NEWER  , value: 'Mais novos' },
  { key: SortValues.OLDER, value: 'Mais antigos' },
  { key: SortValues.NAME_ASC, value: 'A - Z' },
  { key: SortValues.NAME_DESC, value: 'Z - A' },
];

PS: Não sei exatamente o que está fazendo mas acho que esse fragmento:
type SortValuesType = keyof typeof SortValues;

export const options: Array<Option<SortValuesType>> = [
  { key: SortValues.NEWER  , value: 'Mais novos' },
  { key: SortValues.OLDER, value: 'Mais antigos' },
  { key: SortValues.NAME_ASC, value: 'A - Z' },
  { key: SortValues.NAME_DESC, value: 'Z - A' },
];

pode ser simplificado:
//type SortValuesType = keyof typeof SortValues;

export const options: Array<Option> = [
  { key: SortValues.NEWER  , value: 'Mais novos' },
  { key: SortValues.OLDER, value: 'Mais antigos' },
  { key: SortValues.NAME_ASC, value: 'A - Z' },
  { key: SortValues.NAME_DESC, value: 'Z - A' },
];


AVAudioPlayer not working anymore

Question: This program was working before and I do not believe I changed anything. Here is the code. I get the thrown error : file not found: bgMusic
<code>import SpriteKit
import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {

    var backgroundMusicPlayer = AVAudioPlayer()

    func playBackgroundMusic(filename: String) {
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
        guard let newURL = url else {
            print("Could not find file: \(filename)")
            return
        }
        do {
            backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
            backgroundMusicPlayer.numberOfLoops = -1
            backgroundMusicPlayer.prepareToPlay()
            backgroundMusicPlayer.play()
        } catch let error as NSError {
            print(error.description)
        }
    }

    override init(size: CGSize) {
        super.init(size: size)

        playBackgroundMusic("bgMusic")
}
</code>
Answer: Try getting the file path instead. This works for me everytime.
<code>//Change 'ofType' to whatever the file type is. (.m4a, .mp3, etc.)
let path = NSBundle.mainBundle().pathForResource(filename, ofType: ".mp3")
let url = NSURL.fileURLWithPath(path!)
</code>
Then load the url into the AVAudioPlayer.
If that doesn't work, then make sure the filename is correct and that it is added into your project. Best of luck!
Comment: " Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?" This is on the second line
Comment: Unwrap the optional by adding '!' after path. It should be safe to assume your file is there if you added it. If it crashes, then your file is probably not in the project correctly or the filename is wrong.

AVAudioPlayer not working anymore


Create a webview link on Bubblebottombar flutter

Question: I would appreciate your help, I am trying to create a link in the menu of my app, the link would be to open my YouTube channel through webview, can someone tell me how it is possible? Thanks a lot
dasboardactivity.dart
<code> Widget build(BuildContext context) {
return Scaffold(
  body: Container(
    child: Center(
      child: getView(currentPage),
    ),
  ),
  bottomNavigationBar: BubbleBottomBar(
    opacity: .2,
    currentIndex: currentPage,
    backgroundColor: appStore.appBarColor,
    elevation: 8,
    onTap: changePage,
    hasNotch: false,
    hasInk: true,
    inkColor: appStore.appColorPrimaryLightColor,
    items: <BubbleBottomBarItem>[
      tab("home-run.png", keyString(context, "title_bookStore")),
      tab(
          "librarysolid.png",
          isLoginIn
              ? keyString(context, "title_myLibrary")
              : keyString(context, "lbl_categories")),
      tab("search.png", keyString(context, "title_search")),
      tab("user.png", keyString(context, "title_account")),
    ],
  ),
);
</code>
}
Answer: You can resolve with flutter webview package
<code>Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: Stack(
        children: <Widget>[
          WebView(
            initialUrl: this.url,
            javascriptMode: JavascriptMode.unrestricted,
            onPageFinished: (finish) {
              setState(() {
                isLoading = false;
              });
            },
          ),
          isLoading
              ? Center(
                  child: CircularProgressIndicator(),
                )
              : Stack(),
        ],
      ),
    );
  }
</code>
You can use an Stack in order to place it wherever you need it


Is there a geometry where the distance between two points can be complex?

Question: This tweet contained this image which is of course complete nonsense but it got me thinking -- is there such a thing where the distance of two points is a complex number?

Ps. it seems such questions are fit for this SE for example Can there be a geometry where angles can be infinite?
Comment: If by "distance" you mean metric, then no: a metric is by definition real valued
Answer: Akbar Azam, Brian Fisher & M. Khan (2011) Common Fixed Point Theorems in Complex Valued Metric Spaces, Numerical Functional Analysis and Optimization, 32:3, 243-253, DOI: 10.1080/01630563.2011.533046

We introduce complex valued metric spaces and obtain sufficient conditions for the existence of common fixed points of a pair of mappings satisfying contractive type conditions.

While I can't find this paper freely available online, this PDF cites it and defines " XxX→C is called a complex valued b-metric":
Comment: Fair enough, I deleted my comment. That's the trouble with words, you get these "eats shoots and leaves" problems.
Answer: There can be no such metric, as it would not obey the requirements of a metric.  Specifically, you must be able to have the "$>$" operation (for the triangle inequality: $d(a,b) + d(b,c) \geq d(a,c)$), and that does not hold for complex numbers.
Comment: -1: the question doesn't even contain the word "metric". And you could apply your answer to the word "measure", yet complex and even operator-valued measures are a thing (and a useful one!).
Comment: @MartinArgerami:  "distance" implies the *metric*, for instance "Euclidean distance" is a direct result of a "Euclidean metric."  Any distance must obey the rules of a metric:  $d(x,x) = 0$, $d(x,y) = d(y,x)$, and $d(x,y) + d(y,z) \geq d(x,z)$.  Look it up.
Comment: @MartinArgerami is there a complex valued measure on the one dimensional Euclidean space ?
Comment: Yes, lots.$\ \ $
Answer: A distance is always a real number, for reasons given in other answers. It is only when the angle is also introduced to make it a vector that things get complex. For example the shortest distance from one point to another is a real number, but the shortest path is a vector and may prove to be complex.


Unity SteamVR Controller Initialization Issue on Build

Question: So I've created a game that functions perfectly in the editor, however when I build it, it throws me a NullReferenceException error. The Log tells me it is within the Initialize() function but since it is only an issue on build I don't
really have any clue on how to fix it. I dont know what would be different between the build and the editor so I don't know how to bug test it effectively.
Unity begins to initialize the controllers, but then throws this massive block of errors.
[SteamVR] System.NullReferenceException: Object reference not set to an instance of an object.
  at Valve.VR.SteamVR_Input.Initialize (System.Boolean force) [0x00039] in E:\Repos\Mors Oculus\Assets\SteamVR\Input\SteamVR_Input.cs:166
  at Valve.VR.SteamVR.CreateInstance () [0x000e7] in E:\Repos\Mors Oculus\Assets\SteamVR\Scripts\SteamVR.cs:207
  at Valve.VR.SteamVR.Initialize (System.Boolean forceUnityVRMode) [0x00023] in E:\Repos\Mors Oculus\Assets\SteamVR\Scripts\SteamVR.cs:103
  at Valve.VR.SteamVR_Behaviour_Pose.OnEnable () [0x00002] in E:\Repos\Mors Oculus\Assets\SteamVR\Input\SteamVR_Behaviour_Pose.cs:88
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:LogError(Object)
Valve.VR.SteamVR:CreateInstance() (at E:\Repos\Mors Oculus\Assets\SteamVR\Scripts\SteamVR.cs:217)
Valve.VR.SteamVR:Initialize(Boolean) (at E:\Repos\Mors Oculus\Assets\SteamVR\Scripts\SteamVR.cs:103)
Valve.VR.SteamVR_Behaviour_Pose:OnEnable() (at E:\Repos\Mors Oculus\Assets\SteamVR\Input\SteamVR_Behaviour_Pose.cs:88)

I don't really know what to change. Does anyone have any ideas?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: I replaced the entire SteamVR_Input folder with a fresh one and it worked.


Compare the number of comparisons used by the insertion sort to sort the list $ 7, 4, 3, 8, 1, 5, 4, 2$.

Question: Compare the number of comparisons used by the insertion sort to sort the list $ 7, 4, 3, 8, 1, 5, 4, 2$? I found that based on the following pseudocode for the algorithm:
<code>/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (i = 1; i < n; i++)
    {
        key = arr[i];
        j = i - 1;

        /* Move elements of arr[0..i-1], that are
        greater than key, to one position ahead
        of their current position */
        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}
</code>
The total should be starting from phase 1 that begins with 4 and 7 is: $1+2+0+4+3+4+7$, but the correct answer should be $1+1+3+1+4+3+2=15$, can you please explain why we need 15?
My solution:
Phase 1: compare 4 with 7 needs 1.
Phase 2: compare 3 with 7 with 3 with 4 needs 2.
Phase 3: compare 8 with 7 needs 1.
Phase 4: compare 1 with 8 with 7 with 4 with 3 needs 4.
...etc
Answer: For your answer $1+2+0+4+3+4+7$, I think that $0$ should be a $1$. Other than that, your answer looks good to me. It might be worthwhile to discuss with your instructor.
Comment: It sounds like maybe there is an error in his solutions manual, or he has a different convention as to what constitutes a comparison. I'm not overly familiar with what he does here, so I'm hesitant to speak about it.
Comment: This is based on Kenneth book's solution manual indeed. Thanks anyway.


What kind of effect does practicing on difficult-to-play instruments have?

Question: To clarify the title, I'm not asking if it helps your mandolin skills to play violin (or vice versa, whichever you feel is "more difficult").
Let's say you are a guitarist: Does it help or hurt to practice on a really difficult to play guitar? For example, one with horrible action where you have to press down very hard with your fret fingers.
I've always been of the opinion that it helps your performance because of how good it feels to go from a crappy instrument to a good one. However, that might be purely psychological, and in fact playing the "worse" guitar might lead to bad habits.
I've noticed the same thing about playing drums: going from practicing on a crappy drum kit and then playing a nice one makes you feel like your skills have instantly improved. For example on the bad kit, I have to hit the snare dead-center to get a good sound. On the good kit it seems like it doesn't matter where I play it - it always sounds good.
I'm teaching myself to play piano, and I'm purposely using one with really "tight", difficult to press keys for practice.
I'm aware of how general this question is, but is there any evidence or accepted opinion about this?
Answer: When you practice playing an instrument, you are practicing playing that particular instrument.
If you were a brass player, for example, you would NEVER want to spend all of your time practicing on a crappy instrument with wonky tuning and then do the gig on your $3,000 horn. Even if you sound pretty good on the crap instrument, you would be changing too many variables when switching, and you'd likely sound worse. For most instruments, that is, those that you carry with you wherever you go, you should practice on the instrument you want to perform on.
Piano is a different story, since most pianists will not take their instrument with them when they travel. For this reason, pianists must be able to adapt to the instrument they will be performing on with little or no warmup time. In fact, pianists in conservatory will have a few dozen different practice rooms to choose from, and will sign up for time on a variety of pianos each week to stay agile and not get too used to one particular instrument's action or feel.

Now, my first comment about wind instruments is specifically geared towards practicing for performance or recital. If you are just practicing in general and have a few different instruments to choose from, there's no harm in switching around--there will probably be different techniques that are more evident on different instruments, and that can be useful for practice.
A few guitar-specific things I thought of: playing an instrument with a scalloped fretboard, as long as you're staying alert to your tuning, can be great training for your ear and finger dexterity. Playing an instrument with tightly-strung heavy gauge strings will improve your finger strength. Just switch back and forth from your nylon string to your steel string regularly so you don't forget the lighter touch necessary to play the nylon string properly (without being out of tune from mashing the strings too hard).
What I strongly recommend AGAINST doing is practicing on an instrument that is in disrepair just because it is more difficult to play. That is NOT going to help you, except to develop bad habits to compensate for the instrument.
What constitutes disrepair? Any mechanical part that does not move cleanly when it is supposed to, I would consider to be in disrepair. This includes stuck tuning slides, sticky valves, sticking pads, sticking keys or dampers, connectors or fasteners that are stuck in place. If an instrument cannot be tuned to pitch any longer, I would consider it to be in disrepair. For your 'guitar with terrible action' question, I would say if the action can be improved, by all means do so; otherwise the instrument has likely reached the end of its usable lifespan.
TL;DR: If you're a pianist, be able to play on whatever instrument you find yourself in front of. For everyone else, practice for performance on the instrument you plan to perform on, and never play instruments that don't work properly.
Comment: I appreciate this fantastic answer, it shows a good deal of insight into what I was thinking. I am indeed practicing on instruments that are in some state of disrepair, on purpose, to make practicing more of a challenge (sadly, including out of tune piano). I kind of figured "Hey, if I can sound good on this piece of crap I'll sound *great* on a real one". In some ways it's true, but it's probably not helping in reality - just in my own mind.
Comment: non music example: when playing pool, it helps to play with a table with very narrow holes because you become a lot more precise. but I can't think of any case where a crappy instrument would help. There are other 'artificial handicaps' that help, such as don't look at what your hands do, play guitar while walking around or doing something else, etc.. those do help.
Comment: Maybe the pool analogy here would be playing on a pool table that's not level.  It makes everything harder, but not in a useful way for training.
Answer: If you play on a very badly set up guitar with thick strings, you will get certain "low level" benefits like better strength and calluses. (Or, on the contrary, end up injured.)
A poor guitar's bad intonation and tuning stability will stunt the development of your sense of pitch. An instrument's poor tone will not lead you to appreciate the production of a good tone.
If the poor instrument limits how nimbly you can play notes, yet you doggedly persevere on that instrument, you will not be suddenly nimble when you switch to a proper instrument. The poor instrument will stunt your progress, because it will interfere with your ability to train your brain. As months turn to years, you will fall behind where you could have been with a proper instrument.
Deftness in music performance begins with the brain and spinal column, but how it gets there during rehearsal is via the fingers. The brain needs the fingers to execute its idea, at the desired speed. And that must be repeated so that the phrases you are rehearsing are promoted out of the conscious brain into the subsconcious. If the fingers cannot execute what the brain wants to hear, then this cycle of practice is broken. Therefore, a poor instrument hampers the quality of your practice.

Say, if you want to run a fast 10K footrace, do you think it would be wise to do all
  your training with a 70 pound backpack, and in combat boots? Experiments like that
  have been carried out and confirm that excess weight and handicaps spoil a runner's
  economy. There is an increase in fitness which doesn't translate to speed because
  the muscles have learned new motions which compensate for the baggage. A few weeks of
  training without the baggage are needed to recover the running economy and reap the
  benefit from the loaded-down training. Similarly, it may be beneficial to pick up
  a hard-to-play guitar from time to time, just for strength. Electric guitarists can
  benefit from sometimes picking up an acoustic guitar whose strings are a couple of
  gauges heavier.

Pro musicians who are widely acclaimed for their skill all have playable, well set-up instruments. Legends like "such and such virtuoso guitar player uses bridge cables which are a foot off the neck" are just that: legends. Don't buy into the nonsense.
Lastly, that old adage "`tis a poor musician who blames his instrument" contains an important key phrase: "his instrument". If you can shred on your well-made and adjusted instrument, but suck on someone else's poor instrument, the adage does not apply, because it is not your instrument.  This adage has a flipside: the poor musician who blames his instrument is actually right in that his problems really are caused by the instrument, but plodding along with that instrument is part of what makes him a poor musician.
Comment: I agree - I occasionally practice on a guitar with an incredibly heavy action - and I can feel it help when I go back to my light ones. It builds up a bit of finger strength.
Answer: I think you have to take each instrument case by case. I definitely think every pianist should have experience on pianos with different weighting. However, if playing on a not-so-great instrument forces you to form bad habits, these will transfer over to a good instrument and make it sound horrible. A little adaption is good and sometimes necessary, because one is then more prepared to play other instruments. A piano with difficult-to-press-keys can force you to always hit the keys harder. Playing pianissimo will then be difficult when you go back to a better piano. A really bad instrument is often more detrimental than beneficial because of the habits it forms. Per the comments, a good drummer should try to hit the center. If a particular snare forces you to hit the center, it will enhance your technique (disclaimer-- I am not a drummer).
I'm not sure about your guitar example, though (I don't play myself). Many cheap or badly made wind instruments can force the musician to blow to hard. This can give them stronger lungs, but it will also decrease the amount one learns in that period because of always running out of breath.
My conclusion is that a little worse is not all that bad. In fact, it can sometimes be beneficial, more so with some cases than with others. Sometimes it will make your abilities stagnate. If you go to the extreme and get a barely functional instrument, it will definitely be detrimental to your technique.
Comment: Yeah I feared the question was too general, but nonetheless this makes sense to me. Although there is some getting used to going from the "difficult" piano to the "easy/good" one, it seems like it only takes a minute or two to get control. As far as the snare thing, in *general* you want to hit as close to center as possible so it actually helped quite a bit. Your wind instrument example, to me, seems like a good thing because it helps your endurance (which, I would assume, is part of the goal of practicing - but I don't play any so I'm not sure how much this matters).
Comment: You have some good points. I wasn't sure about the snare thing - only limited experience watching drummers. The wind instrument example, however, is from personal experience. When you have to concentrate too much one the problem, you can't focus on learning. That and bad technique can be the worst problems with playing not-so-great instruments.
Comment: Probably important to have a piano that's in tune too - other wise your relative pitch might not develop well. That's perhaps not so important on instruments with smooth changes between tones (ie. unfretted like a double bass, or with a slide, lieka trombone - is there a word for that?), where you have to learn relative pitch if you want to play the instrument at all.
Comment: @naught101: That's a great point that I actually didn't consider.
Answer: From my experience, it depends very much on the instrument.
I experience the very same thing on drums as you describe, I play my kit at home, then play someone else's (who is a much better and more developed drummer than I am) and I suddenly feel much more advanced playing on his beautiful snare, shimmering cymbals and booming toms.
However, playing guitars are different. Because guitar playing is much more personal to you, you need to get used to the feel on the instrument, as you are having a lot more precise contact with it. Therefore practising on different instruments can have an effect on your playing (or that's what I've found).
Take my situation. I appreciate acoustic and electric guitars are in no way the same, both stylistically and musically, but the differing feel and set-up of the different instruments helps me to illustrate my point. I have an acoustic in my room, and play electric when I have time, in the shed outside (stops my family complaining). My acoustic is a Yamaha, with heavy strings and a moderately high action. My electric has a much lower action, with lighter D'addarios. I play my acoustic whenever I am at a loose end in my room, practising solos, tricky songs and riffs on it (often ones that were written for an electric). I them play them on my Tele, and find I have a lot more difficulty playing them at correct speed without mistakes.
I put this down to my fingers being used to applying more pressure and firmness to the strings on my acoustic; when I transfer to electric, that pressure and firmness is not required as much, therefore my fingers slip, and I'm feeling tense when playing.
As a result, I'm currently looking into purchasing a semi-hollowbody guitar, and fitting heavier strings, to give it more the feel of an acoustic.
Regarding your original question, I think going from a bad instrument to a good one is different from going from a good one to a bad. Learning on a difficult one means you have to develop habits in order to play it well, which may not transfer over to a better set-up instrument very well.
I find on bass, it's somewhere in-between, I can play other people's instruments fine, but I prefer playing my own, feeling much more at home, and therefore my playing improves. As Stephen says, it's your baby.
Because on guitars, there are so many things that can vary; action, string gauge, fretboard feel, neck radius, string spacing, therefore when you get settled on one particular combination, you have to deal with adjusting to another combination as well as playing your stuff on the new instrument, hence your playing will change (and in my case suffer!).
Ok, essay over, just a collection of my thoughts, as I am considering this topic a lot more recently due to my current guitar plans that I mentioned. Thanks for listening!
Answer: If you are going to play a classic acoustic nylon guitar forever, there's no need to ever practice on a steel 12-string. In the extreme case it might even make the musculature of your fingers more coarse and decrease your dexterity.
At the same time, the rich sound of the 12-string might also increase your awareness of tone and also your ability to express yourself musically.
Play the instruments you enjoy. Explore new instruments occasionally.
Answer: I'm teaching myself to play piano, and I'm purposely using one with really "tight", difficult to press keys for practice.
I don't think you are doing yourself much of a favor with that.  Piano playing is more than striking the right keys at the right time: the piano is a much more expressive instrument than, say, a harpsichord.  A good player can work with different phrasing and subtle in-voice and in-phrase dynamics in order to arrive at a transparent and emotional rendition of a piece.  That's a major part of what piano playing is about.
An instrument that offers unreliable or inconsistent response and forces you to keep away from light play will actively keep you from developing the finer points of expressivity and playing, leaving you with the kind of "robust" piano play one often hears from teeth-bristling mothers accompanying their young on some solo instrument.
Answer: i dunno about real evidence, but opinion wise...  unless you NEED to go around playing a bunch of different instruments, I'd suggest you get ONE that is ALL your's.  Your baby.  There should be a tight bond between human and instrument, IMO.  I play piano, and I don't really care how I sound on other peoples'.  I care how I sound on mine.  Therefor, it's a stage type of digital.  I don't yet gig, but hope to some day.
Comment: I disagree. Adaptability is an important quality of a musician.
Comment: when you say "small keys" you don't mean the terrible "mini" sized keys on toy digitals, do you?  You just mean fewer than 88 keys I hope.  I can go along with adaptability being important.  But so's the bond between player and instrument.
Comment: Well for one thing, I noticed that practicing on a lightweight keyboard with small keys required some extra effort when I wanted to play the same thing on a regular piano. Then the opposite, going from playing piano back to the keyboard, made it seem like a piece of cake. Currently I have no less than 4 pianos that I play, because I can't exactly move them around at will.
Comment: No I didn't mean the "toy" keyboards for little kids, I meant a regular keyboard (as opposed to a digital piano) where the keys aren't quite as wide and aren't weighted. Although I do love those little mini Casios from the 80's ^_^
Comment: If you go from a piano to a "plastic touch" synthesizer, it may be the case that there is less effort, but your timing will be off. Although the action of pianos is "heavy", in a sense, it is not the same as an unplayable guitar. Astonishing levels of virtuosity are achieved on pianos.


Proving a linear map from a finite dimensional vector space is continuous, without analysis?

Question: On page 93 in Introduction to Analysis by Maxwell Rosenlicht, Problem 22 tasks one with the following:

Let $V, V'$ be normed vector spaces and $f: V \to V'$ a linear transformation.  Prove the following statements.
(a) If $f$ is continuous at one point it is continuous everywhere, and in fact is uniformly continuous.
(b) $f$ is continuous iff the set $\{ \| f(x)\|/\|x\| : x \in V, x\neq 0 \}$ is bounded.
(c) $f$ is continuous if $V$ is finite dimensional. (Hint: Use a basis of $V$.)
(d) The set of all infinite sequences of real numbers with only a finite number of nonzero terms is a normed vector space if we define $$ (x_1, x_2, x_3, \ldots) + (y_1, y_2, y_3, \ldots) = (x_1+y_1, x_2+y_2, x_3 + y_3, \ldots) \\ c(x_1,x_2,x_3,\ldots) = (cx_1, cx_2, cx_3, \ldots) \\ \| (x_1, x_2, x_3, \ldots)\| = \max \{ |x_1|, |x_2|, |x_3|, \ldots \} $$
and the map sending $(x_1, x_2, x_3, \ldots)$ into $(x_1, 2x_2, 3x_3, \ldots)$ is a one-one linear transformation of this normed vector space onto itself that is not continuous.

I am focusing here on (c) in Problem 22. In short my solution went along the lines of:

Let $\|\cdot \|$ denote the abstract norm on $V$. Let $\{v_1, \ldots, v_n\}$ be a basis of $V$.
The map $x \mapsto \| x \|$, where $x\in V$, is continuous with respect to the topology induced by the norm $\| \cdot \|_1$
Via compactness, this enables us to conclude there is a real $M > 0$ such that $M \| x \|_1 \leq \| x \| $ for each $x \in V$.
Therefore for any $x \in V$: if $\|x\| < \delta$, then $ \| x \|_1 < \frac {\delta}M $.
Hence we have $\|f(x)\| \leq \sup\{ \| f(v_i) \| \}_{i=1}^n \cdot \| x\|_1 < \sup\{ \| f(v_i) \| \}_{i=1}^n \cdot \frac {\delta}M $, which can be made smaller than any beforehand given $\epsilon > 0$. $\square$

But in the subsequent Problem 23, we are tasked with following:

Use Problem 22 to prove that if $V$ is a finite dimensional vector space over $\mathbb{R}$ and $\| \|_1$, $\| \|_2$ are two norm functions on $V$ (i.e., real-valued functions such that $(V,\| \|_1)$ and $(V, \| \|_2)$ are normed vector spaces), then there exist positive real numbers $m,M$ such that $m \leq \frac { \| x\|_1 }{ \| x\|_2 } \leq M$ for all nonzero $x \in V$.

We are asked to use Problem 22 to solve Problem 23. Is this not strange, or am I misunderstanding something?
In order to solve Problem 22 (c), I had to use the property  in Problem 23.
Does this mean Rosenlicht had in mind a different solution of Problem 22 (c)? One not invoking the property in Problem 23?
I have been looking online and have not find a proof that does not rely on the property in Problem 23, namely the equivalence of norms in finite dimensional vector spaces.
Does anyone know if Problem 22 (c) can be solved without invoking equivalence of norms? Thank you.
Comment: You can prove that a linear operator is bounded on finite dimensional Hilbert space, and it is continuous if it is bounded.
Comment: Regarding to your confusion, you *do not* need Problem 22 (c) to prove Problem 23. However, it is clear that the author's intention is to let the readers prove Problem 22 (c) without the knowledge of Problem 23.
Comment: @Tab1e thank you for your input! in this case all we know is that $V$ is endowed with a norm; we have no access to a inner product. what I am struggling to see is how we can prove problem 22 (c) without the knowledge of problem 23. evidently I used problem 23 to solve (c) in 22. is there a way to do it without the property in problem 23? i.e. can we forego analysis to solve (c)?
Answer: Let $\text{dim}(X) = n$ and there is a basis $\{e_1, \dots, e_n\}$ for $X$. We can write $x = \sum \zeta_i e_i$ and derive
$$
\begin{align*}
\|f(x)\|_Y =\left\|\sum\zeta_if(e_i)\right\|_Y &\leq \sum |\zeta_i|\|f(e_i)\|_Y \\
&\leq \max_k \|f(e_k)\|_Y \sum|\zeta_i|
\end{align*}
$$
Try to prove the following lemma:
Lemma

Let $\{x_1, \dots, x_n\}$ be a linearly independent set of vectors in
a normed space $X$. Then there is a number $c >0$ such that for every
choice of scalars $\alpha_1,\dots, \alpha_n$ we have
$$
\|\alpha_1 x_1 + \dots + \alpha_n x_n\| \geq c(|\alpha_1|+\dots+|\alpha_n|)
$$

Using the lemma, we have
$$
\sum |\zeta_i| \leq \frac1c \left\|\sum\zeta_ie_i\right\|_X = \frac1c \|x\|_X
$$
for some $c>0$. Now you have
$$
\|f(x)\|_Y \leq \alpha\|x\|_X
$$
where $\alpha = \frac1c \max_k \|f(e_k)\|_Y$.
From this, you can try to prove that $f$ is continuous if it is bounded.
Comment: "Derive (try to prove this)", but this property is exactly that of Problem 23, no? The crux here is that Problem 22 precedes Problem 23. This leads me to suspect there ought to be a way to do it without adverting to the property in Problem 23.
Comment: @kapython NO. This property is not equivalent to the equivalence of norm. Only one norm is used in the statement, how did you come up with that conclusion?
Comment: @kapython I have rephrased the property as a lemma.
Comment: Tab1e:  my impulse to attribute problem 23 to the lemma was due to it invoking a relationship between the abstract norm $\|\cdot \|_X$ and $\|\cdot \|_1$, but this was perhaps wrongful.
Comment: Tab1e: To show it, we know $x \mapsto \|x\|_X$ is continuous under the topology induced by $\|\cdot \|_1$. Then we consider this map on the compact set $\{x\in V : \|x\|_1=1\}$ and argue existence of a positive minimum value.


Mac OS X R error "ld: warning: directory not found for option"

Question: I am trying to install an R package from source, but getting an error:
* installing *source* package 'mclust' ...
** package 'mclust' successfully unpacked and MD5 sums checked
** libs
gfortran-4.8   -fPIC  -g -O2  -c mclust.f -o mclust.o
gfortran-4.8   -fPIC  -g -O2  -c mclustaddson.f -o mclustaddson.o
clang -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/Library/Frameworks/R.framework/Resources/lib -L/usr/local/lib -o mclust.so mclust.o mclustaddson.o -L/Library/Frameworks/R.framework/Resources/lib -lRlapack -L/Library/Frameworks/R.framework/Resources/lib -lRblas -L/usr/local/lib/gcc/x86_64-apple-darwin13.0.0/4.8.2 -lgfortran -lquadmath -lm -L/usr/local/lib/gcc/x86_64-apple-darwin13.0.0/4.8.2 -lgfortran -lquadmath -lm -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
ld: warning: directory not found for option '-L/usr/local/lib/gcc/x86_64-apple-darwin13.0.0/4.8.2'
ld: warning: directory not found for option '-L/usr/local/lib/gcc/x86_64-apple-darwin13.0.0/4.8.2'
ld: library not found for -lquadmath
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mclust.so] Error 1
ERROR: compilation failed for package 'mclust'
* removing '/Library/Frameworks/R.framework/Versions/3.3/Resources/library/mclust'
Warning in install.packages :
  installation of package 'mclust' had non-zero exit status

I don't have /usr/local/lib/gcc/x86_64-apple-darwin13.0.0, so it makes sense that it can't be found. I have /usr/local/lib/gcc/i686-apple-darwin11 and /usr/local/lib/gcc/4.8 (symlink to Homebrew installation). Where is it getting x86_64-apple-darwin13.0.0 from?
There are a lot of references to a similar error online. However, all of them are related to compiling in Xcode and resolved by updating project settings, which is not applicable here.
Comment: Homebrew installations are not supported by "official R Core". There is a Fortran package at http://r.research.att.com/ but I think it might have static linking with the "authorized" version that ends up in the Frameworks tree. I'm not an expert in this area and there are some users of SO (thinking of @hrbrmstr) that think homebrew is "just fine". Do a search on "user:1457051 homebrew" and see if you find more support than I offer.
Comment: The current versions of clang and gfortran used by CRAN can be found here: https://cran.r-project.org/bin/macosx/tools/
Answer: You need to modify the ~/.R/Makevars file. For a greater overview of this see: https://cran.r-project.org/doc/manuals/r-release/R-admin.html#OS-X-packages
Alternatively, this has been answered before in a bit more depth by @kevin-ushey in Rcpp warning: "directory not found for option '-L/usr/local/Cellar/gfortran/4.8.2/gfortran'".
What is happening is your code is not being run under gcc instead it is being forwarded to clang
You will need to change your compile statements in ~/.R/Makevars/ to gcc using:
VER=-5.3.0
CC=gcc$(VER)
CXX=g++$(VER)
CFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
CXXFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
FLIBS=-L/usr/local/Cellar/gcc/5.3.0/lib/gcc/5

This assumes you have already installed gcc via homebrew under:
brew install gcc

(gfortran ships with gcc in brew now)
Comment: Need to set the implicit variables `CXX11`, `CXX14`, and `CXX17` to use `g++$(VER)` just like `CXX` does. These define the compiler that should be used for each language standard. e.g. `CXX11` is the C++11 standard.
Comment: To get this working today with GCC 10.2.0 I had to change the second line to `CC=gcc`.
Comment: I have **gcc** installed via homebrew and I've created a Makevars file but I keep having issues, primarily because I have a newer version of gcc. I changed the last line to `FLIBS=-L/usr/local/Cellar/gcc/7.3.0_1/lib/gcc/7` and then the first line to `VER=-7.3.0_1` (which caused problems until I changed it to `VER=-7`). That might've actually worked for compiling one R package but now for some reason the default compiler remains as clang, I'm not sure why... Have any ideas??
Comment: Thank you very much for your response--I really do appreciate it. Now it appears that I'm able to compile some packages with no problem and then when other packages fail to compile I end up just commenting out the Makevars file entirely so that my system uses **clang** instead, which seems to mostly fix the issue. Is that sort of ad hoc approach *normal*??
Answer: Incorporating previous solutions with additional help from the comments, the following solution has worked for me on Mac OS X High Sierra.
Create/edit ~/.R/Makevars with the following contents:
VER=-8
CC=gcc$(VER)
CXX=g++$(VER)
CXX11=g++$(VER)
CXX14=g++$(VER)
CXX17=g++$(VER)
CFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
CXXFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
FLIBS=-L/usr/local/Cellar/gcc/8.2.0/lib/gcc/8

Note, I am using homebrew and have gcc version 8.2.0 installed.
Comment: The FLIBS lead worked in a similar case when the compiler couldn't find libs for gfortran
Comment: Just for anyone else lading here with the same issue, this approach also worked for me on MacOS Big Sur
Comment: Alas, for me with Big Sur on M1, it does not. As with comment on other answer, first changed second line to `CC=gcc` and used /opt/homebrew. But throws "checking whether g++-10 accepts -g... no
configure: error: no C++ compiler found or it cannot create executables"
Answer: I had this issue for a long time, working on a Mac. Following the other answers on this page and other questions, I did the following and it finally worked!
Step 1 - brew install gcc (it installed gcc-11 for me. If this is different for you in the future, replace gcc-11 below with the corresponding version. You can find the version by checking in the folder /usr/local/bin and seeing the latest gcc version file there)
Step 2 - xcode-select --install (this installs Xcode CLI)
Step 3 - ln -sf /usr/local/bin/gcc-11 /usr/local/bin/gcc (this makes a new gcc symlink under /usr/local/bin/. Source)
Step 4 - I did not have a ~/.R/Makevars file. Heck, I didn't even have the ~./R folder. Made the folder and the file. Here is what I wrote in the Makevars file (remember to change the GCC version in the first and last line according to the version you have. Also remember to not have the entire version number that's in the last line, in the first line. Just the overall version number - 11 in my case) -
VER=-11
CC=gcc$(VER)
CXX=g++$(VER)
CXX11=g++$(VER)
CXX14=g++$(VER)
CXX17=g++$(VER)
CFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
CXXFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
FLIBS=-L/usr/local/Cellar/gcc/11.2.0_3/lib/gcc/11

Now restart, and voila! It works.
Comment: Fixed my gfortran issues just now.
Comment: This worked for me (Sep 19, 2023) on Mac OS Ventura 13.5.2. R version 4.2.3. Make sure to change the verison number VER and the FLIBS path to your latest version. Thanks, @user1993!
Comment: @jzadra I mention that in step 1 - check bin
Comment: Since most of these answers are old, how do I determine what the version value should be?
Answer: From http://thecoatlessprofessor.com/programming/rcpp-rcpparmadillo-and-os-x-mavericks-lgfortran-and-lquadmath-error/ you can fix this by downloading the optional gfortran libraries from http://r.research.att.com/libs/ and extracting them. To do this on the command line
curl -O http://r.research.att.com/libs/gfortran-4.8.2-darwin13.tar.bz2
sudo tar fvxz gfortran-4.8.2-darwin13.tar.bz2 -C /

Comment: when I enter second line, I get ```tar: Unrecognized archive format```. What am I doing wrong?
Answer: I'm working on MacOS Mojave (10.14.5) and on R 4.0.0. The problem here is that "CRAN R 4.0.0 builds and higher no longer use any custom compilers" (see here), so the Makevars solution does not appear to work anymore.
The solution for me was to download and install the GNU Fortran compiler from the official R-Project website. Note that you will also need Xcode and Xcode command-line tools.
After running the installer with default settings, compilation of gfortran code worked without problems.
Answer: For R 4.3.0 and higher you can fix this issue by going to https://mac.r-project.org/tools/ and installing the gfortran-12.2 universal:

R 4.3.0 and higher uses universal GNU Fortran 12.2 compiler. You can download an installer package gfortran-12.2-universal.pkg (242MB) - for more details and other download options see R-macos GNU Fortran releases on GitHub.
Comment: waited only 7 years for this
Answer: I received the same error on MAC. All I needed to do was to install gfortran-6.1.pkg from https://cran.r-project.org/bin/macosx/tools/. Make sure that the package is installed under /usr/local/gfortran so it can be found by R.
Alternatively you can install it via homebrew typing brew cask install gfortran in the terminal (it may ask for your password).
Answer: In my case I combined this answer with this one, to produce the following code in the ~./R/.Makevars-file.
touch ~./R/.Makevars

(because it didn't exist there)
open -a BBEdit ~./R/.Makevars

(I use BBEdit as text editor)
Added the following lines to the Makevars-file:
VER=-11
CC=gcc$(VER)
CXX=g++$(VER)
CFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
CXXFLAGS=-mtune=native -g -O2 -Wall -pedantic -Wconversion
# FLIBS=-L/usr/local/Cellar/gcc/11.1.0_1/lib/gcc/11
# FLIBS = -L`gfortran -print-file-name=libgfortran.dylib | xargs dirname`
FLIBS=`gfortran -print-search-dirs | grep ^libraries: | sed 's|libraries: =||' | sed 's|:| -L|g' | sed 's|^|-L|'`

These two lines were suggested by @KevinUshy.
# FLIBS=-L/usr/local/Cellar/gcc/11.1.0_1/lib/gcc/11
# FLIBS = -L`gfortran -print-file-name=libgfortran.dylib | xargs dirname`

I commented these out, as I figure that the final line would probably work best.
Two notes.
I have brew installed and I used brew to install gcc using the command brew install gcc.
I figure out the version-naming using brew info gcc, which gave me 11.1.0_1, but it is linked as gcc-11, so VER=-11 in the .Makevars-file.
Hope this helps others.
Comment: I am on version 11 too but somehow my gcc is linked as `gcc`, so I removed `VER=-11` and it worked.
Answer: I am having Mac OS Catalina and in my case installation of Homebrew, the newest gcc and Gfortran 8.2.0 solved the issue.
Comment: This worked for me in Mac OS Catalina as well! I used the gfortran 8.2 Mojave installation https://github.com/fxcoudert/gfortran-for-macOS/releases
Comment: On Mojave, ```brew update && brew reinstall r``` followed by ```brew link --overwrite r``` worked.
Answer: The solution was to re-install problematic packages with Homebrew.
$ brew uninstall --ignore-dependencies --force openssl
$ brew install openssl

$ brew uninstall --ignore-dependencies --force readline
$ brew install readline

Answer: Digging this topic, if you tried these and much others approaches related to this error and got no success, I strongly recommend you to check if your OSx - just in case - deleted the .zshrc file.
If that's the case, you should create again this file in the root dir. type in your terminal:

touch .zshrc

followed by

openssl_prefix=$(brew --prefix openssl) printf "CFLAGS=-I$openssl_prefix/include \nLDFLAGS=-L$openssl_prefix/lib"

example of output:

CFLAGS=-I/usr/local/opt/openssl@3/include LDFLAGS=-L/usr/local/opt/openssl@3/lib

add them to the zshrcfile content, run

source .zshrc
to refresh the file and that`s all!
Answer: Had this problem using R on macos 12.4.  It was caused by old and stale entries in my ~/.R/Makevars file.  Once I commented everything out everything compiled just fine.  I have XCode and brew install gcc active.
Answer: For later versions of R (R 4.0 and higher) and later operating systems, the recommended fix for this problem seems to be to install gfortran via rtools (see here, already mentioned in the answer of @lks_swrx).
When following these instructions, I ran into an additional problem, since my computer uses Apple Silicon chips (not Intel anymore), for which I wanted to add a solution here:

Download the appropriate gfortran tarball from rtools
Run tar fxz gfortran-12.0.1-20220312-is-darwin20-arm64.tar.xz -C /
Add it to your path by adding this line to your .zshrc file:
nano .zshrc (or whatever you use as text editor)
export PATH=$PATH:/opt/R/arm64/gfortran/bin

So far, so good; but the installation of DESeq2, which brought me here, did still not work, because R could not find the library. This is the fix:

Create a symlink to the gfortran library in /usr/local, so that R can find it:
ln -s /opt/R/arm64/gfortran /usr/local/gfortran (might require sudo)


Finding limit to $\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}$

Question: I need to find limit for:
$$
\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}.
$$
The first thing that comes to mind is simplifying with $\lim_{x \to 0} \sin(x)/x = 1$; however, we have limit going to 2.
I tried to  first rewrite the expression with limit going to zero. We could do this by replacing $x$ with $t = x-2$:
$$\lim_{t \to 0^+} = \frac{\sin(t+2)}{(t+2)t}$$
But I get stuck here. The first instinct is to try and extract $\sin(x)/x$ from this expression to simplify it. But I have no idea how.
Comment: this is not an indeterminate form
Comment: Where's the problem with your first expression? $\sin(x)/x$ is finite when $x$ approaches $2$. Before simplifying anything you should always test the limit.
Answer: Let be $x-2:=y$. We have
$$\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}=\lim_{y \to 0^+}\frac{\sin(y+2)}{y(y+2)}=\lim_{y \to 0^+}\frac{\sin(y+2)}{(y+2)}\cdot \lim_{y \to 0^+}\frac 1y=\frac{\sin 2}{2}\times (+\infty)=+\infty$$
Comment: Thanks! Can I ask why  $\lim_{y \to 0^+}\frac 1y=\infty$? In my text book whenever denominator is equal to zero, when limit is going to zero, it's considered indeterminate(?) and they seek to rewrite the expression in a way where denominator is not zero.
Comment: @LennyWhite You're welcome. You can try with a calculator. If the denominator of a fraction is always more little near to zero you can see that the calculator gives you a large number. Try it!!!!
Answer: As noticed
$$\lim_{x\to2^+} \dfrac{\sin(x)}{x} = \dfrac{\sin(2)}{2}=c>0$$
$$\lim_{x\to2^+} \frac1{x-2}=\infty$$
and then
$$\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}=\lim_{x\to2^+} \dfrac{\sin(x)}{x}\frac1{x-2} = \infty$$
Answer: You actually don't have anything special to do here, you have:
$$\lim_{x\to2^+} \dfrac{\sin(x)}{x} = \dfrac{\sin(2)}{2}$$
Which is a finite non-zero quantity. With that,
$$\lim_{x\to2^+} \dfrac{\sin(x)}{x\cdot(x-2)} = \dfrac{\sin(2)}{2\cdot(x-2)} = +\infty$$
Comment: Thank you! Can I ask the logic behind $\dfrac{\sin(2)}{2\cdot(x-2)}$ being equal $+\infty$?
Comment: I'm a bit late, but if we take $\lambda = \dfrac{\sin(2)}{2} \ne 0$, then we see that $\dfrac{\lambda}{x - 2}$ will go to infinity because we are dividing by a quantity that approaches $0$.


Proof of $\zeta(2)=\frac{\pi^2}{6}$

Question: While messing around with some integrals, I have found the following proof for $\zeta(2)=\frac{\pi^2}{6}$, but I'm not sure if it is valid:
We take a look at the integral $I=\int_0^{\frac{\pi}{2}} \ln(\cos(x))\space dx$. Clearly, we have $\Im(I)=0$; to show that the integral converges isn't difficult and consequently, it is real. Now some calculations using $\cos(x)=\frac{e^{ix}+e^{-ix}}{2}$:
$$
I=\int_0^{\frac{\pi}{2}} \ln\left(\frac{e^{ix}+e^{-ix}}{2}\right)\space dx=\int_0^{\frac{\pi}{2}} \ln\left(e^{2ix}+1\right)-ix-\ln(2)\space dx=\int_0^{\frac{\pi}{2}} \ln\left(e^{2ix}+1\right)\space dx-i\frac{\pi^2}{8}-\frac{\pi}{2}\ln(2)
$$
Now:
$$
J=\int_0^{\frac{\pi}{2}} \ln\left(e^{2ix}+1\right)\space dx=\int_0^{\frac{\pi}{2}} \sum_{k=1}^{\infty}\frac{(-1)^{k-1}\cdot e^{2ixk}}{k}\space dx=\sum_{k=1}^{\infty}\frac{(-1)^{k-1}\cdot \left[\frac{e^{2ixk}}{2ik}\right]_0^{\frac{\pi}{2}}}{k}=\sum_{k=1}^{\infty}\frac{(-1)^{k-1}\cdot \left(\frac{(-1)^k-1}{2ik}\right)}{k}
$$
When $k$ is even, then $(-1)^k-1=0$ so those terms cancel out, leaving:
$$
J=\sum_{k=1}^{\infty}\frac{\left(\frac{-2}{2i(2k-1)}\right)}{2k-1}=i\sum_{k=1}^{\infty}\frac{1}{(2k-1)^2}=i\left(\sum_{k=1}^{\infty}\frac{1}{k^2}-\sum_{k=1}^{\infty}\frac{1}{(2k)^2}\right)=i\cdot\frac{3}{4}\zeta(2)
$$
Clearly, we have $\Re(J)=0$ and therefore $0=\Im(I)=\frac{3}{4}\zeta(2)-\frac{\pi^2}{8}$ and thus $\zeta(2)=\frac{\pi^2}{6}$.
I'm not sure with all those complex terms which are involved so it would be highly appreciated if someone could tell me wether the steps are valid or not.
Edit:
The main aspects I'm concerned about are $\ln\left(e^{ix}+e^{-ix}\right)=\ln\left(e^{2ix}+1\right)-ix$ or $e^{i\pi k}=(-1)^{k}$ and in general manipulations involving the natural log of complex arguments, because I'm familar with the fact, that it can take infinitly potential values, but until now I havent had a proper introduction to the subject and learned the major things autodidactically, so I'm not sure about the validity.
Comment: Those points are somewhat subtle, as nothing there is absolutely convergent. That's not necessary, but it would be sufficient.
Comment: I don't know, it looks pretty good to me, you can integrate the power series term-by-term.  Let us know if you find an issue with it.  In any case, there are several fairly simple proofs of this fact.
Comment: @GregoryGrant: Yes I guessed so, but if we want to check everything properly to be absolutely sure it works we might as well do it formally. Besides does the power series obtained by termwise integration converge to the original on the boundary of the disk of convergence? A lot of issues are being conveniently swept under the rug here. I still think this approach should work but I don't have time now to verify it rigorously. It was just a passing glance that I gave to the question.
Comment: The main things I would worry about are the splitting of the complex logarithm and then doing the definite integration term-by-term in the logarithm sum.
Comment: I think I've seen this before (looking at some places, but have not found it yet).
Comment: @GregoryGrant: It's not a power series.
Comment: @user21820 Why isn't it a power series?  It's also a Taylor series if you want, but Taylor series are power series.
Comment: @GregoryGrant: It's an exponential function inside. One would have to be careful when converting it to a power series, because integrating the result termwise is not obviously the same as integrating the exponentials.
Comment: @user21820 It's fine, just a change of vars inside a power series, that has no effect on whether or not you can reverse the order of the integral and the sum.
Comment: a somewhat related answer is here http://math.stackexchange.com/questions/8337/different-methods-to-compute-sum-limits-n-1-infty-frac1n2 by community which is from G. Mikhalkin (as the post says)
Answer: I see three steps which are delicate in some sense:

the definition of the logarithm of complex numbers in the integral $I$ in such a way that usual (real) formulas still hold at least for the complex numbers involved in those computations;
the exchange of the integral and the series in the integral $J$;
the direct application of the fundamental theorem of calculus in the final step of the evaluation of $J$ (actually an exchange of two limits is happening here);

The first thing to be chosen is probably a suitable analytic extension of the real logarithm to the complex plane, which is equivalent to choose an appropriate principal argument function $\operatorname{Arg}(z)$ such that
$ z = |z|e^{i\operatorname{Arg}(z)}$.
I'm using the following conventions: $\ln_{\mathbb{R}}$ stands for the well known real logarithm defined on positive real numbers; $\ln_{\mathbb{C}}$ stands for a suitable extension of $\ln_{\mathbb{R}}$ to the complex plane ($0$ excluded). In particular one can choose:
$$ \ln_{\mathbb{C}}z= \ln_{\mathbb{R}}|z|+i \operatorname{Arg}(z) $$
where $\operatorname{Arg}(z)\in \left]-\pi,\pi\right]$.
In this way, $ z\mapsto\ln_{\mathbb{C}}(z) $ is the (unique) analytic extension of $ \ln_{\mathbb{R}} $ to the domain $ \mathbb{C}^{**} := \mathbb{C}\setminus\{x\in\mathbb{R} : x\le 0\} $.
The complex numbers involved in the integral $I$ are all in the closed upper half plane, so this extension should work.
This justifies the fact that:
$$
\ln_{\mathbb{R}}\cos(x) = \ln_{\mathbb{C}}\frac{e^{i2x}+1}{2e^{ix}} =
\ln_{\mathbb{C}}({e^{i2x}+1}) - \ln_{\mathbb{C}}({2e^{ix}}) =
\ln_{\mathbb{C}}({e^{i2x}+1}) - \ln_{\mathbb{R}} 2 - ix
$$
Observe that with our choices the identity $ \ln_{\mathbb{C}} e^{ix} = ix $ is true if and only if $x$ belong to the interval $ \left]-\pi,\pi \right]$. Here everything works since $ \operatorname{Arg}(2e^{ix})= \operatorname{Arg}(e^{i2x}+1) = x \in [0,\pi/2] $.
There is another reason for choosing this particular extension $\ln_{\mathbb{C}}$ and it is the fact that it satisfies the identity
$$
\ln_{\mathbb{C}}(z+1) = \sum_{k=1}^{+\infty} \frac{(-1)^{k-1}z^{k}}{k}
\quad\forall |z|\le 1, z \ne -1,
$$
which is used in the computation of $J$. This is a consequence, for instance, of the identity theorem for holomorphic functions.
In fact, if, for instance, I had chosen $ \operatorname{Arg}(z) \in \left[ 0, 2\pi \right[ $ (as sometimes it is common and convenient to do), then the identity would have hold true only in the upper half ball, since the points $z+1\in\mathbb{R}$ with $ z\ge -1 $ would have been discontinuity points for the corresponding argument function and, thus, for the corresponding complex logarithm.
Note that the series above converge pointwise in that set and uniformly on the sets $ E_{r} := \{ z \in \mathbb{C} : |z|\le 1, |z+1|\ge r\}$,
for each $ r \in \left]0,1\right[$.
I found a very clear explanation of this on some slides by Klaas Pieter Hart; here are the links to the slides and to the web page of Klaas Pieter Hart:
http://fa.its.tudelft.nl/~hart/37/onderwijs/weblecture/handout.pdf;
http://fa.its.tudelft.nl/~hart
Now, let's come to point 2: the exchange of the series and the integral in the computation of $J$. Here a problem appears since, as $ x \to \pi/2^{-} $,
the point $ e^{i2x} $ moves on the circle $ |z|=1 $ approaching $ -1 $ which is the unavoidable singularity of $ \ln_{\mathbb{C}}(z+1) $. Moreover the uniform convergence of the series above does not hold in any neighborhood of $-1$.
In fact, the integral $J$ is a converging improper integral (as seen from Riemann's eyes, at least!), so it would be more precise to consider it as:
$$ J = \lim_{\theta\to\pi/2^{-}} \int_{0}^{\theta} \ln_{\mathbb{C}}(e^{i2x}+1) dx, $$
which also explains why I spoke of an exchange of two limits in point 3.
Then we can apply the fact that the series now converges uniformly on the arc described by the points $ e^{i2x} $ for $x\in[0,\theta]$ as long as
$ \theta < \pi/2$, and we can rightfully exchange the integral and the series to get:
$$
J = \lim_{\theta\to\pi/2^{-}} \int_{0}^{\theta} \ln_{\mathbb{C}}(e^{i2x}+1) dx =
\lim_{\theta\to\pi/2^{-}} \sum_{k=1}^{+\infty}(-1)^{k-1}\frac{e^{i2k\theta}-1}{2ik^{2}}.
$$
We finally arrive to point 3, since now one would like to move the limit w.r.t. $\theta$ inside the series.
Here things are easier since:
$$
\left|(-1)^{k-1}\frac{e^{i2k\theta}-1}{2ik^{2}} \right| \le
\frac{1}{k^{2}} \quad \forall \theta\in[0,\pi/2] \text{ and } \forall k
$$
and Weierstrass M-test grants that the series now converges totally, uniformly and absolutely for $ \theta \in[0,\pi/2]$ and the limit can be moved inside the series to conclude the argument.

Proof of $\zeta(2)=\frac{\pi^2}{6}$


JavaScript Compare ERRO

Question: Estou tentando passar um for para validar uma lista que preciso porém não estou conseguindo fazer com que funcione e não entendi o porque ainda.
Tenho o seguinte código:
$('#aprovados').click( function(){
  $.getJSON($('#listeditappjobs').attr("data-list-app-my-jobs-url"),
    function(data){
      if (data){
        var apps = data.data
        console.log(apps[0])
        var infojob = data.datas
        console.log(infojob)
        var aprovados = []
        for(i = 0; i < apps.length; i++){
         if (infojob.distance >= apps[i].distance  &&
             infojob.xp <= apps[i].years_xp &&
             infojob.salary_min <= apps[i].pre_salary  &&
             infojob.salary_max >= apps[i].pre_salary)
            {aprovados.push(apps[i]); }
               };
        console.log(aprovados)
      }else{alert("LISTA vazia")
    }},
);
});

O Que eu tenho de retorno é:
Object { distance: 1, escolaridade: "TecnologoCursando", user: "firstname.lastname@example.com", pre_salary: "1500.12", years_xp: 3 }

Object { distance: 2, xp: 3, salary_max: "1500.01", salary_min: "200.00" }
Array []

O que eu estou fazendo de errado?
Answer: O problema é que você está comparando números como strings:
infojob.salary_min <= apps[i].pre_salary
       |                     |
     "200.00"            "1500.12"

infojob.salary_max >= apps[i].pre_salary
       |                     |
     "1500.01"            "1500.12"

Use parseFloat() para convertê-los em números:
if (infojob.distance >= apps[i].distance  &&
    infojob.xp <= apps[i].years_xp &&
    parseFloat(infojob.salary_min) <= parseFloat(apps[i].pre_salary)  &&
    parseFloat(infojob.salary_max) >= parseFloat(apps[i].pre_salary))
   { aprovados.push(apps[i]); }

No entanto, se observar, esse if não irá ser verdadeiro porque a última condição é false:
parseFloat(infojob.salary_max) >= parseFloat(apps[i].pre_salary)
                  |                                 |
               1500.01                           1500.12

1500.01 não é >= do que 1500.12.

Exemplo onde todas as condições são verdadeiras:

var data = {
   data: [{
      distance: 1,
      escolaridade: "TecnologoCursando",
      user: "firstname.lastname@example.com",
      pre_salary: "1500.12",
      years_xp: 3
   }],
   datas: {
      distance: 2,
      xp: 3,
      salary_max: "1500.12",
      salary_min: "200.00"
   }
}

var apps = data.data;
console.log(apps[0]);
var infojob = data.datas;
console.log(infojob);
var aprovados = [];
for(i = 0; i < apps.length; i++){
   if (infojob.distance >= apps[i].distance  &&
       infojob.xp <= apps[i].years_xp &&
       parseFloat(infojob.salary_min) <= parseFloat(apps[i].pre_salary)  &&
       parseFloat(infojob.salary_max) >= parseFloat(apps[i].pre_salary))
   { aprovados.push(apps[i]); }
}
console.log(aprovados);
Comment: Obrigado cara, me ajudou muito!
...referente aos dados, eu tenho mais um monte eu coloquei ai só exemplo pra conseguir explicar mais ou menos o que precisa rs

JavaScript Compare ERRO


Convergence in Probability question.

Question: Let $\lambda_n = 1/n$ for $n=1,2,\ldots$. Let $X_n \sim Poi(\lambda_n)$. Show that a) $X_n \rightarrow_P 0$. b) Let $Y_n = nX_n$. Show that $Y_n \rightarrow_P 0$ (where $\rightarrow_{P}$ denotes convergence in Probability)
Part a) is relatively straight forward as
We know that $\mathbb{E}(X_n) = \lambda_n = 1/n$ and $\mathrm{var}(X_n) = \lambda_n = 1/n$. We know that since $X_n >0$ that $|X_n| = X_n$. Then from Chebyshevs inequality we know that $$P(X_n >\epsilon) \leq \frac{\mathrm{var}(X_n)^2}{\epsilon^2} = \frac{1}{n^2\epsilon^2} \rightarrow 0\;\mathrm{as\;}n \rightarrow \infty. $$
For part b) i cannot use this same approach as $\mathbb{var}(Y_n) = n^2*1/n = n$. Also i know convergence in quadratic mean implies convergence in probability but $\mathbb{E}(Y_n - 0)^2 = n^2(\mathbb{E}(X_n^2)) = n^2(1/n + 1/n^2) \not \rightarrow \infty$ as $n \rightarrow \infty$. Any ideas?
Answer: One way of proving that $nX_n \to 0$ in probability is to use characteristic functions. Recall that $Ee^{itX_n}=e^{-(\frac 1 n) (1-e^{it})}$. Hence  $Ee^{itnX_n}=e^{-(\frac 1 n) (1-e^{int})} \to 1$ as $ n \to \infty$. This implies that $nX_n \to 0$ in distribution which is equivalent to convergence in probability.
Comment: Hi thanks for the response, i'm not sure this method is mentioned in the chapter so perhaps they intended of a different method to prove it. Its from the book All of Statistics chapter 5.
Answer: In case you are not familiar with characteristic functions (yet), you could use the fact that $$P(nX_{n}=0)=P(X_{n}=0)=e^{\frac{1}{n}} \rightarrow 1 $$ since the Poisson distribution is a discrete distribution with values in $\mathbb{N} \cup \{0\}$

Convergence in Probability question.


Changing ordering of results in django-haystack

Question: I am using django-haystack for search. By default it is showing oldest objects first whereas i want to show latest on top. Can anyone guide me how can i do this?
My code sample is shown below:
search_indexes.py
class PostIndex(indexes.RealTimeSearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr='title')
    created = indexes.DateTimeField(model_attr='created')

    def get_model(self):
        return Post

    def index_queryset(self):
        return self.get_model().objects.filter(created__lte=datetime.datetime.now())

Can anyone tell me the exact file where i'll have to make changes and what changes? Do i have to make changes to query.py file in haystack? Query.py has
 def order_by(self, *args):
        """Alters the order in which the results should appear."""
        clone = self._clone()

        for field in args:
            clone.query.add_order_by(field)

        return clone

How can i make changes to this to show the latest on the top?
Answer: You can set order_by in your haystack_urls.py (or whatever you called it) e.g
qs = SearchQuerySet().order_by('-created')

urlpatterns = patterns('haystack.views',
    url(r'^$', SearchView(searchqueryset=qs), name='haystack_search'),
)


Adding and removing elements in an array: An exercise

Question: I am looking to fill an array a with the numbers 1 through 10 and take a random number from that array and add it to an array b and remove that element from array a. I would like to know the most efficient way of doing this. EDIT: (The exercise requires that I not have repeated values in the arrays and that the permutation is random each time the method is called.) Here is my method so far:
public int[] nextPermutation() {
    int capOne = 10;
    int capTwo = 10;
    int aSize = 0;
    int bSize = 0;

    int[] a = new int[capOne];
    int[] b = new int[capTwo];

    int upperBound = 11;
    Random generator = new Random();

    //fill initial array with 1 - 10
    for (int i = aSize; i < 10; i++) {
        a[i] = i + 1;
        //companion variable for sizing array
        aSize++;
    }

    //Create a random integer and add it to array b
    //Remove same integer from array a
    //Repeat and remove another random integer from the remaining integers in array a and    add it to b

        permuted = b;
        return permuted;
        }

I may be approaching this in an inefficient if not completely incorrect manner. If so, I'm sure you won't hesitate to tell me. Any help on this is greatly appreciated.
Comment: you better use a list
Comment: Given that the array contains ten elements, I doubt you need to worry about efficiency too much. Focus on correctness.
Comment: Hi StinePike. As in List list = Arrays.asList() or an ArrayList?
Comment: can you have repeated values?
Comment: No I cannot have repeated values. I should have specified that. My apologies.
Comment: You can use ArrayList or List.Any one of this you can use.
Comment: I agree that an ArrayList would be much easier to use. The exercise in the book I am reading asks for an array though.
Comment: Really, an Array is the wrong animal.
Answer: You can:
//randomly choose element
int index = (int) (Math.random() * aSize);
int dataFromA = a[index];

//"remove" it from A
aSize--;
for(int i = index; i<aSize; i++) {
    a[i] = a[i+1];
}

//"add" it to b
b[bSize] = dataFromA;
bSize++;

Only interesting part is removing from A, where you have to reduce the size before the cycle (or you can i < aSize-1, then decrement size)
I guess you have to use arrays since this is an excersice, but using List for this would be better.
Answer: Here is a program producing random permutations, using swap. Well, I'm not sure which can produce a better result, but swap should be faster than add/remove to/from an array:
public int[] nextPermutation() {
    int cap = 10;
    int[] a = new int[cap];
    Random generator = new Random();

    //fill initial array with 1 - 10
    for (int i = 0; i < cap; i++) {
        a[i] = i + 1;
    }

    for (int i = 0; i < cap; i++) {
        int j = generator.nextInt(cap);
        int x = a[j];
        a[j] = a[i];
        a[i] = x;
    }

    // You can reduce the size of the output array:
    // int output[] = new int[5];
    // System.arraycopy(a, 0, output, 0, 5);
    // return output;

    return a;
}


What is the correct term for the "common" pentatonic scale?

Question: So a "pentatonic" scale is just any scale with 5 scale degrees (pitches). Yet, in most music we always just seem to assume that it's the scale with the following number of semitones (half steps) between each degree: 2,2,3,2,3. I've read about the different modes of this scale, achieved by starting the scale on different degrees to achieve a different feel giving us, e.g., major and minor pentatonic scales). But what is the actual term for this general pentatonic scale, regardless of mode? And are there other named pentatonic scales, possibly used by different cultures?
To make a comparison, the diatonic scale is a specific heptatonic scale with intervals 2,2,1,2,2,2,1, and therefore 7 different modes. But there are other heptatonic scales that also have 7 modes. Likewise, there is a specific pentatonic scale with intervals 2,2,3,2,3, and therefore 5 different modes. What is that scale called?
Comment: Then I agree that your question has no answer. Not every concept has a specific, unambiguous term for it.
Comment: I'm not used to seeing "**the** diatonic scale", because my understanding is there is more than one diatonic scale. The heptatonic scale with 2-2-1-2-2-2-1 half steps has been called "**the** major scale" in every context I've seen it. Sometimes it is also called "**the** Ionian mode".
Comment: Fair point; I guess it would be more correct for me to say **a** diatonic scale. But still, when I say that, you know the heptatonic intervals to which I'm referring, and the possible modes of such a scale (e.g., Ionian). But what word could I use to refer to the set of *pentatonic* scales with intervals 2,2,3,2,3 (i.e., not a specific mode)? As discussed in the comments on @It's HEDLEY's answer, "anhemitonic" isn't sufficient either.
Comment: Can you explain why "anhemitonic" is not sufficient? Is it because 2-2-3-2-3 and 2-3-3-2-2 are different patterns but are both anhemitonic and pentatonic?
Comment: Correct, that is the issue.
Answer: All scales, regardless of the number of pitches they contain, have modes. A mode is simply a rotation of the starting scale. For a heptatonic example, consider the harmonic minor scale: 2-1-2-2-1-3-1. It has seven unique modes.
The 2-2-3-2-3 pentatonic scale has 5 modes:

Major (2-2-3-2-3), most common
Egyptian (2-3-2-3-2)
Blues minor (3-2-3-2-2)
Blues major (2-3-2-2-3)
Minor (3-2-2-3-2), 2nd most common

These are all in the class of pentatonic scales labeled "anhemitonic", meaning that the scales contain no semitones. This term doesn't quite fit your requested definition though, as "anhemitonic pentatonic" could also refer to scales with other intervals, such as 2-4-2-2-2.
The term you're looking for doesn't exist. The pentatonic collection you're asking about is referred to by "anhemitonic pentatonic" or "major pentatonic" for the 1st mode. No musician would think of some other pentatonic scale with a different structure. It's the latter that would need a specialized term.
Comment: @Rabadash8820 "Major pentatonic" and "Anhemitonic pentatonic" are the terms of art.
Comment: @Rabadash8820 The term you're looking for doesn't exist. The pentatonic collection you're asking about is referred to by those two categories given in my post. No musician would think of some other pentatonic scale with a different structure. It's the latter that would need a specialized term.
Comment: Hey, thanks for the quick response! You kind of just restated the content of my question though.  Mentioning "anhemitonic" is helpful, but as you say, it is a "class" of scales; one with intervals 2,2,2,3,3 would be another example. I'm asking if there's a technical term for the 2,2,3,2,3 scale specifically (regardless of mode), similar to the term "diatonic" for 7-tone scales.
Comment: Seems "anhemitonic" is an ambiguous term then. According to the [Wikipedia article](https://en.wikipedia.org/wiki/Anhemitonic_scale): "anhemitonic scales do not contain semitones", which is a fairly general definition; an "anhemitonic pentatonic" scale would just be a 5-tone scale without semitones. But you're saying that it more specifically means a pentatonic scale with intervals 2,2,3,2,3, so there's ambiguity. Also my understanding was that "major pentatonic" refers to a specific *mode* of this pentatonic scale.
Comment: I see. I was mainly interested because I'm making a database of musical scales, and I wasn't sure which identifier to use to distinguish this class of common pentatonics. I've just been calling them "Western" pentatonic scales. But if there's no term, then there's no term. ¯\_(ツ)_/¯
Comment: @Rabadash8820 That should be clear enough. Just know, other musical cultures outside of "the West" use the same scale.
Comment: Hm, good point. Maybe "common" or "standard would be more appropriate...
Comment: Blues minor I can go with - E>G is m3. But Blues *major*..?
Comment: @Tim For what it's worth, Wikipedia lists a major blues pentatonic scale in addition to the minor blues pentatonic scale.
Comment: @ToddWilcox - yes, I picked up on that. I can understand maj/min pents, and maj/min Blues, but maj/min Blues pents leave me cold.
Comment: I had never encountered "Egyptian" before for 2-3-2-3-2. I've more often heard that one called "neutral" since it is neither major nor minor.  Your answer sent me to Scale Finder [Scale 1189](https://ianring.com/musictheory/scales/1189) which calls it "suspended pentatonic" and also gives it the Egyptian name "Meh", which is I suppose the answer to "Is this a major or minor scale"?
Answer: In answer to your header the "common" one would be pentatonic minor. Ask 100 guitarists and most would ask 'why, are there others?' Some may have extrapolated the 2nd most "common" - the major pentatonic, which is a mode (or is it the other way round..?) as both have a sensible reasoning behind their names - min. pent. has m3 (A>C in key Am) for example, while maj. pent. has at least M3 between ^1 and ^3 - C and E (in key C). A little contrived, but there we are.


Device Choose Dialog does not show up

Question: I have a Samsung Galaxy S i9000 smartphone, and I want to debug my Android app on my device.
I read the instructions at http://developer.android.com/guide/developing/device.html. I must say that although I didn't install any other driver than the Kiel Software and the USB drivers coming with the smartphone itself, I can see my device on the list when I write adb devices -- I see a device there with some numbers at the beginning and than 'device'. I also see a device in my device manager as Samsung Android Composite ADB Interface under the ADB Interface branch. Also in DDMS tool I see two devices; one emulator, and the other device with the same number as I see in the command line.
I think everything is right so far, but when I press the run button in Eclipse, or the debug button, a Device Chooser dialog does not show up as described in the android development website. Has anyone any idea?
Comment: Check the _Console_ window to see what is going on. The Device Chooser dialog only shows up if it cannot automatically select a target.
Comment: I just change the target selection mode from automatic to manual, than it shows up.. Ohh was so easy, but I think it must be specified in the description page of android. Thanks..
Answer: Check the Console window to see what is going on. The Device Chooser dialog only shows up if it cannot automatically select a target.
Answer: Well the steps should be:
- install drivers (or Kies, it's simpler for me since I connect a lot of different devices)
- check if USB Debugging is checked under Settings -> Applications -> Development -> USB Debugging
- check if the device shows up in the ADB list
If that doesn't work, as was the case with me once trying something on Honeycomb, try simply deleting any emulators and see if it doesn't automatically upload to your device.

Device Choose Dialog does not show up


Oracle Apex - Dynamically check checkbox item that is not within a report

Question: I have a checkbox item on my page (note: this is not inside a report) and I want to dynamically check the checkboxes when the page loads. I have a table which has all the checkbox types and a table which identifies which checkboxes that user has access to or in better terms should be checked.
My question is, within an Apex checkbox item how do you tell it to dynamically check a checkbox. I have it working in a report and my query looks like this:
SELECT at.name AS TITLE,
     CASE
         WHEN at.name IN (SELECT atp.name FROM preferences p) THEN apex_item.checkbox(1,at.value,'CHECKED')
         ELSE apex_item.checkbox(1,at.value, 'UNCHECKED')
      END AS CHECKBOX
FROM access_types at

Can I do something similar in an oracle apex checkbox item?
Comment: You can use a little bit of javascript to check a checkbox.
Comment: @Annjawn, javascript would be an option but I need to reference my preferences table to see which checkbox should be checked. How can I do that using javascript?
Comment: A simple solution could be to have hidden fields and populate the fields with the preference table values. Once the hidden fields have the values, the javascript can easily read the field and based on the value of the field check the checkbox.
Comment: @Annjawn, thank you. This would work. It just seems weird that you can not precheck a checkbox on a checkbox item list. It seems like that is something that would be important to web developers in oracle apex
Answer: Not sure it is exaclty what you want but if you simply need to initialize a checkbox item on page load, you can :
1 - Use the Source attribute of the checkbox item and set the following attributes :

Source Used : Always, replacing any existing value in session state
Source Type : SQL Query (return single value) or SQL Query (return colon separated value) depending if your checkbox item contains several checkboxes or not.
Source value or expression : your query that returns the right values.

2 - Use a Before header computation to compute your item :

Compute Item : Your checkbox item
Computation Point : Before header
Computation Type : SQL Query (return single value) or SQL Query (return colon separated value) depending if your checkbox item contains several checkboxes or not.
Computation : your query that returns the right values.

Note: I use checkboxes in reports too, but I noticed that when you have a lot of rows, it is very slower than using simple HTML checkboxes, so if you think your report is slow, I suggest you to generate simple HTML checkboxes from your query :
SELECT
  at.name AS TITLE,
  CASE WHEN at.name IN (SELECT atp.name FROM preferences p) THEN
    '<input type="checkbox" value="'||at.value||'" checked="checked" />'
  ELSE
    '<input type="checkbox" value="'||at.value||'" />'
  END AS CHECKBOX
FROM
  [...]