Qual o custo de chamar muitas funções?

Question: Recentemente, diante de uma discussão sobre Clean Code e melhores práticas de programação, um colega de trabalho comentou que em seu emprego anterior teve muita resistência por parte dos demais programadores para começar a dividir o código e torná-lo mais legível.
O principal motivo da resistência sempre foi de que muitas chamadas de funções iriam empilhar muitos dados no stack e consequentemente perder muita performance.
Particularmente, não vejo como uma chamada de função pode gerar um impacto tão negativo, mas eu digo isso baseado em uma experiência principalmente de linguagens de alto nível como Java, C# e PHP. Considerando o uso de uma linguagem de baixo nível (onde eu posso de fato gerenciar a memória) como C ou C++:
Qual é o custo de chamar 10 funções a mais?
Como consigo calcular a quantidade de memória gasta nesta operação?
Detalhe: No meu entendimento, a diferença de performance é extremamente desprezível, e portanto estou meramente interessado em saber como calcular o custo das chamadas.
Comment: Definição de idiota: Pessoa que usa desempenho/performance como desculpa esfarrapada para não seguir boas práticas de programação e escrever código gambiarrado.
Comment: Ah, e essas pessoas que não seguem boas práticas por insistir em bater na tecla do desempenho/performance, invariavelmente não tem a menor ideia de qual é o processo que deve ser realizado para se mensurar aquilo que elas tanto defendem.
Comment: @VictorStafusa, concordo com você. Performance é algo importante, mas ela não deve impedir de escrever um código minimamente legivel.
Comment: Dei +1 em todas as respostas, pois foram todas satisfatórias. Marquei a do BigOwn como sendo a correta, pois me pareceu ser a mais completa
Comment: Performance é algo relativo, você tem que olhar mais de perto, sem um cenário, não dá pra dizer se faz ou não diferença. 10ms em uma rotina de indexação do google é uma coisa, 10ms em um cadastro de livros que tem 10 usuários é outra. Geralmente, essa discussão de vale ou não fazer é feita em código legado e a galera não ta muito afim de refatorar (ter trabalho). Mas, existem muitas situações onde código escrito seguindo 'padrões' realmente vai ser mais lento do que código que só tem um main :P (generalizando). No teu caso, o gerenciamento de memória parece ser o mais gritante.
Answer: Performance
O custo de chamar função é pequeno ou grande dependendo de como você olha. Em geral o custo é de salvar alguns registradores em memória (muito provavelmente ficará no cache L1 que é muito rápido) e depois recuperar o estado original dos registradores antes do fim dela.
Além disso pode haver cópias de dados por causa da passagem de parâmetro. Se isso não ocorreria se não fosse uma função, depende da situação, alguns casos a cópia é obrigatória mesmo sem a função.
Em certas circunstâncias o compilador consegue linearizar a função, ou seja, em vez de chamá-la (call) ele copia o código da função para o lugar que estava chamando. Você conseguirá a legibilidade e a performance.
Se o compilador não fizer isso é porque não pode ou não compensa fazer o inline da função (ok, há situações que o humano sabe que pode ou compensa, e o compilador não).
Na pergunta linkada acima falo disso. Se a função não for minúscula e executar por um tempo muito curto não compensa. Também não compensa otimizar o que será chamado poucas vezes, mas isso nem sempre o compilador consegue saber.
O programador pode saber até que algo é chamado muitas vezes mas na verdade em um monte de lugar que há espera natural, então a performance não importa.
É verdade que em dispositivos com recursos reduzidos pode ser útil fazer um pouco mais de otimização. A otimização pode ser muito pior nesses casos, porque se ganhar performance perde memória e pouca memória afeta muito a performance. E um dos recursos escassos é bateria. Código mais rápido costuma ser código mais econômico.
No passado, quando os computadores eram pouco potentes, isso era bem mais importante.
A performance é desprezível na maior parte dos casos e onde não for, o compilador te ajuda. É claro que pode haver caso que a performance está ruim, mas o mais provável é que o algoritmo é ruim e não a chamada da função que está atrapalhando.
Há casos em que a linearização da função pode causar custos extras e o que parecia uma ganho de performance certo, dá o contrário. E como a diferença é bem pequena, o programador "espertão" que fez o que ele achou que daria melhor performance acaba nem percebendo que ele fez o pior, ainda que esse pior também não vá atrapalhar grande coisa.
Legibilidade
Eu jamais direi para sempre preferir reproduzir o código do que chamá-lo, mas raramente é preciso isso e só deve fazê-lo depois de verificar que a performance não é a esperada (tem que medir). O custo de otimizar pode não compensar o ganho. Porque a manutenção se torna mais difícil. Você quebra o DRY.
Claro que também entre o legível com menos performance e o legível com mais performance eu prefiro o de mais performance. Mas copiar o código para evitar a chamada dificilmente será mais legível que chamá-la.
Linguagens
Se a pessoa usa PHP, principalmente, ou Java ou C# ela não quer o máximo de performance. Essas linguagens podem ser rápidas, podem se beneficiar dessa otimização, mas não é tão comum assim precisar disto. Quando precisa de muita performance em geral o C ou C++ é preferido. Nessas linguagens faz mas sentido eliminar chamadas de função, mas depende da aplicação, depende do ponto da aplicação.
Memória
A pergunta fala em consumo de memória também. A função usará mais memória para salvar os registradores e é possível que também gaste um pouco mais por causa da cópia de parâmetros, mas nem sempre. Se o código foi feito direito isso pouco importa, porque a memória usada é da stack que já está alocada, usando ou não.
Profiling
Você precisa de um profiler para verificar como o código está executando e indicar os custos. Valgrind é o mais conhecido para Linux e para Windows provavelmente deve estar usando Visual Studio que tem um profiler.
Tem outras maneiras, mas essa é a mais precisa e correta.
Coloquei no GitHub para referência futura.
Answer: Diferenças de desempenho significativas por causa do tamanho da pilha de execução só fariam sentido em poucos casos. Os que consigo elencar que são realistas são esses:

Uso intensivo de recursão a níveis bem profundos.
Código que execute em dispositivos com pouquíssima memória disponível e baixíssimo poder computacional.
Chamadas a funções dentro de loops que realizam computações intensas.

Há cenários que combinam mais do que um desses casos acima, mas a maior probabilidade é que você não esteja caindo em nenhum desses casos, e portanto ficar fazendo micro-otimizações de código sem ter uma base sólida de conhecimento calcada em evidências concretas acaba sendo burrice. Muitas vezes essas micro-otimizações acabam é surtindo o efeito oposto, ou seja, deixam o código mais lento.
Além disso, os compiladores de C++ são bem espertos, muuuito espertos. Os compiladores de C++ modernos foram desenvolvidos pela colaboração e trabalho árduo de milhares de pessoas extremamente competentes e inteligentes naquilo que faziam e eles são capazes de ver oportunidades e possibilidades de otimizações muito além do que a maioria dos programadores experientes em C++ e assembler seriam capazes. Há um monte de otimizações que se aplicam a esses casos e casos relacionados, tais como inlining, alocação de registradores para variáveis mais utilizadas, desenrolamento de laços, recursão de cauda, caches, e mais um monte de outras coisas.
Mesmo nos 3 cenários acima, se você recai nos casos 1 e 3, o problema provavelmente não é o uso de funções e sim a forma como estas estão organizadas.
Se você recair no caso 2, você provavelmente não estará pensando em otimizações relacionadas ao tamanho da pilha de execução, e sim em espremer o máximo possível de bits no menor espaço possível olhando para o projeto no nível do hardware, considerando coisas como posicionamento de transistores em um microchip, consumo de energia elétrica, geração de calor, etc.
Novamente, provavelmente o seu caso não é nenhum desses.
E para ter certeza, se a conversa de fato chegar no desempenho/performance como muleta ou desculpa esfarrapada para mexer ou não mexer no código, é importante realizar-se medições. Estimar desempenho e realizar-se otimizações é uma coisa que requer evidência, provas e experimentos realizados com rigor metodológico, ou seja é ciência. Ir simplesmente no achismo de desobedecer boas práticas porque isso supostamente produziria um desempenho é falacioso e temerário.
Além disso, a maioria dos problemas referentes a desempenho que existem no mundo real (e não os problemas imaginários inventados por quem não quer seguir boas práticas de programação) não têm qualquer relação com o fato de você estar ou não realizando chamadas de funções ou procedimentos. São problemas que em geral envolvem projetos de algoritmos, organização dos dados na memória ou no disco, threads, cacheamento de informações, sistemas distribuídos, processos síncronos vs assíncronos, e outras coisas que são referentes a arquitetura do projeto, e não a pequenos detalhes referentes ao tamanho da pilha de execução ao se realizar 10 chamadas a uma função.
Answer: Sugiro fazer testes em looping medindo o tempo total de no mínimo 1 milhão de iterações.
Mesmo em linguagens de alto nível, conforme mencionado, como Java, na qual tenho razoável experiência, o tempo total das chamadas, sem operações de I/O não deve chegar perto de 1 segundo.
Sobre empilhar muitos dados na stack, com o poder computacional atual isto é irrelevante. Já desenvolvi em linguagens onde a preocupação com o tamanho dos registros de dados gravados era muito grande, já que no passado as ofertas de armazenamento eram muito inferiores. Porém até hoje, jamais tinha visto alguém dar atenção ao custo de chamada de funções em detrimento da qualidade do código e, principalmente, facilidade de manutenção e evolução.

Qual o custo de chamar muitas funções?


find the probability of a spade from a five-card deck

Question: I am trying to solve a simple exercise from a probability book but I have no idea how.
Given a five-card deck containing: ace of spades, king of spades, king of hearts, queen of spades, and queen of hearts, there are 2 players and each one has exactly one card. You observe evidence that one player has a picture card (king or queen). What's the probability that the other player has a spade?
I think at conditional probabilities, but I don't know how to model this events. P(A|B) where A is the event of extracting a spade and B represents event of having a spade from a picture card. I know that if I observe picture card than the probability of being a spade is 1/2.
Comment: How many cards does each player hold?  Did we see the rank of all of the one players' cards, or just that one?
Comment: It matters how the cards are split up among the players.  Consider the extreme example of where the youngest player is *always* given *all* of the cards.  In such a scenario, it is impossible for the older player to hold a spade (*or in fact any card at all*).  Consider the other extreme where for each card a coin is flipped.  If heads was flipped the first player gets the card.  If tails, then the second player gets the card.  Consider a third example where the first player is always dealt the top two cards and the second player gets the remaining three. These all have different final answers
Comment: each player has exact one card. All that I know is that one of them has a picture card. (it can be spade or not). I have to find probability that the other player has a spade.
Answer: Hint
Taking your "All that I know..." means that a random card "opened" is seen to be a face card,
either it is a spade face card (Pr = ?) in which case the other card has a Pr of $\frac14$ of being a spade,
or it is a non-spade face card (Pr = ?) in which case the other card has  Pr of $\frac24$ of being a spade
Can you now frame it in terms of conditional probabilities, and apply the law of total probability ?
Comment: $$Pr(A) = Pr(A|B) * P(B) + Pr(A|C) * P(C) $$ where A is the event of having a spade, B if "open" card is a spade and C if "open" card is not a spade. $$Pr(B) = \frac{1}{2}, Pr(A|B) = \frac{2}{4}, Pr(C) = \frac{1}{2}, Pr(A|C) = \frac{3}{4}$$ thus resulting $$Pr(A) = \frac{2} {8} + \frac{3}{8} = \frac{5}{8}$$.


Alternate picking from string 1 to string 3 - ACDC back in black

Question: I am a beginner guitar player and I am currently learning how to play back in black from ACDC. I can already pretty play the whole song, though the part I struggle the most is on the first section of the song, the lick after the chord progression E D A, as shown below:

I would say that I am already at 80% of the speed of the original song. Though I am having quite a hard time in improving the speed up until 100% of the normal speed.
It was when I started wondering about perhaps changing the alternate picking technique I am currently employing. I imagine that the "classic" picking technique would be (from string one to three):

down up (3-0)
down up (3-0)
down (2^(4) 2p0)

I noticed, however, that the technique above requires much more picking-hand movement than if I do:

down up (3-0)
up down (3-0)
up (2^(4) 2p0)

Which would be more like an "arpeggio" going upwards. Despite requiring considerably less movement with the picking-hand, I noticed that this technique is way less natural than the first one. I also noticed that most, if not all the guitar tutorials would teach the first technique (like here and here).
Therefore I would like to ask if anyone would recommend me sticking to the second technique, the one requiring less hand movement. I know there is no "one size fits all" in guitar, but I reckon it is important to stick to some "correct" movements in the guitar, especially when you are a beginner.
Comment: In my formative years I worked on the principle that when i needed to change strings, the last pluck would be in the direction of the next string. Spent a *lot* of time trying to perfect that, and it works in a lot of cases. Obviously there are times when it becomes counter-productive, which is when an extra finger often comes in handy, rather than the pick. It's complex to explain exactly what happens but something along those lines needs looking at for the thousands of different opportunities that this sort of conundrum will present to you in the future!  Suffice to say that alternate ...
Comment: ...picking isn't always the practical solution, and I recommend getting used to hybrid picking , which will often, when it comes automatically, be a good way round.
Comment: I'd recommend taking lessons and working through a graded guitar series.
Comment: According to @Tim 's comment your first example is the correct way (and how I play it, too; see my answer below). The "direction of the next string" is up / lower in pitch so playing down-up down-up is the best economy of motion. :)
Comment: Sounds like a google search for "economy picking" would be useful here.
Answer: Professional guitarist here. Congrats on your progress! Keep it up and you'll get there soon.
A competent guitarist should be able to pick this lick any number of ways. Because, honestly it's a relatively simple lick to play and the recorded tempo isn't super fast. The "classic" way (first example) is how I usually do it. You could also reverse that ("up-down, up-down, up") - which would be accurate if you want all downstrokes on downbeats and upstrokes on upbeats. Again, it shouldn't make a significant difference. Alternate picking needs to be second-nature, something you do without thinking, as an impulse. Shifting licks to other beats, off-beat, syncopated variations, picking the same lick different ways - these are all excellent ways to improve your picking ability and ultimately your speed. Good luck!
Comment: Just tried it, and, yes, plan A came out the most effective. And there's not a lot more pick travel needed! For real economy, pull offs worked o.k. for 2nd and 4th notes... Wonder about the term 'correct' - 'more effective' may be more apposite! +1.
Answer: The problem with trying to optimize a 4 note phase inside a longer passage is that you may set yourself up to be sub optimal later on, after the lick you are trying to speed through.
It is commonly assumed that consecutive picking is always optimal but it does not take long to discover that this is false.  Unless the pattern of the lick across strings is the same for a long time, consecutive picking a couple notes then changing can set you up to be either (1) in the wrong direction for something else, or (2) develop an awkward rhythm with your picking hand that never really gets smooth.  Having played professionally for over 30 years I can tell you from personal experience that even with 3 note per string pattern (the poster child for consecutive picking) I can play these across all 6 strings way faster and with more control, in both directions, using alternate picking than consecutive picking.
With alternate picking you have a steady regular movement of (up, down) across the phrase.  Assume for the moment that the phrase is steady 8th or 16th notes for a while (not your lick but it demonstrates a point).  Regardless of the number of notes per string the right hand has an easier job moving back and forth.  Changing string is a matter of opening the elbow, or turning the wrist slightly.  In contrast, trying set up every string crossing to be consecutive set you up to have irregular right hand rhythm pattern.  For the 3 note per string it's something like (short-short-long) = (down-up-down), etc.  This can feel awkward but at the end of the day it's a matter of practice.
Any approach has advantages and potential disadvantages.  If you "pick" one and drill it I'd hope that it would eventually become smooth and comfortable.  If you look at exercises in the Mel Bay series he suggests several picking approaches to every exercises, at the very least all down stroke, pure alternate, then consecutive depending on the placement of the string crossings.
This is a classic song and riff.  Are you sure the TAB is exactly how it's played?  If you apply a pull off to the 3-0, 3-0, licks on the first two strings you could probably use straight down stroke all the way and create a little more of a blues feel.


Configuration Mime Types error

Question: I have a Drupal 8 installation and am developing the site. It's not operational yet.
I have 2 problems i think are related.
First of all a selected image in a custom content type isn't uploaded or shown in new content of the content type. It is a standard image field.
When searching for a solution i got an error log saying that there is a problem with a missing MIME Map extension in sophron. When looking at the Mime types in the Configuration section, my second problem arises.
I get the following error when clicking MIME Types:

The website encountered an unexpected error. Please try again later.
Error: Class 'FileEye\MimeMap\MapHandler' not found in Drupal\sophron\EventSubscriber\SophronEventSubscriber->initializeMap() (line 68 of modules\sophron\src\EventSubscriber\SophronEventSubscriber.php).
Drupal\sophron\EventSubscriber\SophronEventSubscriber->initializeMap(Object, 'sophron.map.initialize', Object)
call_user_func(Array, Object, 'sophron.map.initialize', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('sophron.map.initialize', Object) (Line: 129)
Drupal\sophron\MimeMapManager->setMapClass('Drupal\sophron\Map\DrupalMap') (Line: 105)
Drupal\sophron\MimeMapManager->getMapClass() (Line: 152)
Drupal\sophron\Form\SettingsForm->buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 520)
Drupal\Core\Form\FormBuilder->retrieveForm('sophron_settings', Object) (Line: 277)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 91)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 573)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 694)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Does anyone have an idea?
Comment: How can this be reproduced by others?
Comment: Sounds like you probably didn't use Composer to install the sophron module
Answer: Based on the https://www.drupal.org/project/sophron module page. you should install it with
<code>composer require drupal/sophron
</code>
the error is complaining about missed class that you need to install the module by composer way ( as what recommended in module page)

Installation

Require the module via
$ composer require drupal/sophron
This will download both the module and any dependency. Then, enable
the module as usual.

Configuration Mime Types error


Is it possible to suppress gen 2 GC collection in .NET?

Question: My program allocates a very large number of instances that comprise a long-lived DAWG. During the construction of this DAWG, there are times when the progress slows down 100 fold, and this correlates perfectly with .NET performing gen 2 GC collections. During these periods, the "% time in GC" is 99.5%, and the "total gen 2 collections" increments every few seconds. After several back-to-back gen 2 collections, they stop triggering for no obvious reason and the program speeds up again. A few minutes later, the cycle restarts.
The number of instances I create is on the order of 25 million, and they take up several GB of RAM, so it's not too surprising that the gen 2 collections take this long. What is surprising is that gen 2 collections come in "trains", and get triggered continually.
Can I somehow prevent this without completely rethinking my approach? Perhaps there's some way to ask .NET to suspend gen 2 collections until further notice? The program runs very efficiently apart from these occurrences, so .NET is clearly quite up to this task apart from this unfortunate corner-case behaviour.
(I tried setting GCSettings.LatencyMode to GCLatencyMode.Batch, but the issue remained. The amount of free physical RAM at the time the GCs start happening is around 1GB. This is on a 64-bit machine.)
Comment: "So, don't _do_ that". Seriously, maybe it's time to get "old school" and use, say, five arrays with 25Million entries, rather than 25 Million instances with five properties each?
Comment: @romkyns the struct array/index approach **is** the only way to do this conveniently, though. Anything else is *worse* (unmanaged memory, etc). See mine and Sam's blog entries on this subject: http://marcgravell.blogspot.com/2011/10/assault-by-gc.html and http://samsaffron.com/archive/2011/10/28/in-managed-code-we-trust-our-recent-battles-with-the-net-garbage-collector
Comment: @JohnSaunders Maybe, and I have investigated that approach. Because C# doesn't allow pointers to structs that contain managed types (arrays, in my case), this entails a **severe** drop in maintainability, because everything is now an index instead of a reference to the target class.
Comment: @Timwi: I know the severity. It's just very clear it's time to bite the bullet. Wrap the ugly in an abstraction, but wrap it. This is not premature optimization. It's time to optimize this into something that can possibly work. 25M little instances is outside the design center for CLR memory management.
Comment: This is one of those issues whose severity is difficult to communicate well — other people have to experience the issue before they will sympathise with the gravity of the problem...
Comment: @Marc thanks, looks right on the mark. Given that the DAWG is very cleanly separable from the rest of the C# code, and that the struct array approach pretty much entails managing my own memory anyway, I think this might be a time when dropping down to C++/CLI is actually a better option.
Answer: In .NET 4.5+ you can specify your preference for fewer Gen 2 collections by using the new GCLatencyMode options.
GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;

More info here:
http://blogs.msdn.com/b/dotnet/archive/2012/07/20/the-net-framework-4-5-includes-new-garbage-collector-enhancements-for-client-and-server-apps.aspx

My app cannot tolerate pauses during a certain time window
A growing subset of .NET developers has built commercial apps and
  services that deliver results according to defined business
  requirements or SLAs. Stock markets are examples of services that must
  deliver very timely results while markets are open. Typically, these
  apps perform significant work during the time when they want to
  deliver low-latency results. Yet they cannot tolerate noticeable
  pauses due to a collection.
Our customers have told us that they would deploy more memory on their
  servers if doing so would remove long pause times (which are typically
  introduced by full blocking GCs). In the .NET Framework 4.5, we
  provided that option by introducing SustainedLowLatency mode, which
  avoids full blocking GCs. This mode is also available for the
  workstation GC in the .NET Framework 4 via Update 4.0.3.
While the SustainedLowLatency setting is in effect, generation 0,
  generation 1, and background generation 2 collections still occur and
  do not typically cause noticeable pause times. A blocking generation 2
  collection happens only if the machine is low in memory or if the app
  induces a GC by calling GC.Collect(). It is critical that you deploy
  apps that use the SustainedLowLatency setting onto machines that have
  adequate memory, so they will satisfy the resulting growth in the heap
  while the setting is in effect.
In the .NET Framework 4.5, SustainedLowLatency mode is available for
  both workstation and server GC. To turn it on, set the
  GCSettings.LatencyMode property to GCLatencyMode.SustainedLowLatency.
  The .NET Framework 4 includes a LowLatency mode for workstation GC;
  however, this setting is only intended to be used for short periods of
  time, whereas SustainedLowLatency mode is intended to be used for much
  longer.

There is also NoGCRegion that you can try.
https://msdn.microsoft.com/en-us/library/system.runtime.gclatencymode%28v=vs.110%29.aspx

Indicates that garbage collection is suspended while the app is
  executing a critical path. NoGCRegion is a read-only value; that is,
  you cannot assign the NoGCRegion value to the GCSettings.LatencyMode
  property. You specify the no GC region latency mode by calling the
  TryStartNoGCRegion method and terminate it by calling the
  EndNoGCRegion method.
Answer: Starting from .NET 4.6 you can 'attempt to disallow' garbage collection in a code region by using the GC.TryStartNoGCRegion and GC.EndNoGCRegion methods.
try
{
    GC.TryStartNoGCRegion(TOTAL_SIZE, true);

    <No GC region code here>
}
finally
{
    if (GCSettings.LatencyMode == GCLatencyMode.NoGCRegion) GC.EndNoGCRegion();
}

For more info on the arguments and possible exception see here.
However, there is still no guarantee that GC will not be called. If for example you are using some library in 'No GC region code' and that library calls GC.Collect(), not only that the garbage collection will occur but also exception will be thrown by GC.EndNoGCRegion().
I am afraid you will have to rethink your approach as .NET garbage collection does not seem to be built (as of .NET 4.6) to handle millions of allocated objects with complex relationships between them. NFX library mentioned in one of the posts here is an option as well as using structures, simplifying model to reduce relations, use indexes into arrays instead of references etc.
Comment: The `TryStartNoGCRegion` needs to be outside the `try` block.
Answer: We had the similar issue with caching social+routing data.
We had to cache hundreds of millions of entries as storing this out-of-process was not fast enough due to network traffic (even on local host).
Instead we created a special 100% managed memory manager that allocates byte[] segments and the sub-allots the space there. The objects from CLR heap are turned into "PilePointers{int segment, int address}" via a special binary serialization which is orders of magnitude faster than BinaryFormatter. So now, the object graph of any complexity and size may be stored for a LOMG TIME in the managed heap, yet GC blocking pause < 10 ms, full GC is around 30-60 ms.
We store 300,000,000 objects easily on a 64Gb PC, and the most interesting part of it is this: the solution works WAY FASTER than storing objects in an un-managed heap via Marshal or out-of-process via redis/memcache.
See this:
Pile:
https://www.youtube.com/watch?v=IUBF2Ncvbbs
Cache:
https://www.youtube.com/watch?v=Dz_7hukyejQ
Get the code (Apache 2):
https://github.com/aumcode/nfx
Answer: No.
You can't suppress it because it's necessary to guarantee the correctness of the program (at least so far as the framework is concerned).
Simply put, the CLR doesn't let you live this dangerously. If you need manual memory management, then you have to make your own data structures out of structs, and manage everything manually.

That said, 25 million is a lot of objects, but it shouldn't be several gigabytes unless your objects are also relatively large. Can you use arrays of structs instead of classes to avoid the extra references? Is there any information you can remove?
Comment: That is explicitly false.  The null GC is fully valid, from a specificational point of view.  http://blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047586.aspx
Comment: Any references? Since when is GC necessary to guarantee correctness? Is my program incorrect during the minutes when no gen 2 GCs occur?
Comment: @romkyns: That's because you know *a priori* what's going to happen. The obviously GC doesn't, so it tries to clean up because it's pretty confident that allocating objects at such a high rate jeopardizes the program. So it puts all its effort into making sure your program has as much memory as needed to run correctly.
Comment: True, which is why I was hoping I could give it a hand. There's nothing wrong with clever algorithms that sometimes need a hand. The GC already provides several ways in which I could give it hints, so it was not an unreasonable assumption that there might be a way to nudge it in the right direction in my situation.
Comment: @romkyns: I said guarantee correctness *at least so far as the framework is concerned* -- in other words, the GC is designed to simulate infinite memory for your program as well as possible, and as such, it would remove this guarantee on your program (and hence jeopardize its correctness) if it allowed for disabling itself.
Comment: @SLaks: The null GC is **only valid** if there is no need for clean-up. In this case, though, there certainly *is* a need, so the null GC isn't valid.
Comment: @Mehrdad Firstly, there is *no need* to clean up; the gen 2 GC doesn't clean up anything; all the long-lived objects remain alive. Secondly, not removing junk is not invalid if you don't run out of memory - and I don't.
Comment: @romkyns: Oh of course -- I wasn't saying it was unreasonable, I was just explaining why it isn't possible in .NET (strong framework guarantees = less custom control). :)


Format specifications for real numbers

Question: I would like to print some real numbers to a log file.  To make them easy to read I would like them to all have the same width.  I know these numbers will range from 0 to 4095.75 so I tried this:
$display("expected= %4.2f, actual= %4.2f", expected, actual)

What I expected to see was this:
expected=   12.25, actual=   12.75
expected= 4093.25, actual= 4094.75

But what I got in was this:
expected= 12.25, actual= 12.75
expected= 4093.25, actual= 4094.75

How do I force the width of the value above the decimal point to be 4 characters?  Section 126.96.36.199 Size of displayed data of the LRM is silent on %f.
Answer: Using %7 works for your values with 2 simulators I tried:
module tb;

real expected, actual;

initial begin
    expected = 12.25; actual=   12.75;
    $display("expected= %7.2f, actual= %7.2f", expected, actual);
    expected= 4093.25; actual= 4094.75;
    $display("expected= %7.2f, actual= %7.2f", expected, actual);
    #5 $finish;
end

endmodule

Output:
expected=   12.25, actual=   12.75
expected= 4093.25, actual= 4094.75

Comment: Stupid me assuming that the first number referred to what happened before the decimal point instead of the total length of the field.
Comment: @nguthrie: That was just a wild guess on my part.  The IEEE Std 1800-2012 does not explicity show the %X.Yf syntax.  It just alludes to the C language.  Behavior might be system-dependent, too.
Answer: It is possible also to specify how many number we want to see for floating point vars, after comma:
    `uvm_info(get_type_name(), $sformatf("tslot_start=%.3f, tslot_start_tolerance=%.2f",
tslot_start, tslot_start_tolerance), UVM_LOW)

Format specifications for real numbers


Modified version of heat equation

Question: Consider the following equation:
$$u_t(t,x)=\frac12u_{xx}(t,x)-x\cdot u(t,x),\qquad u(0,x)=x\exp(-x^2/2).$$
After searching in Wikipedia, I can see that this is similar to the heat equation, with an extra $-x\cdot u(t,x)$ term.
Given that I know very little PDE theory,
I usually use mathematica to analyse them. However, mathematica doesn't seem to do anything with the formula, which I interpret as it saying that it can't find a solution.
After looking in the wikipedia page for the Heat equation, I've tried writing $u(t,x)=a(t)b(x)$ and then reasoning about this, but it leads to a contradiction. Are there elementary tricks that would be expected to work in such a case, or is this equation well-known and have a name?
Comment: The trick you tried is called 'separation of variables' and is a reasonable first try.
Answer: Separation of variables works.  You get $u_t = a^{\prime}b$ and $u_{xx}=ab^{\prime\prime}$, so that your equation becomes $$a^{\prime}b ={1\over 2}ab^{\prime\prime}-xab = \left({1\over 2} b^{\prime\prime}-xb\right)a.$$
Divide by $ab$ to get $${a^{\prime}\over a} =\frac{\left({1\over 2} b^{\prime\prime}-xb\right)}{b}.$$
Since the left side is a function of $t$ alone and the right side is a function of $x$ alone, the two sides must be equal to a constant $\lambda$.  So we have two ODE's:
$$a^{\prime}(t) = \lambda a(t) \mbox{ and } {1\over 2} b^{\prime\prime}(x)-(x+\lambda)b(x) = 0.$$
Without some boundary conditions (like $u(t,0)=u(t,\alpha)=0$), it's hard to continue, but the solutions for the second equation will be in terms of Airy functions.  The choice of $\alpha$ might determine values of $\lambda$, in which case the first ODE is easy to solve.  You may get a sequence of solutions $u_{\lambda} = a_{\lambda}b_{\lambda}$ for whatever $\lambda$'s work.  Then some linear combination of the $u_\lambda$ could be forced to make $u(0,x) = x\exp({-x^2/2}).$

Modified version of heat equation


Problemas no PUT com Spring data JPA

Question: Estou usando arquitetura Controller, DTO, Repositoy, Service
Uso Postman para testar as requisições, eu consigo fazer POST no Usuario normalmente e quando faço GET o Postman me retorna
{
    "id": 3,
    "nome": "Arthur",
    "cpf": "281.590.328-89",
    "cnh": "35214349616",
    "telefone": "(61) 99805-2147",
    "email": "email@example.com",
    "senha": "1234",
    "perfil": "alugador",
    "endereco": {
        "id": 3,
        "logradouro": "Quadra SHPS Quadra 502",
        "bairro": "Setor Habitacional Pôr do Sol (Ceilândia)",
        "numero": 927,
        "complemento": " ",
        "cidade": "Brasília",
        "estado": "DF"
    }
}

Faço POST no Carro passando id do Usuario e o GET me retorna:
{
    "id": 4,
    "usuarioRegistrador": {
        "id": 3,
        "nome": "Arthur",
        "cpf": "281.590.328-89",
        "cnh": "35214349616",
        "telefone": "(61) 99805-2147",
        "email": "email@example.com",
        "senha": "1234",
        "perfil": "alugador",
        "endereco": {
            "id": 3,
            "logradouro": "Quadra SHPS Quadra 502",
            "bairro": "Setor Habitacional Pôr do Sol (Ceilândia)",
            "numero": 927,
            "complemento": " ",
            "cidade": "Brasília",
            "estado": "DF"
        }
    },
    "kmsRodados": 555.0,
    "documentoCarro": "555",
    "tipoCombustivel": "55",
    "marca": "CAMARO",
    "modelo": "GOL BOLA",
    "placa": "TTT-1555",
    "valorCarro": 363636.0,
    "estaAlugado": true
}

Quando faço um POST no Aluguel, passando id do Usuario e id do Carro, o GET me retorna "carro":null
Alguém pode me ajudar?
{
    "id": 7,
    "usuarioCliente": {
        "id": 3,
        "nome": "Arthur",
        "cpf": "281.590.328-89",
        "cnh": "35214349616",
        "telefone": "(61) 99805-2147",
        "email": "email@example.com",
        "senha": "1234",
        "perfil": "alugador",
        "endereco": {
            "id": 3,
            "logradouro": "Quadra SHPS Quadra 502",
            "bairro": "Setor Habitacional Pôr do Sol (Ceilândia)",
            "numero": 927,
            "complemento": " ",
            "cidade": "Brasília",
            "estado": "DF"
        }
    },
    "carro": null,
    "retirada": "2009-08-07",
    "entrega": "2019-08-04",
    "valor": 99.0
}

Answer: confira se no DTO, vc esta passando o carro
public static AluguelDto converteEntidadeEmDto(Aluguel aluguel) {
        AluguelDto dto = new AluguelDto();
        dto.setId(aluguel.getId());
        dto.setEntrega(aluguel.getEntrega());
        dto.setCarro(aluguel.getCarro());
        dto.setUsuarioCliente(aluguel.getUsuarioCliente());
        dto.setRetirada(aluguel.getRetirada());
        dto.setValor(aluguel.getValor());
        return dto;
    }
public static Aluguel converteDtoEmEntidade(AluguelDto dto) {
    Aluguel aluguel = new Aluguel();
    aluguel.setCarro(dto.getCarro());
    aluguel.setId(dto.getId());
    aluguel.setEntrega(dto.getEntrega());
    aluguel.setRetirada(dto.getRetirada());
    aluguel.setValor(dto.getValor());
    aluguel.setUsuarioCliente(dto.getUsuarioCliente());
    return aluguel;
}

Problemas no PUT com Spring data JPA


Python - evaluate a function with for

Question: I want to evaluate discrete points of a function for each value of a given array (named wl). So far I have:
from pylab import *
import numpy

#wl is a defined list
a=1
b=3934.3
c=0.2885
for x in (wl):
    G[x]=a*exp(-(wl(x)-b)^2/c^2)

but I get the error TypeError: 'numpy.ndarray' object is not callable. What I need is a second list named G whose values correspond to the evaluated function at each value in the list wl.
What does this error mean? Should I somehow define G before?
Thanks.
Comment: It's not actually defined as a list. This is your problem: `wl(x)` What is your intent?
Comment: Maybe you are thinking it in a too complicated way and just mean: G = a*exp(-(wl-b)^2/c^2) ? If wl is a numpy array, that'll give you the gaussian function. No need for any loops.
Comment: You say `wl` is a list, but you're calling it as though it were a function. Which is what the error says.
Comment: Please supply the whole traceback, not just the error.
Answer: G=numpy.exp(-(wl-b)**2/c**2)*a

I think would work ... since you can often drop in whole numpy arrays' like they were a single value and get back a new array of calculated values
(changed ^ to ** since I think you want power not bitwise XOR)
you can see this behavior like so
t1 = numpy.array([1,2,3])
print t1 - 1
print t1 * 2
print t1 ^ 2
print (t1^2)*2

Comment: Thanks, I didn't know they can be treated like this. However I get an error in relation with another function: `TypeError: ufunc 'bitwise_xor' not supported for the input types`.
Comment: ^ is XOR not power if you want power use `**` since your list is floating point numbers it doesnt know how to XOR  against a  (or something like that at least... )
Answer: If wl is a list (or numpy.ndarray) you can't do wl(x).
Probably you need x in place of wl(x) in a*exp(-( wl(x)-b )^2 / c^2)

Python - evaluate a function with for


Salvar associações cakephp 3

Question: Estou tentando salvar dados associados em Cakephp 3, no banco de dados tenho duas tabelas tabela entidades(id, nome_principal) e enderecos(id, entidade_id, cidade)
Em EntidadesTable eu realizei a associação:
$this->hasMany('Enderecos', array(
    'className' => 'Enderecos',
    'foreignkey' => 'entidade_id',
    'joinType' => 'INNER'
));

No controller Entidades eu salvo com os seguintes dados:
$entidade = $this->Entidades->newEntity();

if ($this->request->is('post')){
    $entidade = $this->Entidades->patchEntity($entidade, $this->request->getData());
    if ($this->Entidades->save($entidade)) {
        $this->Flash->success(__('Entidade cadastrada com sucesso!'));
        return $this->redirect(['action' => 'consultar']);
    } else {
        $this->Flash->error(__('Ops, algo deu errado, verifique se os campos foram preenchidos corretamente!'));
    }
}

$this->set(compact('entidade'));

E na view, meu form está assim:

Nome

<input type="text" id="nome_principal" name="nome_principal" placeholder="Nome" class="form-control input-md">

Cidade

<input type="text" id="cidade" name="cidade" placeholder="Cidade" class="form-control input-md">

Os dados da entidade salva normalmente no banco de dados, mas o entidade_id e cidade da tabela enderecos não salvam, alguém consegue me ajudar?
Comment: Por favor não esqueça de mencionar a versão exata do CakePHP (última linha em vendor/cakephp/cakephp/VERSION.txt ou lib/Cake/VERSION.txt)
Answer: Editei o patchEntity passando a chave associated que informa o model associado que será salvo:
$entidade = $this->Entidades->patchEntity($entidade, $this->request->getData(), ['associated' => ['Enderecos']]);

Aqui eu criei seus inputs utilizando o FormHelper seguindo o padrão de dados associados:
echo $this->Form->control('nome_principal', ['id' => 'nome_principal', 'class' => 'form-control input-md', 'placeholder' => 'Nome', 'label' => 'Nome']);
// Enderecos controls (hasMany)
echo $this->Form->control('enderecos.0.cidade', ['id' => 'cidade', 'class' => 'form-control input-md', 'placeholder' => 'Cidade', 'label' => 'Cidade']);

Veja Saving HasMany Associations e Converting Request Data into Entities para mais detalhes.
Comment: Fecho o balão Rayann, obrigado pela ajuda!

Salvar associações cakephp 3


What does Axiom of Choice know about when Creating a Vitali Set?

Question: An Vitali set $V$ is constructed in https://en.wikipedia.org/wiki/Vitali_set by applying $\textsf{AC}$ to pick a single element from each of the countable equivalence classes in $\mathbb R / \mathbb Q$, restricted to the interval $[0,1]$.
The interval $[0,1]$ is then reconstructed (and additionally as a by-product of the method of construction, with extra elements in the range $[-1,2]$), from these equivalence classes by forming for each element $q_k$ $\in$ $\mathbb Q$ restricted to $[-1,1]$, the disjoint sets $V_{k}$ defined as:
$$V_{k}=V+q_{k}=\{v+q_{k}:v\in V\},$$ where $V$ is the Vitali set, and
$$[0,1]\subset\bigcup V_k \subset [-1,2].$$
By usage of $\sigma$ additivity and invariance under translation of the measure $\mu$
$$\lambda (V_k) = \lambda (V),$$
we get \begin{equation}1\le\sum_k \mu(V)\le 3\label{1}\tag{1}\end{equation}
However, if in $(\ref{1})$, the countable sum is replaced by $\omega$, then $(\ref{1})$ could become, for example:
\begin{equation}1\le \omega * \mu(V)\le 3\label{2}\tag{2}\end{equation}
or
\begin{equation}\displaystyle \frac{1}{\omega}  \le \mu(V)\le \frac{3}{\omega}\label{3}\tag{3}\end{equation}
As creation of a Vitali set via the use of the axiom of Separation isn't possible, then 'in effect' $\textsf{AC}$ is providing a 'supercharged' axiom of Separation to create the Vitali set.
Does this use of $\textsf{AC}$ mean an uncountable $\mathbb R $ sized "equivalent expression" could be thought of as being used in the axiom of Separation, which means in $(\ref{3})$ it can lead to the knowledge of very small number types (e.g. Surreal Numbers etc.) or to an extension of the Lebesgue measure to include non-standard number types?
Comment: The Axiom of Choice is just a sentence in the language of set theory. Much like Jon Snow, it knows nothing.
Comment: And there was me thinking that AC was like Lord Varys who knows everything (and much more than the axiom of Separation).
Answer: What you are doing makes no sense. Cardinals and ordinals are not real numbers. If you want to think about them as surreal numbers, then you need to give up their standard arithmetic (in the case of cardinals you need to forfeit everything, in the case of ordinals you need to resort to "natural/Hessenberg sums" instead which tend to disagree with the standard arithmetic in most cases).
So there is no sense in moving from the sum to multiplying a constant by $\omega$. You're just mixing up concepts in a way that makes no sense.
Comment: As I said, you're mixing concepts. (This is my gripe with modern internet-based education (see also [this.](http://karagila.org/2017/dangerous-knowledge-in-the-information-age/))) The $\omega$ used in the sentence you're citing is not the *standard* use of $\omega$ in set theory, and you would need to specify the context for it. Moreover, it's still not *the same* as just infinite summation and you're just mixing up concepts that have no business being mixed up.
Comment: And as you can see, it's not a very well form idea to begin with.
Comment: @ Asaf Karagila : Lectures on the Hyperreals, R. Goldblatt, 1998, Section 3.8, page 27, derives the expression: 1/ω=ϵ where ϵ is an infinitesimal and ω is an unlimited number. It says "The properties observed of ϵ and ω show that ∗R is a proper extension of R and hence a new structure". So in a hyperreal number system the expression (3) has meaning when μ(V) is replaced by ϵ. Similarly hyperfinite sums can exist. As a result does this not explain why a Vitali set is not Lebesgue measurable because use of AC for Vitali sets means that infinitesimal numbers are 'effectively' created ?
Comment: @ Asaf Karagila. The use of hyperreals in Vitali sets is discussed here : https://math.stackexchange.com/questions/257655/hyperreal-measure.


On instruments that use frets, where's the best spot to press a string on, in order to minimize hand fatigue and potential for injuries?

Question: I know this question sounds completely subjective at first sight, it even triggered the automatic "The question you're asking appears subjective and is likely to be closed" alarm, but please read further.
Action is the distance between the fret and a string at any given fret (in fretted instruments). Normally at the 12th fret, but some instruments have less than 12 frets, so the convention might be at the 10th fret for other instruments, or any other fret really.

"What's the best action" is completely subjective under most contexts. The lower the action the less force you'll need to press the string, but the more likely it is to buzz (touch a fret you are not fretting). It can also change stuff like tone and loudness (I don't know the actual acoustic basis of these changes, but that's for another question).
So the best action is the best balance between ease of play, good tone, good loudness. This is completely subjective, until you reach an edge case: action that is too high. If you can't finish a song, or a full performance, or get too tired, or feel too much pain, then you can say, objectively, that the action is too high.
If you are not using amplification, high actions might be more fitting. Or low actions for old guitars, or some specific guitar tones. Maybe a middle ground for recording. Some don't care, most will notice immediately an action that is too high.
And that can be a big game-changing problem. Sometimes you just need to make the gig / recording happen with someone else's instrument. Sometimes you are just playing an instrument you are not proficient at, but the circumstances called for it (last-moment changes in a band you direct, a favor, you are drunk). Maybe your hand is tired. Maybe you have less calluses than two months ago. There's an endless list of situations where action can come back to bite you, so knowing how to minimize its influence seems like a very useful tool.
That's where "On instruments that use frets, where's the best spot to press a string on?" stops becoming subjective. If said instrument happens to have too high an action, if it's high enough, you can risk not only fatiguing your hands and fingers before you can end the first song, but there's high potential for injuries and pain, both short and long term.
So, where can the string be pressed, so the least amount of force needs to be applied in order to touch the fret? Barely touching the fret is not enough, but maybe we can oversimplify that one? Or is calculating the exact extra force needed in relation to the force being applied with the strums / picking needed? I guess another way of viewing it is, where between the frets is there less string tension while pressed? Is it near the sharper part of the fret (assuming a non-ideal fret that has mass)? Or near the flatter part of the fret (sharper part being the one pointing towards the side in which pitch increases, flatter being the opposite direction)?
Or is it in the exact middle, between the frets? If it's not, why is it less tension near that fret, and not near the other, neighbor of the same string? There must be an actual objective, measurable, repeatable way to answer this, right? One that can use to optimize our technique, even if we are not struggling with action (that was just one example of many where this info would be very valuable).
Another situation where this is objective, relevant, and has the potential to prevent injuries, is in instruments and fingerings where stuff like "half barre" is used, like a barre chord but you need to let some strings that are located below the barre finger sound, so you need a kind of bridge shape, making your fingers do bends that your classically-trained teacher will faint at. Putting so much force on a finger that's so weirdly collapsed is a no-no (some try to prevent collapsed fingers at all). But for instruments where non-ergonomic positions are the norm, knowing exactly where to put that finger can make all the difference.
In other words, how can we know exactly where to press a string in order to apply the least force possible to reach the fret?
Comment: I was taught to hold near the corresponding fret. My tutor said you'd need lesser force, I also learned that lesser holding near Fret is better in terms of pitching too. Increasing Tension and Decreasing Effective Length from the Corresponding fret to bridge happens when Sstring is heeld too far behind the fret. I don't know about Fatigue or Injuries tho, My tutor said that I'd never get to call myself a guitar If I haven't had a cut in my finger yet. I don't think this has anything to do with injuries. Injuries happen if you posture is off.
Comment: Directly above it pretty obviously distorts the sound. I'm not sure about why its not somewhere in the middle but I'm sure it's not near previous fret. 1. Previous Fret Restricts Pressing of String and Normal Reaction from Previous Fret will make you to Exert More Force to Press. (contd)
Comment: 2. String is pressed so that the place where the fret is becomes a Node for the Vibrations in String so That Fundamental Tone and Frequency Changes, Primary goal is to hold string against corresponding fret. If you notice carefully, String will curve from the place you held, if distance b/w fret and hold increases, buzzing might happen as string might go too far from fret, When I started playing, I noticed that Holding too far from fret made the sound damped and only then I started holding near fret.
Comment: I'm having trouble with this question because you seem to be making a strict association between action and required pressure. I don't think that's the case. The pressure to get a clear note will depend on a number of factors; to me action is more about the speed at which you can fret and unfret, since action represents the distance you have to move the string until it contacts the fret. I don't think the answers you've gotten so far are incorrect, but I was a little thrown off by that.
Comment: The thing is, I haven't answered your Primary Question yet. I'm sharing things like where not to, and what I was told
Comment: @dwizum it might not be noticeable for a guitar, but for a bass it is clearly the case, there is a "spring force" added because you bend to string more (try to do a bend on a E string near the head and you'll have a clear notion which force it is). It's not clear the OP is talking about a bass or a guitar though..
Comment: The problem with answering this question is that the parameters are not clearly defined.  How clear does the tone have to be before we consider that the string is well and truly pressed down?  How high is the fingerboard between the frets/ how high are the frets?  This affects how far back we can play from the fret and still get an acceptable tone.
Comment: *The higher the action, the more tension you have to apply to the string for it to reach the fret* yes, true - but the tension required to get the string to the point of first contact with the fret is orders of magnitude smaller than the tension you *then* add, bending the string down past the fret, to get a clear note. Ultimately though, my point in that comment was more about how I'm not sure why you're focusing so much on action, when your actual question doesn't even mention action, and correct answers to your actual question don't really even depend on taking action into account.
Comment: I wouldn't even want to play the guitar shown in the picture. The action is way too high for me. Might use it as a slide guitar, but that's all.
Answer: Producing a sharp angle for the string over the fretwire makes for a clear, clean sound. So just behind the fretwire will be a good place. It also means not having to press down on the fingerboard so hard - keep the same pressure on and move a finger around on a fret - lower, wider frets will show better, and you'll find more pressure is needed for a clear note at the back end of a fret - closer to the nut.
There's also a couple of other factors involved here though. One is tuning. At the back end of a fret, a string will become slightly sharper - that's one aspect of 'classical' vibrato. So to be properly in tune, close to the fretwire makes more sense.
All this falls by the wayside somewhat when we consider chords (I'm on guitar here). Often, there's not enough space for optimum finger positioning, so compromises have to be made. That's just one reason why beginners struggle with barre chords. Collapsing fingers is necessary on some shapes - there's no other way to press strings sometimes.
On injury - most players manage to play without injuring themselves - there's a sort of warning, called pain. That works quite well, if attention is paid to it! There's probably more injury likelihood from pressing too hard, which often reveals itself in pain round the base of the thumb. That's sometimes due to bad action, but more likely due to the player not being aware of hand/finger (and arm) position. Partly, I suspect, the reason for the question.
Having said all that, on guitar at least, past fret 12, there's not much choice as to where to press! Bass is obviously different, and a lot of the time, only single notes are deployed. Get a mandolin and again, the question is academic.
Comment: I cannot envisage why an extra high action could be a 'good thing'. Unless it's slide - but not on nylons!
Comment: And with a high action comes the propensity to stretch strings out of tune as they are fretted. Not good practice. And slowing down playing, due to greater stress, etc. Perhaps the question of optimum string height is also important.
Comment: If a Guitar was made for High Action, It's Frets would be spaced accordingly so that effectively, the length of the string when Fretted matches Length of String in a Regular Action one. (just addingon your point @above)
Comment: I think adding a little more explanation (or link to other question) about the hand positioning might be nice. I know that was my reasoning in reading this question because I feel like I do barre chords wrong because I end up with aching hands afterwards.
Comment: Is there an explanation why "At the back end of a fret, a string will become slightly sharper" might happen? (it doesn't, and classical vibrato works in different way, but let's just have it for explanation's sake)
Comment: @Tim pressing harder can certainly make the note sharp, but the effect is largest right at center between frets. Classical vibrato works because finger grips the string and rolling back and forth pulls the string slightly tighter and looser. You can bend classical guitar string to slightly lower pitch, and that wouldn't work with just pressing harder. You can do the same with wound strings of steel string guitar, but the pitch change is very small.
Comment: @ojs - I see now. I had a student who used to make his vibrato by actually pressing harder and releasing, but that's pretty unusual.
Comment: @MatthewGreen - there are many reasons why players - particularly beginners - get aches from barring chords. Bad actions, pressing too hard, not trying other fingerings, guitar slung too low, +, +, +.
Comment: @ojs - because the string needs pressing harder when the fingertip is at the back of the fret, it's under more tension, so sounds (slightly) sharper. You say classical vibrato works in a different way - please enlighten me. There is a subtle tonal change too - is that what you infer?
Comment: @ojs - so you've said that the string's pitch is sharper when the finger is rolled, due to higher tension. We seem to agree. That's what i was saying.
Comment: The difference I was after is that with finger rolling technique, you pull the string towards nut or bridge. When you press the string hard, you pull the string away from both.
Answer: The proper place to fret a string is close to the fret wire.  Your finger should be right behind the fret.  You should not have to apply a lot of force to depress the string.  A lot of beginners make the mistake of thinking that you can place the finger anywhere between the frets with the same result, since the fret defines where the string stops, but this is completely false.  If you finger the string too far behind the fret, the string will slide back and forth along the fret, causing slight pitch changes and buzzing.  If you play forte like this, the string will buzz horribly against the fret.  Sometimes, when playing complicated chords, we need to make sacrifices and one string might not be depressed with the ideal technique. But as much as possible, the finger should be just behind the fret, even touching it, but not right up on top of the fret, as that will cause the flesh of the finger to go slightly over the fret and dampen the sound.
The second mistake people make is that they think they have to press down until the string touches the wood on the finger board.  This is also completely false.  You only need to press with enough force to get the string to hit the fret and not buzz, and this is usually much less force than people assume is needed.  Ideally, the fingers need never touch the finger board.  In my opinion, this mistake is most often the cause of sore and tired hands.  Learning the correct grip for your action is crucial for getting good sound and maintaining your hand (and instrument) health.
How high is high action? It's really hard to judge.  My classical has very high action relative to my electrics, yet it is no harder to play.  With high action, you will need to move more to release the strings and move from one note to the other, which in the long run may make speed more difficult, but I'd say that if you practice proper hand placement, you should be able to hold a chord with a relaxed hand (without a strong grip).
The way I was taught grip was to put the finger on the string in the correct place with NO force, start playing that note over and over.  As you play, slowly press the string until you get a clean tone with no buzzing.  This is all the force you need.  The tricky part is training yourself to apply only this much force as you play fast and move around.  That's decades of practice.
Comment: I didn't mean to imply its easier but if you finger at the opposite fret it will buzz.   If I understand you correctly
Comment: Tried playing my steel string acoustic with relatively low action and light strings without the string touching.  Even with my fingers right behind the fret on the thinnest strings, the string always touched the wood.
Comment: @pro, not sure what to say to that.  The real question is does it need to to not buzz?  It is common to want to do this, and many guitarists do myself included sometimes.  But I can get very clean full sound without going that far, especially on the classical.  Are your frets very low?
Comment: @ggcg I don't know what "very low" means, precisely.
Comment: If the fret are filed down so they are not high.  This happens over time due to the need to file them down when they are dented from playing
Answer: The question is in no way subjective and the result can be found out very simple by experimenting and testing  the sound.

If you press the string too close to the fret end or right on the fretwire the string vibration will be inhibit and the sound becomes dull and dumb.
If you press right behind the bend where the string is laying on you need the minimum of strength and the sound is perfect.
When we press in the middle between two frets we may need less strength - referring the law of lever act - but the string starts to vibrate and to clank above the iron fret.
At the end close to the next lower fret all action is useless as we are too for from the bridge which is built by the fret that divides the string.

I've never been taught Guitar playing. But you can test this physical experiments by yourself and the facts are quite logical.
As a supplement: the string is pushed down just behind the collar so far that it has a clearly defined support.  Then it can swing freely and sounds good.  If you press too hard, it gets tiring, the playing speed slows down and - the notes are often not quite correct anymore, because the string is stretched too much when it is pressed down onto the wood  until you hear a clear tone.  If you press too lightly, the string hums.  If you press too hard, you won't last long because your fingers become "tired".  You have to find a middle ground and train.  Your fingers will hurt at the beginning.  But that stops as soon as the cornea has formed.
The italic text is an answer from here:
https://www.gutefrage.net/frage/gitarrensaiten-durchdruecken-oder-finger-nur-auflegen

There must be an actual objective, measurable, repeatable way to
  answer this, right? One that can use to optimize our technique, even
  if we are not struggling with action.

I suppose you have already made the similar experiences as I but you are interested in the physics and the perfect point.
A fisher, a boatman, a mountaineer, a bell ringer  ... they all know that the longer the longer one side of the move moment is the less strength we need.

But the trouble is: the longer we are distant from the point it starts to linger. So you have to make a compromise.
So there is no 'perfect' point - but an optimal place:

On the basis of the locations of fulcrum, load and effort, the lever is divided into three types. It is one of the six simple machines identified by Renaissance scientists. A lever amplifies an input force to provide a greater output force, which is said to provide leverage. The ratio of the output force to the input force is the mechanical advantage of the lever. As such, the lever is a mechanical advantage device, trading off force against movement.
https://en.wikipedia.org/wiki/Lever
Comment: I say: this is all correct, also what you say what others say. You can test it yourself :)
Answer: Luckily, you can answer this yourself, objectively, with the exact instrument you're wondering about.
Get a capo with adjustable tension. Or, rig a clamp or some other method to press the strings with a consistent and adjustable pressure. Place the capo in a given position relative to a fret, and add tension until a normally-plucked string stops buzzing. Record the tension (i.e. the number of turns or whatever adjustment you've used). Try again with a different position, and compare the results.
Ultimately, this will confirm what Tim's answer describes - pressing immediately behind the fret will give the clearest sound for the least pressure.
As a further answer to something indirectly related to your question, you spent a lot of time in your question talking about action, and the effect that action has on required pressure to fret a string cleanly. Specifically, you said:

The lower the action the less force you'll need to press the string

You can use this same method to test that, as well - set the action low, test the pressure required, then repeat with a high action. I'm confident you'll find that action doesn't substantially change the pressure required to get a clean note - the pressure needed to move the string from it's resting position down to the point at which it first contacts a fret will be trivial compared to the pressure needed to bend the string over the fret far enough that the note is clean.
Action impacts speed more than pressure. With a high action, it simply takes more time to press the string down into position, so it takes more finger speed to change notes quickly, which can be perceived as requiring pressure - and, indeed, some beginners try to compensate for slow fingers by pressing harder, which - ironically - is really the opposite of the true solution (pressing just barely hard enough to get a clean note will allow you to move faster). Beginners may also perceive that a higher action wears them out more quickly, but again - that is more due to attempts to compensate for speed than for pressure required.
Comment: When fretting near the nut, the pressure needed is tangibly higher for a high action than for a low action.
Comment: I guess I'm confused about how you are able to attribute the calluses to requiring more pressure on the string due to a difference in action. Are there no other differences at all between the two instruments? You seem to be describing the results of changing between specific instruments/setups, which makes it difficult to extrapolate to general statements because none of the rest of us know exactly what change has happened. I don't think what you've said here means my last paragraph is wrong, but I do think we're not understanding each other fully.
Comment: I've been not only playing, but also building stringed instruments (acoustic and electric guitars, tenor guitars, basses, and ukulele mostly) for nearly three decades. I have a list of clients who've played and recorded on instruments I've built from scratch who would vouch for me not being confused about the basics. If anything, I suppose I should apologize for not writing in a clear enough style for you to understand what I'm saying. I'd be willing to bet that if we sat down in person and looked at your instruments together, we could have an intelligent conversation about this.
Answer: If you're playing a guitar, somewhere behind the fret is best.  It depends on whether you're playing chords or single notes, but somewhere from the middle to just behind the fret works well.
If you're playing an electric bass guitar then pressing directly down on the fret is best.  If you press between the frets then you will need to provide more force which may injure the joints of your fingers.  Trust me, I know.  I did it the wrong way for years and paid the price.  The slight loss of sustain really isn't noticeable in the bass guitar.
If you're a skeptic about the suggestion for the bass guitar, then I suggest you check out  Peter Murray's "Essential Bass Technique: The Definitive Technique Manual for Bass Guitar" which helped me greatly improve my right and left hand technique.
Comment: That's a new one on me. Press down **on** the fretwire? Might depend on style of playing. Certainly no vibrato would be available that way - but it would aid transition across to fretless...
Comment: @Tim I think it's debatable though. I like with some cute melodic lines on the acoustic bass to play sometimes on the fret, even fingers crossing a bit the line to the right to produce a smooth sound, however when playing with my metal band, the loss of sustain would be totally noticeable (not only sustain, sharpness too), so keeping it just behind the fret is needed. Never completely between the frets though, I agree on this.
Comment: If what you say is true, and common, just about every bass guitarist should be at risk. In 40+ yrs playing between the frets, am I just lucky?
Comment: @Tim well it depends on your physiology, past life and instrument. I have a long scale bass with fattest strings I can buy. I don't have weak hands but injured both thumbs in other activities. Now I can't play more than 2h/2h30 long with this bass without pain, if I use another bass I can play longer
Comment: @Kaddath - very small hands. 5 string - .040 -  .120" strings, but beautiful actions. I tend to play SGC Nanyo Bass Collections. 34-35" scale - and *don't* press hard with thumb - or anything! Surely fat strings = more pressure needed?


PYTHON is UNFAIR. Its treating list and a non list variable with partiality

Question: With the example code below:
mat = []
x = 5
def add(c,b):
        print c+b
        x = 8
        mat.append(c)
        mat.append(b)
add(5,6)
add(8,9)
print mat
print x

mat is getting appended but why isn't x changing? Why is python treating the list and a variable a different way?
Comment: http://stackoverflow.com/questions/146359/python-scope
Comment: How do you expect python to treat them the same if you don't treat them the same yourself? You mutate `mat` but assign something new to (a new) `x`. Try `mat = [8]` inside the function instead of `mat.append` and you see that now the list isn't treated any different. Any mutation will carry on and any asignment won't.
Answer: Don't think of variables in Python as named boxes in which you store data. Think of them as nametags you stick on objects.
In your function, you are sticking the name x on the object 8. This is a local name, so it goes away when the function ends. Inside the function, the local name x "shadows" (prevents access to) the global name x so the global name x is not affected by the assignment. It still points to the object 5 and when you print it outside the function, that's what you get.
You are not changing what object the name mat refers to inside the function. Rather you are changing (mutating) the object pointed to. A method call, even one that changes the object, is not the same as an assignment. No local name mat is created so you are mutating the same object you created outside the function.
This is a common pitfall for beginning Python programmers, but it is understood easily enough and once understood, does not pose any significant difficulty in programming in the language.
The fact that you don't understand something doesn't make it "UNFAIR." Python has been around for more than two decades. It was designed by very smart people and is used by, probably, tens of thousands of programmers around the world. If there were something wrong with Python at this fundamental of a level, it would have been fixed by now.
Comment: @surya, x was visible - until you hid it by creating a local variable also called x. Had you done mat=[c,b] you would have seen the same behaviour there.
Comment: I agree that python is one of the best languages designed by experts and smart people. And I agree with ur explanation. But my question is how is mat visible inside the nested function? if mat is visible, so should be x? Python should be reasonable right.
Comment: @Dave, x is not visible inside the function add(c,b). without assigning 8, i tried to print it. it resulted in a traceback
Comment: @surya what version of python are you using? Because that is categorically not the behaviour I get with 2.7. It prints x happily. The only way I can get a traceback is if I try to print a new variable, in which case it throws a NameError: global name 'y' is not defined. If there had been a global variable of that name, it would have printed it.
Comment: There will be an `UnboundLocalError` when you try something like `x += 1`. That is a hickup and arguably a flaw in the language but it can be handled by calling `global x` beforehand. (see [here](https://emptysqua.re/blog/python-increment-is-weird/))
Answer: Mutation and rebinding are two different operations. The former modifies the object regardless of where it may be, whereas the latter only modifies the local name, leaving other names untouched.
Answer: The add function there does the following:

Print the result of c+b
Create a new variable in the local scope, referring to the value 8.
Locate mat, and invoke the member function append(c)
Locate mat, and invoke the member function append(b)

As a result, mat and x both continue to refer to the same objects they referred to before, however the list represented by mat has changed, because of the add calls.
Answer: lists are mutable, whereas the number isn't.  More examples here http://inst.eecs.berkeley.edu/~selfpace/cs9honline/Q2/mutation.html
Answer: Assigning to x inside your add() function creates a new variable. This is one of Python's quirks.
Here is a workaround:
mat = []
x = 5
def add(c,b):
        global x # do not define a local 'x'
        print c+b
        x = 8
        mat.append(c)
        mat.append(b)
add(5,6)
add(8,9)
print mat
print x


How to export for specific files in nodejs or deno

Question: By using export keyword, we can export anything from a file to another file in JavaScript. But is their any way to export for specific files. So that other file can't import from this file.
export const t = {
a:'this will export for index.js only'
}

Comment: No, there is no way.
Comment: As @jabaa [mentioned](https://stackoverflow.com/questions/76844153/how-to-export-for-specific-files-in-nodejs-or-deno#comment135471099_76844153): that's not possible. However, if you edit the question to explain to us what the real problem is that you think would be solved by such a mechanism, perhaps as can offer ideas or answers to solve the real problem.
Comment: @jsejcksn Actually I want to export some private data as an object or function and want to create a bound where without access no one can read that object.
Answer: If you are referring to how java controls access of classes to the rest of the application public, private, protected then no. If you only want a singular file to be able to use a variable then declare the variable in the file you want to use. or look into changing the architecture of your application. Ex: change your function to use dependency injection.
Answer: There's no way to achieve that directly, since import.meta does not contain that information. But you can do it if you export a factory function instead, that way you can access the caller file by using Error.stack.
module.js
const callerUrl = () => {
  const error = new Error()
  const lines = error.stack?.split('\n')
  let line = lines && lines[3] || ''
  line = line.replace('at', '')
  line = line.replace(/\:[0-9]+\:[0-9]+/, '')
  return line.trim()
}

export default () => {
  const file = callerUrl();
  const x = {};

  if(file.endsWith('/index.js')) {
    x.a = 'from index.js'
  }
  else if(file.endsWith('/foo.js')) {
    x.a = 'from foo.js'
  }

  return x;
}

index.js
import factory from './module.js';
import './foo.js';

console.log(factory());
// { a: "from index.js" }

See: Access the calling file name from within a function in a different file

I don't recommend exporting something based on the caller file though.
Comment: Hi @MarcosCasagrande! I don't downvote cavalierly (and as you pointed out, it costs the actor rep to do so), but downvoting is just as important as upvoting to manage quality on this site. I'm curious — what is your meaning of "always"?
Comment: Why I downvoted this answer: the error [`stack`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack) property is not in the [spec](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-error-objects) which means that it's non-standard and is not on a standards track — so any code which relies on it will be subject to varying values in different runtime implementations and breaking changes in each runtime's implementation. AFAIK, none of them claim any guarantee of a specific format — please inform me if I'm mistaken.
Comment: The `Error` constructor can be intercepted to change `stack` thereby bypassing a stack inspecting guard. e.g. `globalThis.Error = new Proxy(globalThis.Error, { construct(...args) { const result = Reflect.construct(...args); result.stack = "42"; return result; } }); ` will cause all new `Error` instances to have a ` stack` value of `"42"`.
Comment: @mfulton26 What does that have to do with the answer? You can intercept a lot of things in JS, don't intercept it if you want to use this approach, and don't use anything intercepting Error constructor.

You could comment on any JS answer using any method that can be intercepted. "Don't use `.map`, it can be intercepted, "Don't use `.endsWith`, it can be intercepted"
Comment: The point I was trying to make is that checking the stack trace doesn't solve the problem, it only creates a hurdle for someone to get access to what they want. If the factory method doesn't return what someone wants then all they need to do to get what they want out of the factory is to slip a different `stack` value in and now they've imported something that was intended to not be importable by them.
Comment: FYI: I didn't down vote your answer. I appreciate the "thinking out of the box" solution. I've explored `import.meta.resolve()` along with some other APIs but ultimately I don't think there's a way to do what's being asked.
Comment: Never, in any of my applications Error stack was modified, so I don't think it is a real problem, you're creating imaginary scenarios. Don't rely on any property or method since it can be intercepted, use assembly instead.


opening a variable in php from a text file

Question: i want to copy some files the hard way (dont ask me why its just too complicated) and use a variable created to a file and opened from another script then it initiates the coping
i already made a functional page that saves the value i want now i have this code that i want to extract the variable that is in a file called tmpCraft.txt and make it copy the specified file to the destination from the tmp file so this is my code its called accountCrafter.php
<?php

$dst = fopen("tmpCraft.txt", "r") or die("Unable to open file!");
echo fread($dst,filesize("tmpCraft.txt"));
fclose($dst);

$file = 'structure/index.html';

if (!copy($file, $dst . "/index.html")) {
    echo "failed to copy $file...\n";
}else{
    echo "copied $file into $newfile\n";
}

?>

i ran it and this was the result:

noni
  Warning: copy(Resource id #3/index.html) [function.copy]: failed to open stream: No such file or directory in H:\xampp\htdocs\dev4\test2\accountCrafter.php on line 9
  failed to copy structure/index.html...

The value was noni
for some reason it extracts the value as
Comment: What do you expect `$dst . "/index.html"` to do? `$dst` is a file handle, not a string containing a directory name.
Comment: `$dst` was a file pointer, not a string. Correct the directory that you're passing into the copy function.
Comment: "extracts the value as" what?
Comment: Are you trying to copy `structure/index.html` to `noni/index.html`?
Comment: Instead of `echo`ing the result of the `fread`, put it in a variable and use that in the `copy` instead of `dst`.
Comment: i figured it out i could have just used $dst = file(File path)
Comment: yes exactly barmar that was what i was trying to do
Comment: thanks a lot barmar
Comment: the value of Resource id #3/index.html
Answer: This is probably what you want:
<?php
$dst = trim(file_get_contents("tmpCraft.txt"));
$file = 'structure/index.html';
$newfile = $dst . "/index.html";

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}else{
    echo "copied $file into $newfile\n";
}

?>

You need to set $dst to the contents of the file, not the file handle. trim() will remove any extraneous whitespace around the name in the file.
Comment: this is what i get
Warning: copy(noni /index.html) [function.copy]: failed to open stream: Invalid argument in H:\xampp\htdocs\dev4\test2\accountCrafter.php on line 6
failed to copy structure/index.html...
Comment: Looks like your file has a space after the name. Use `trim()` to remove extra whitespace.
Comment: i see what is happening i added to $newfile in the failed section of your code and i saw a space between the value dst and / index.html so this is exactly what i mean
Comment: failed to copy structure/index.html... to noni /index.html
Comment: you can see a space between noni and /index


Ao mapear classe para viewModel, alguns dados são perdidos

Question: Tenho uma consulta que retorna um cliente e seu telefone, mas ao mapear a classe para a viewModel, eu perco os dados de telefone:
consulta:
public Cliente ObterClientePorId(Guid ClienteId)
{
      var consulta =
            Contexto.Cliente.Join(Contexto.Telefone,
                                  p => p.ClienteId,
                                  pt => pt.ClienteId,
                                 (p, pt) => new {p, pt}).FirstOrDefault();

  if (consulta != null)
  {
      var cliente = consulta.p;
      cliente.telefone = consulta.pt;

      return cliente;
 }

Mas ao fazer o mapeamento da classe cliente para a viewModel cliente, ele perde os dados que estavam em telefone.
Mapeamento:
    public ClienteViewModel ObterClientePorId(Guid ClienteId)
    {
        //aqui tem os dados de telefone
        var consulta = _cliente.ObterClientePorId(ClienteId);
        //aqui o telefone fica null
        var cliente = Mapper.Map<Cliente, ClienteViewModel>(consulta);

        return cliente;
    }

ClienteViewModel:
public class ClienteViewModel
{
    public ClienteViewModel()
    {
        ClienteId = Guid.NewGuid();
    }

    // campos...

    public List<TelefoneViewModel> TelefoneViewModel { get; set; }

    //mais campos...
}

Comment: Sim, usando operadores implícitos, por exemplo.
Comment: Já tentou não usar o Automapper?
Comment: não tentei, ai eu faria o mapeamento na mão?
Answer: Tentou mapear a classe Telefone para "TelefoneViewModel"? Falo isso pois sua classe ClienteViewModel possui uma List< TelefoneViewModel> e não List< Telefone>.
Talvez isso funcione:
var telefones = Mapper.Map<List<Telefone>, List<TelefoneViewModel>>(consulta.telefone);
var cliente = Mapper.Map<Cliente, ClienteViewModel>(consulta);
cliente.TelefoneViewModel = telefones;

Se não funcionar, compartilhe suas classes Cliente e Telefone, por favor.
Abraços.
Comment: @AlexandrePreviatti Entendi. Da para você colocar as ações de mapear dentro de um foreach, ou seja, você pega uma lista de clientes, faz o foreach na lista e faz o mesmo processo ai da resposta.
Comment: deste modo funcionou, obrigado! Eu tinha tentado fazer algo parecido, só não tinha feito aquele cast pra list.
Comment: @austin felipe Como ficaria caso a consulta retornasse uma lista de lientes, como faria para mapear esses telefones?
Comment: @AlexandrePreviatti Não entendi a pergunta direito. Se retornar uma lista de clientes, não precisa de Cast, certo?
Comment: @AustinFelipe como é retornado apenas um cliente, eu consigo recuperar os telefones com "consulta.telefone" se fosse uma lista de clientes não seria possível... A dúvida é, se em vez de:  var cliente = Mapper.Map(consulta); fosse var cliente = Mapper.Map, List>(consulta); supondo que a consulta fosse uma lista de clientes, como faria esse mapeamento dos telefones?


How do I create a simple backspace button on iOS?

Question: I have a custom numeric keypad on which I want to include a special "clear" button—more or less a backspace button that removes the last character. I can't find any way to get this button to work. Here's the simple code:
-(IBAction)buttonDigitPressed:(id)sender {
    currentNumber = currentNumber*10 + (double)[sender tag];
    priceOne.text = [NSString stringWithFormat:@"%.2f",currentNumber / 100.0f];
}

-(IBAction)cancelOperation {
    (backspace code goes here)
}

Any ideas would be great! Thanks!
Comment: This has got nothing to do with Xcode and one cannot click on an iPhone.
Answer: Representing the number as a float or double might be a bad idea; you might run into trouble with floating point roundoff errors when the number you typed in the text field cannot be represented exactly as a floating point number. (This happens with fractional numbers only of course). Why don't you store the number as an NSString? You can then simply chop off the last digit using string operations and convert it to a number using [NSString doubleValue] when you need the numeric value.

Edit: okay, so here's a bit more. Let us assume that currentNumber is an NSMutableString* instead of a double. I'm writing the following code off the top of my head, but it shows the general idea:
- (IBAction)buttonDigitPressed:(id)sender {
    [currentNumber appendString:[NSString stringFromFormat:@"%d", [sender tag]]];
    priceOne.text = currentNumber;
}

- (IBAction)cancelOperation {
    [currentNumber deleteCharactersInRange:NSMakeRange([currentNumber length]-1, 1)];
    priceOne.text = currentNumber;
}

Whenever you need the actual value in the text box, you just simply say [currentNumber doubleValue]. In fact, you don't even need currentNumber as you can start manipulating priceOne.text directly.
Comment: I apologize, I'm a bit confused and still very new to all of this iPhone programming. Now when you say I should store the number as an NSString, how exactly would I change that?
Answer: Ok, I'm going to try and interpret your sample a bit and walk you through what I would do to get a behavior like the standard keyboard backspace button. If you want to leave comments to correct my assumptions, I'll update accordingly.
The first thing you would want to do is track the currently active UITextField in your view controller or the class for your keypad. The only real option I can see would be to delete backward from the end as there is no non-private way to get the current cursor location in a UITextField. Assuming priceOne is your text field something like:
priceOne.text = [priceOne.text substringToIndex:priceOne.text.length - 1];

Now, this should behave fine as long as you have text in the text field but you'll have issues if priceOne has no text in it so check that it's length is greater than 0.
To really get the behavior of the standard keyboard, I would suggest considering a move away from UIButton so that you can enable your control to fire repeatedly via an NSTimer during a long press and other subtle behaviors.
PS| I agree with Tamás that it is likely a poor idea to use float or double to represent currency values; particularly so if you intend to do math with them.


Theorem 3.50 - Principles of Mathematical Analysis - Rudin

Question: Theorem Suppose $$\begin{align}(a)&\sum_{n=0}^\infty a_n\quad\text{converges absolutely}\\(b)&\sum_{n=0}^\infty a_n=A\\(c)&\sum_{n=0}^\infty b_n=B\\(d)&c_n=\sum_{k=0}^n a_k b_{n-k}\quad(n=0,1,2,\dots)\end{align}$$ Then $$\sum_{n=0}^\infty c_n=AB$$
Proof. Put $$A_n=\sum_{k=0}^n a_k,\quad B_n=\sum_{k=0}^nb_k,\quad C_n=\sum_{k=0}^nc_k,\quad \beta_n=B_n-B.$$
Then after some manipulations we obtain $$C_n=A_nB+\underbrace {a_0\beta_n+a_1\beta_{n-1}+\dots+a_n\beta_0}_{\gamma_n}$$
We wish to show that $C_n\to AB$. Since $A_nB\to AB$, we only need to show that $\gamma_n\to0$ as $n\to \infty$. Then the proof proceeds as below. Put $$\alpha=\sum_{n=0}^\infty|a_n|.$$
Let $\epsilon>0$ be given. By (c), $\beta_n\to0$. Hence we can choose N such that $|\beta_n|\leq\epsilon$ for $n\ge N$, in which case
$$\begin{align}|\gamma_n|&\leq|\beta_0a_n+\dots+\beta_Na_{n-N}|+|\beta_{N+1}a_{n-N-1}+\dots+\beta_na_0|
\\&\leq|\beta_0a_n+\dots+\beta_Na_{n-N}|+\epsilon\alpha\qquad(1)\end{align}$$
Keeping $N$ fixed, and letting $n\to\infty$, we get $$\limsup_{n\to \infty}|\gamma_n|\leq\epsilon\alpha$$ since $a_k\to0$ as $k\to\infty$. Since $\epsilon$ is arbitrary, we have proved the theorem.
Question: I can't understand the passage (1) and what follows. Could you please help me? Any hint or answer is welcome.
Thank you.
Answer: You reach $$ |\gamma_n|\leqslant |\beta_0a_n+\dots+\beta_na_{n-N}|+\epsilon\alpha$$
There is a typo, certainly, and it should read  $$ |\gamma_n|\leqslant |\beta_0a_n+\dots+\color{red}{\beta_N}a_{n-N}|+\epsilon\alpha$$
Now, we have $N$ fixed summands. Taking the limit superior, since the right hand side converges, given for each $a_{n-k}\to 0$ as $n\to\infty$, you get $$\limsup\limits_{n\to\infty}|\gamma_n|\leqslant \varepsilon\alpha$$
Since $\varepsilon$ is arbitrary, you get $\limsup\limits_{n\to\infty}|\gamma_n|\leqslant 0$. Since $|\gamma_n|\geqslant 0$, we always have $\limsup\limits_{n\to\infty}|\gamma_n|\geqslant 0$, hence $\limsup\limits_{n\to\infty}|\gamma_n|= 0$. But $0\leqslant \liminf\limits_{n\to\infty}|\gamma_n|\leqslant \limsup\limits_{n\to\infty}|\gamma_n|= 0$, so $\lim\limits_{n\to\infty}|\gamma_n|=0$, so $\gamma_n\to 0$ as we wanted.
Comment: Note that it is $\leqslant \varepsilon|a_{n-N-1}+\cdots +a_0|$ for $\beta_k<\varepsilon$ if $k>N$. But $|a_0+\cdots+a_{n-N-1}|\leqslant |a_0|+\cdots+|a_{n-N-1}|\leqslant \sum_{n\geqslant 0}|a_n|=\alpha$.
Comment: @Charlie Saying $x\leqslant \varepsilon$ for every $\varepsilon >0$ is equivalent to saying $x\leqslant 0$.
Comment: Thank you Pedro for your answer. How do I know that $$|\beta_{N+1}a_{n-N-1}+\dots+\beta_na_0|\leq\epsilon\alpha?$$
Comment: Why does Rudin take the limsup rather than just the limit, since we know $a_k$ is a convergent sequence?
Answer: Starting from the words "It is here that we use" on page 75, the proof basically states the following.
For converging series the terms converge to zero by Theorem 3.23 Cauchy criterion on page 60. In our case
\begin{align}
n \to \infty \quad \text{ implies } \quad a_n, b_n \to 0
\end{align}
By the same token, as the partial sums $ \sum_{k=0}^{n}b_k = B_n$ converge to $B$ as $n \to \infty $, the "tails" between partial sums $B_n$ and $B$ (called $\beta_n$, i.e. $\beta_n=B_n-B$) also
\begin{align}
n \to \infty \quad \text{ implies } \quad \beta_n \to 0
\end{align}
By following the steps on the proof, we arrived at the key inequality
\begin{align}
  \left| \gamma_n \right| \le
   &\underbrace{
    \left| \beta_0 a_n + \dots + \beta_N a_{n-N} \right|
   }_\text{terms ending in $\beta_N$} +
\underbrace{
   \left| \beta_{N+1} \alpha_{n-N-1} + \cdots + \beta_n a_0 \right|
}_\text{each $\beta$ having index over $N$, so each less than $\epsilon$ } = \nonumber \\
   &
\left| \beta_0 a_n + \dots + \beta_N a_{n-N} \right| +
   \underbrace{
    \left| \beta_n a_0 \cdots \beta_{N+1} \alpha_{n-N-1} \right|
   }_\text{ flipped the order of terms} \nonumber \\
   \le &
\underbrace{
 \left| \beta_0 a_n + \dots + \beta_N a_{n-N} \right|
}_\text{Comment(**) below} +
   \underbrace{ \epsilon \cdot \alpha }_\text{ Comment (*) below } \nonumber
 \end{align}
Comment (*) :

$\alpha$ contains infinite terms, whereas we had finitely many previously,  $a_{n-N}$ terms in the right summand above (indexes run from 0 to $n-N-1$, no $n-N$ terms in total).

all $ \beta $-terms are less than or equal $ \epsilon $.

triangle inequality.

So in the last inequality we fixed the right part, namely $\epsilon \cdot \alpha $ It depends only on our arbitrary choice of $\epsilon$ (it thus can be as small as we wish), and inherent properties of the series $\sum a_n$, which converge absolutely to $\alpha$ that is also given.
Now, the left term (**),
\begin{align}
\left| \beta_0 a_n + \dots +
\beta_N a_{n-N}
\right| \label{key_term}
\end{align}.
Here Rudin says "keep N fixed and push $n \to \infty $. This means the number of terms is fixed and remain the same (total N+1, as index with beta runs from zero to N), so the number of $\beta$'s that we add together remains the same despite we increase $n$! Only $a_n$ have index n in them, not betas!
Still, as we start to push n to infinity, indexes with a's all uniformly shift and increased by 1 and further to infinity. Their values during this process might be all reduced to zero. That is why the whole term goes to zero, as required.


How can I judge a torus and picture's surface is homeomophic or not?

Question:
I think that image's surface is like Möbius. So not homeomorphic to sphere. How can I judge and explain about that in usual topology $\mathbb{R}^3$?
Comment: Looks like an orientable surface of genus $2$ to me.
Comment: It's important not to get confused with how a surface is embedded iin R^3 and its homeomorphism type.
Answer: If you cut along the marked green curve, reposition the surface some, and then reglue, you can see that it is exactly a genus two surface.
Comment: nice pictures! :)
Comment: Thank you for your answer and picture. :)


How do i fix: TypeError: unorderable types: NoneType() < float()

Question: i'm trying to get this code to run in Python-3.x
This is the section in which the line appears:
    #Here we check to make sure horizon (19) and ovveride (16) digital pins aren't on
#print("GPIO 16 (ovveride) is " + str(GPIO.input(16)))
#print("GPIO 19 (horizon) is " + str(GPIO.input(19)))
#print(GPIO.input(19))
if (GPIO.input(16) == False) and (GPIO.input(19) == False): #check to see if the passive mode switch is on
# GPIO 16 is for override and GPIO 19 is for horizon mode

#In this section we rotate as needed
    starttime = datetime.datetime.utcnow()
    if (getcurheading() > getsolarheading()) and (getsolarangle() > 2) and (getcurheading() != 999):
        while (getcurheading() > (getsolarheading() + hmargin)) and (starttime + datetime.timedelta(seconds=pan_time_limit) > datetime.datetime.utcnow()):
            if debug == True:
                print("1: Moving " + str(getcurheading()) + " to " + str(getsolarheading()))
            motor2neg()
        motors.setSpeeds(0, 0)

starttime = datetime.datetime.utcnow()
if (getcurheading() < getsolarheading()) and (getsolarangle() > 2) and (getcurheading() != 999):
    while (getcurheading() < (getsolarheading() - hmargin)) and (starttime + datetime.timedelta(seconds=pan_time_limit) > datetime.datetime.utcnow()):
        if debug == True:
            print("2: Moving " + str(getcurheading()) + " to " + str(getsolarheading()))
        motor2pos()
    motors.setSpeeds(0, 0)

starttime = datetime.datetime.utcnow()
if (getcurheading() > tomorrow_static) and (getsolarangle()<0) and (getcurheading() != 999):
    if (getcurheading() - tomorrow_static) > sleep_tolerance:
        while (getcurheading() > (tomorrow_static + hmargin)) and (starttime + datetime.timedelta(seconds=pan_time_limit) > datetime.datetime.utcnow()):

The error which is generated is:
Traceback (most recent call last):
  File "solarrobot7-core.py", line 261, in <module>
    if (getcurheading() < getsolarheading()) and (getsolarangle() > 2) and (getcurheading() != 999):
TypeError: unorderable types: NoneType() < float()

Is this another case of Unicode strings vs. bytes?
The below is what i think is the definition of curheading.
#Translate the IMU from magnetic north to true north since the calcs use true north
def getcurheading():
# The escape character for # is \x23 in hex
    serialport.write(b"\x23o0 \x23f")
    headresponse = serialport.readline()
#   print(headresponse)
    words = headresponse.split(",")
    if len(words) > 2:
        try:
            curheading = (float(words[0])) + 180
            if curheading + Declination > 360: curheading = curheading - 360 + Declination
            else: curheading = curheading + Declination
        except:
            curheading = 999
#   print(curheading)
    return curheading

Thanks for pointing out that i didn't include the definitionj.
Comment: what is `getcurheading` ?
Comment: Thanks for the reply, pvanchy!  i'll give it a try and get back to you.  As you can see i've already incorporated the "b" in     serialport.write(b"\x23o0 \x23f") because it was throwing an Unicode to bytes error.
Comment: current problem is not related to unicode issue, it's something another
Answer: if (getcurheading() < getsolarheading()) and (getsolarangle() > 2) and (getcurheading() != 999):
TypeError: unorderable types: NoneType() < float()

This error means that your function called getcurheading returns None and the function getsolarheading returns float thats why comparison for these values is not applicable
So, I recommend you to investigate getcurheading function and think when it returns None and why. Or share this function with us
UPDATED:
As I can see from the definition of the function, you're writing to the file with a space separator, and reading with comma separator, that's why you have less than 2 items in words list, as a result, curheading variable is not defined, and a function returns None what is the root of your problem
if you have something like that in your file: #o0 #f
words = headresponse.split(",")

words will equals to ["#o0 #f']
and you'll never inside of this loop:
if len(words) > 2:

to resolve your issue you can change this line. Replace this:
words = headresponse.split(",")

with this:
words = headresponse.split(" ")

Comment: Guess what.  Upon further inspection we found that the lines were not indented correctly.  We fixed them and everything is o.k.  We're moving on to check the next lines in this 500+ program.  Thanks for your help!