Getting error '_io.TextIOWrapper' object has no attribute 'ascii_lower'

Question: def get_frequencies(filename: str) -> None:
    '''
    1. Open a text file.
    2. Read all its lines.
    3. Turn each line to lower case (use .lower() )
    4. Ignore any letters that are not a-z (use string.ascii_lower)
    5. Compute the counts for each letter
    6. Go through all the letters,
    6. Compute the frequency of each letter.
    7. Print the letter, and its frequency.

    Parameter:
    ---------
    filename: the name of the text file
    '''

    text = open(filename, 'r')
    letters = text.ascii_lower
    for i in text:
      text_lower = i.lower()
      text_nospace = text_lower.replace(" ", "")
      text_nopunctuation = text_nospace.strip(string.punctuation)
      for a in letters:
          if a in text_nopunctuation:
              num = text_nopunctuation.count(a)
              print(a, num)

Here is the Traceback I got when running the code:
Traceback (most recent call last):
  File "C:/MyPython/Code/StackOverflow-Questions/get_frequencies-Broken.py", line 28, in <module>
    get_frequencies('test1.txt')
  File "C:/MyPython/Code/StackOverflow-Questions/get_frequencies-Broken.py", line 18, in get_frequencies
    letters = text.ascii_lower
AttributeError: '_io.TextIOWrapper' object has no attribute 'ascii_lower'

Comment: While it is okay to ask questions about homework, there should be at least one attempt to solve the task and a specific question about it. At least the question should be well formatted. You can find help here: https://stackoverflow.com/help/how-to-ask
Comment: What is not clear about the error? `text` is a file object and it doesn't have a `ascii_lower` attribute. You probably meant `string.ascii_lower`. Maybe if you would share some context and actually ask a question, we would be able to help...
Answer: You need to import string, and you need to assign string.ascii_lowercase to the letter variable.
Here's a working version:
import string

def get_frequencies(filename: str) -> None:
    '''
    1. Open a text file.
    2. Read all its lines.
    3. Turn each line to lower case (use .lower() )
    4. Ignore any letters that are not a-z (use string.ascii_lower)
    5. Compute the counts for each letter
    6. Go through all the letters,
    6. Compute the frequency of each letter.
    7. Print the letter, and its frequency.

    Parameter:
    ---------
    filename: the name of the text file
    '''
    text = open(filename, 'r')
    letters = string.ascii_lowercase
    for i in text:
      text_lower = i.lower()
      text_nospace = text_lower.replace(" ", "")
      text_nopunctuation = text_nospace.strip(string.punctuation)
      for a in letters:
          if a in text_nopunctuation:
              num = text_nopunctuation.count(a)
              print(a, num)


Why is my voice lower pitched when I get up in the morning?

Question: When I sing or speak just after waking from a long sleep, I can reach lower pitches than I can after being awake for a few hours.
Why does this happen? What happens to my body after waking that increases the pitch I can reach?
Comment: Muscle tension?
Comment: Not because of any tension, because I can sing well. It is something like not being warmed up. But I don't know what is that my voice is in lower frequencies in that time!
Comment: Are you sure you can also reach higher pitches later in the day? Or just not reach as low?
Comment: Well, actually the default pitch in which I sing in the morning is lower than the pitch I usually sing. Yes, sure I reach higher pitches later in the day. Thanks for the edit Slim.
Answer: I found an answer to my question here:

Our voices tend to sound lower when we first wake up for three reasons. First, fluids collect in the tissues of the throat while we sleep. It's the same temporary phenomenon that makes our eyes look puffy when we first wake up. Second, mucous builds up overnight from lack of use. And third, our vocal chords dry out from breathing through the mouth while we sleep. Due to lack of lubrication they cant move together as well as they should to form the higher pitch.
Comment: I also wonder if being in a relaxed state has anything to do with it.
Answer: It has to do with the fact that on a good night's sleep your vocal chords have had time to relax and had no strain or any kind of outside interference with them and they were able to just rest for a few hours.


DIV SLIDER BOTTOM CSS

Question: Olá,
Pretendo utilizar o mesmo código que criei neste exemplo jsfiddle, para que a DIV que está oculta, ao invés de aparecer do topo, aparaça do footer (de baixo para cima).
Vejam este exemplo, clicando no circulo amarelo.
E depois através desta imagem, terem noção do que preciso.
Confesso que tentei, mas não consegui chegar neste resultado.

body {
 display: flex;
 align-items: center;
 justify-content: center;
}

.dialog {
 width: 300px;
}

.container {
 border: none;
 box-shadow: 0 40px 77px rgba(0, 0, 0, 0.22), 0 27px 24px rgba(0, 0, 0, 0.2);
 position: relative;
 background-color: #fff;
 background-clip: padding-box;
 outline: 0;
}

.container .header {
 min-height: 16px;
 border: none;
 background: #fff !important;
 color: #3f51b5;
}

.container .title {
 line-height: 0;
}

.content {
 background-color: #efefef;
 height: 350px;
 padding-top: 5px;
 padding-bottom: 5px;
 padding-left: 15px;
 padding-right: 15px;
}

.footer {
 text-align: right;
 border-top: 1px solid #e5e5e5;
 padding: 8px 0;
}

.pt-5 {
 padding-top: 5px !important;
}

.px-15 {
 padding-right: 15px !important;
 padding-left: 15px !important;
}

.mt-0 {
 margin-top: 0px !important;
}

/* DIV-IMAGE */

.header {
 position: relative!important;
 z-index: 20!important;
}

.view-image .header {
 box-shadow: 0px 2px 5px 0 rgba(0, 0, 0, 0.26);
}

.show-image {
 background: rgb(232, 216, 49);
 color: rgba(124, 98, 152, 1);
 width: 40px;
 height: 40px;
 text-align: center;
 position: absolute;
 right: 1em;
 bottom: 0;
 margin-bottom: -15px;
 border-radius: 100%;
 font-size: 16px;
 cursor: pointer;
 box-shadow: 0px 2px 5px 0 rgba(0, 0, 0, 0.26);
 transition: all .3s;
}

.view-image .show-image {
 -webkit-transform: rotateX(-180deg);
 transform: rotateX(-180deg);
 box-shadow: 0px -2px 5px 0 rgba(0, 0, 0, 0.26);
}

.icon-nocode,
.icon-yepcode {
 transition: opacity .3s;
 position: absolute;
 left: 0;
 display: block;
 width: 100%;
 line-height: 40px;
}

.icon-nocode {
 opacity: 0;
}

.view-image .icon-nocode {
 opacity: 1;
}

.view-image .icon-yepcode {
 opacity: 0;
}

.panel-image {
 box-shadow: 0px 2px 5px 0 rgba(0, 0, 0, 0.26);
 border-radius: 8px;
 overflow: hidden;
}

.div-image {
 z-index: 5;
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 height: 300px;
 background: rgba(124, 98, 152, 0.94);
 color: rgba(245, 247, 247, 0.92);
 padding: 0em 1em;
 transition: all .4s;
 -webkit-transform: translateY(-100%);
 transform: translateY(-100%);
}

.view-image .div-image {
 -webkit-transform: translateY(0);
 transform: translateY(0);
 box-shadow: 0px 2px 5px 0 rgba(0, 0, 0, 0.36);
}
<!DOCTYPE HTML>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link href="style.css" rel="stylesheet">
        <title>To push</title>

     TITLE

       <button id="user-close" class="matter-button-text matter-primary mr-5" data-dismiss="modal">CLOSE</button>
    <button id="user-save" class="matter-button-unelevated matter-primary" data-pos="bottom-left">SAVE</button>

Answer: Vamos lá.
Na .div-image você precisa jogá-la pra baixo.
Retire o top: 0 e coloque o bottom: 0.
Agora temos que jogá-la pra fora da tela. Podemos usar o mesmo translate usado. Use translateY(100%). O translate é relativo ao tamanho do elemento.

.div-image {
    z-index: 5;
    position: absolute;
  bottom: 0;
    left: 0;
    right: 0;
    height: 300px;
    background: rgba(124, 98, 152, 0.94);
    color: rgba(245, 247, 247, 0.92);
    padding: 0em 1em;
    transition: all .4s;
    -webkit-transform: translateY(100%);
    transform: translateY(100%);
}

.view-image .div-image {
    -webkit-transform: translateY(0);
    transform: translateY(0);
    box-shadow: 0px 2px 5px 0 rgba(0, 0, 0, 0.36);
}

DIV SLIDER BOTTOM CSS


Gesture recognition with HMM

Question: I'm approaching at pattern recognition with HMM (with c++ or python).
My data are x and y coordinate (normalized between -1,1) of the hand in a recorded video and I want to recognize.
This is what I have understand to classify a hand that make a gesture (for example a circle):

I need some train data (for example N different video with an hand that make a circle) of the same size (X coordinate (x,y) of the hand)
I have to initialize one HMM (called HMM_circle) with BAUM-WELCH algorithms (or something interative EM-based algorithm) and find the parameters of HMM_circle.
HMM_circle has X observed states and Y hidden states.
Record some new observation (some new coordinate of a gesture to classify) new_OBS. Size of new_OBS must be X.
Find the likelihood of new_OBS given the hidden markov model HMM_circle with BACKWARD-FOREWARD algorithm. This likelihood is a number between 0 and 1. If it is major than a threashold (for example 0.8) it is classified as a circle.

Now, I have something not clear.
How many hidden states in my HMM_circle (Y)? how long the train data (X)? How many train data (N)? Why?
Sorry, I've just began to learn machine learning.
Answer: You sure chose a tough problem to learn machine learning. I don't know if you've read the literature so I'm going to recommend these papers, having used his system.
Answer: This may not be exactly what you are looking for, but this paper, 'Sharing Features among Dynamical Systems
with Beta Processes',  outlines an unsupervised nonparametric model which will inherently make your questions of hidden states and size of training data irrelevant. For an experiment similar to the problem you propose, see section 5.

Gesture recognition with HMM


CDI and EJB mix with glassfish 3.1

Question: I have two application deployed on glassfish - application A and B.
Both are deployed as war package, application B uses some components from application A.
Now in application A I have an interface:
public interface BusinessInterface() extends SomeOtherInterface {
    void someAction();
}

I have 3 implementations of this interface - two in application A, one in application B: BusinessInterfaceA1, BusinessInterfaceA2, BusinessInterfaceB
As long as all of them are CDIBeans, everything is fine - I'm using custom @Qualifier annotations (@BusinessInterfaceA1, @BusinessInterfaceA2) and @Default annotation for B's implementation to distinguish them.
But now I need both application's A implementations to be Stateful EJBs and this is where it becomes funny.
When I just add @Statefull annotation on both implementations, a I got something like this:
javax.servlet.ServletException: org.jboss.weld.exceptions.WeldException: WELD-000049

details:
java.lang.IllegalStateException: Unable to convert ejbRef for ejb BusinessInterfaceA1 to a business object of type interface SomeOtherInterface

How can I fix it? I need all implementations to be avaliable in a way I could inject them like
@Inject @SomeAnnotation private BusinessInterface businessInterface;

Answer: It is bug in Glassfish 3.1. The workaround is, to mark implementation with all required interfaces, e.g.:
@Statefull/@Stateless
public class BusinessInterfaceImpl implements BusinessInterface, SomeOtherInterface {
   // implementation
}

Even BusinessInterface extends SomeOtherInterface, and from Java specs its useless to do that, but as a workaround for that bug it works.
Another solution is to use Glassfish 4.0
Comment: It's been a long time since I needed it, I don't have proper environment to test it right now, but thanks anyway.

CDI and EJB mix with glassfish 3.1


Adding new menu items to hook_menu

Question: I am building a module which already has the function Mymodule_menu() at the beginning of the code. I was wondering if it is possible to use hook_menu_alter() to add new menu items (i.e. building new pages) somewhere down the code.
What I'm trying to do is build a form module whereas when the user presses "Submit", the code inside the form_submit() function will build a new page using the form values the user entered, and then redirects the user to that page.
Is that even possible. Appreciate the help from anyone. Thank you all in advance!
Comment: You can add new menu items to hook_menu() at any time, but they won't become available until you clear the cache.
Answer: No, hook_menu_alter() is not thought to dynamically add new routes. As any similar alter hook, it is thought to alter the routes defined from other modules.
It would not work for dynamically adding new routes for the simply fact that, similarly to hook_menu() is only invoked in specific cases, for example, when a module is installed, uninstalled, enabled, or disabled.
If you need to have dynamic pages, you need to do what Drupal does for nodes: You define a route with wildcards, which is similar to the node/%node route defined for nodes.
hook_menu() has some example for this kind of routes, under Wildcards in Paths.
For example, a route definition as the following could be used to serve a page like my-module/1, my-module-2, etc. mymodule_abc() would recive the wildcard value as argument, and it could use that argument to access data from a database table, which is essentially what Drupal does when a user visits node/1: It loads the node whose ID is equal to 1 from the node table, and it shows it to the user who requested that page.
  $items['my-module/%'] = array(
    'page callback' => 'mymodule_abc',
    'page arguments' => array(1),
  );

As side note, as said in Auto-Loader Wildcards, instead of my-module/%, you could use my-module/%mymodule_abc, and mymodule_abc_load() will be called every time a page like my-module/1 is accessed, getting the wildcard value (1) as argument; it could then return the object saved in the database from the form submission handler.
See node_load() as example. That function returns the object saved in the database from the form submission handler of the node edit form.
Auto-Loader wildcards are helpful when there are more routes that your module defines. For example, the Node module uses them because the routes it defines using wildcards are node/%node, node/%node/edit, and node/%node/delete. Instead of putting the code to load the node in 3 different page callbacks, it puts the code in a single function (node_load()) automatically called from Drupal.
Answer: From your question it seems, you're trying to add new menu entry in custom module where we should be using hook_menu. The only thing to avoid is adding new menu entry in Core or Contributed module(s). hook_menu_alter is used in custom module to alter existing menu item defined by Core or Contributed modules.
Below is descripton taken from hook_menu API page.

Define menu items and page callbacks.

Below is descripton taken from hook_menu_alter API page.

Alter the data being saved to the {menu_router} table after hook_menu
  is invoked.
Answer: I also found the thread "Sending results of form to new page" which was talking about exactly what I need.

Adding new menu items to hook_menu


Enable/ Disable a button by creating custom directive in angular 6

Question: Need to enable/disable multiple buttons dynamically on multiple HTML pages on the basis of a conditions i.e. Active = true then enable button and if Active = false then disable the button. How to create and apply custom directive.
Comment: https://stackblitz.com/edit/angular-disable-directive
Answer: Perhaps something like this:
.ts
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[disableControl]'
})
export class DisableControlDirective {

  @Input() set disableControl( condition : boolean ) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor( private ngControl : NgControl ) {
  }

}

html:
<button [disableControl]="condition">Button 1</button>
<button [disableControl]="condition">Button 2</button>
<button [disableControl]="condition">Button 3</button>

condition would be a boolean in your component that would disable/enable control when necessary.
Source: https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110
Comment: your exmaple is working for all controls but Rajesh want disable multiple buttons.. you code may be something like that...
Comment: `
Disable
Enable`


Relationship between a closed operator and an operator with dense image.

Question: Let $T: X \to Y$ be a linear map. We say that $T$ is $\textbf{closed}$ if $x_n \to x$ and $Tx_n \to y$ implies that $y=Tx$.
Loosely speaking, (hopefully not incorrectly speaking), the closeness of an operator is a weaker condition than continuity.
Suppose now that the image of $T$ in $Y$ is dense. Is there a relationship between this and the closeness of the operator?
i.e, does $T$ having dense image in $Y$ imply that $T$ is closed?
Comment: Of course, you assume that there is some kind of topology on $X$, respectively $Y$.
Comment: Sure we assume there is a topology on the respective space. I am not entirely sure how to prove an operator is closed, and thus not sure how to show it is implied by density. It would be nice to see a proof (or just a sketch of the proof).
Answer: The answer to your question is no. You can take any non-closed operator $T$ and restrict its codomain to the closure of $\text{ran}\,(T)$. The image of this new operator is dense, and it is easy to verify (according to your definition) that it remains non-closed.


What makes this song sound so medieval?

Question: This is a song I've been listening for about a year:

.
A year ago, I didn't really know any music theory. I was baffled by it: why does it sound medieval? As I knew nothing, I didn't take it too far anyways. Fast forward a year, now I know a lot more, and I'm wondering why this sounds medieval.
Most medieval songs sound medieval because of the Dorian mode, 6/8 time, and the "medieval" instruments (which may not be so medieval after all...), is what I've read over time. Can someone chip in and check out why exactly this sounds so medieval? (By medieval I feel like something after 1400, so renaissance I guess?)
Comment: Doesn't sound at all "medieval" to me. Perhaps it's that video giving the medieval vibe?
Comment: I have to agree that it doesn't sound very medieval, but I could see why you might think that after being suggested by the video that it "should" sound medieval.  Maybe it's more in line with "medieval" cliches from film scoring and video game music than actual medieval music?  I'm hoping you get a good answer, even if most people's reaction will be "doesn't sound medieval to me."
Comment: _Actual_ medieval music is monophonic chant with perhaps a couple of instruments and a major fifth.
Comment: This doesn't sound medieval at all....
Comment: @ToddWilcox that's rather more renaissance.  Even considering that Timotej Leginus is thinking of 15th-century music, Greensleeves is probably too late as it is from the 16th century.
Comment: The video is definitely medieval and the general feel of visual artistry is medieval, but to be fair, I'm listening to this song mostly without any graphics, so it's definitely the song for me. The vocals have been giving me a medieval vibe though, but earlier in the song, where noly instruments are present, it's kinda medieval too.
Comment: Spent nine minutes waiting for the medieval bit.
Comment: For context, if someone says "medieval music", this is the first thing that pops into my head: https://youtu.be/OCpF2cwm_04
Comment: If someone says they're going to "go medieval" on me, can I expect them to play music like this for me? :)
Comment: The lead guitar has a hint of a [drone](https://en.wikipedia.org/wiki/Drone_(music)) in the melody (although it modulates every other measure), and a timbre superficially similar to a [hurdy-gurdy](https://en.wikipedia.org/wiki/Hurdy-gurdy).
Comment: Probably I'm too used to [*Age of Empires 2*'s OSTs](https://www.youtube.com/watch?v=jadxTFqyhRM) to think that those songs sound more "medieval" than the metal song in this question. But regarding the metal song, I guess it's also understandable that there are also "Gothic" musical genres.
Comment: This has been hinted at in other answers and comments, but part of the (perceived, and perhaps actual) "old" feel comes from the simple, almost plodding chord structure used throughout the song despite the uptempo rhythm. I'd put this song somewhere in the black/gothic metal category, and this isn't that uncommon. It creates a certain mood, especially when combined with all the tropes we are exposed to.
Answer: I have to say that I don't know much about heavy metal, but this sounds like what I imagine to be death metal.  I did a bit of searching on that premise, and I found one site that classifies (I think) this band as "Epic/Medieval Black Metal."
I do know a bit about medieval music, although I'm no expert, and this sounds almost nothing like medieval music to me.  There is the modality, as you note, but that's about it.  I therefore suspect that the answer to your question ...

why does this exactly sound so medieval?

... is that you have formed your own cultural associations with this style of music and the medieval period.  You're obviously not the only one with this association, but I haven't yet found much in the way of authentic medieval elements in this music.  I'll try to give it a closer listen tomorrow and edit this answer accordingly.
I tried imagining some medieval music played by distorted electric guitars, and it didn't sound much like this.  The melodic development is different, for example, and the pitches change more actively.
I would suggest having a listen to some recordings of actual medieval music.  Ask yourself whether there are any common elements that you might cite to rebut my assertion that this music doesn't sound medieval (after all, I may just be overwhelmed by the electric guitars and thereby blinded to some aspects of the piece that I should be taking into account).  If you can find these elements, but you are still not satisfied that you understand what it is about this music that seems medieval to you, ask another question, post a comment under this answer, or edit your question to clarify.
Comment: @TimotejLeginus That sounds less medieval to me than the first song.  It's not Dorian, it's almost the four chords of pop.
Comment: Thanks for your answer! It may be a thing that I really maybe did associate it with medievality, since I was listening to other metal bands (but they didn't quite match this one's style), while playing a game set in medieval times, which was highly realistic, so I guess it could be that. But as I said, looking at it after a year, having a "trained" (semi-semi-semi...-trained, if you will) ear it doesn't sound too much medieval, like it did a year ago.
Comment: However, there's just one thing you could check out, and it's this: https://youtu.be/xDSM0UOA280 , check out the guitar solo at 18:20. It sounds really, really medieval to me. Could it be in the dorian mode, or the likes of that?
Comment: I certainly do have a twisted perspective of medievality, then :) The solo sounds really medieval to me.
Comment: @TimotejLeginus specific things you've probably associated with "medieval" games and their music that show up: chanting (Skyrim), bouncy melodies (like Zelda), complex melodies (90s CRPGs had these because D&D is more Renaissance than medieval), and a couple of places in that full album sounded like the "Mario progression" (also Zelda). Both also sounded a lot like power metal, which has always had strong ties to fantasy, implicitly medieval. It helps that these songs and power metal aren't quite "normal" metal, having chanting, bouncy melodies, and the Mario progression so it sets them apart.
Answer: I agree with the comments that this sounds vanishingly little like actual medieval music. However, it does have some elements that can be loosely associated with medieval music -- church music in particular -- combined with modern movie-soundtrack conceptions of how best to accompany medieval battle scenes.

Unison vocals accompanied (in unison) by instrument(s). The vocals -- both the gutteral, distorted vocals of the verses and the more "melodic" vocals of the chorus -- are in unison and accompanied by solo guitar, also in unison. This is medieval-ish.
Choral chant-like. Although the vocals do not resemble a medieval chant, they do sound chant-like in a broader sense. Repetitive, limited pitch range, and in the verses, resembling a chorus. It does give the music a sort of religious association, which also conjures medieval times.
Accompaniment in open fifths. The use of fifths to accompany a melody is a hallmark of early medieval chant (see: organum). Because of this we tend to associate fifths-based accompaniments -- especially those like here that move in parallel with the melody -- with medieval music.
Martial drumming. Much of the drumming has a march-like or heat-of-battle quality to it. Although the specific drumming in this piece has nothing to do with medieval music, it does have everything to do with movies about medieval battles. The drum track here could easily accompany a scene in which the barbarian hordes engage in brutal, bloody, slow motion battles.

That's my best sense of where the associations come from -- spurious or otherwise -- but ultimately I have to echo Phoog's thought: you've learned some music theory; now spend a whole bunch of time listening to (and reading about) medieval music. You could do worse than Hildegaard von Bingen and Josquin des Prez.
Comment: @phoog Touché. Though I propose we can safely rule out the double-pedal kick drum.
Comment: @Aaron I can almost see the villager now; in a thatched roof cottage... frantically cobbling together a ramshackle device with help from the local blacksmith that would allow his foot to operate a beater on a pigskin drum - and that day the earliest incarnation of the double kick was born...
Comment: @Charleh One of the times I wish I was born in medieval times, then I realize that I'd probably die of sniffles.
Comment: "This has nothing to do with medieval music"; many modern performances of medieval music employ percussion, and there is iconographic evidence supporting the practice.  Medieval music was written centuries before the modern orchestral score was invented, but that doesn't mean they weren't using percussion instruments.
Comment: @phoog I don't mean the user of percussion has nothing to do with medieval music. I mean that the particular style of drumming doesn't have anything to do with medieval music.
Comment: Fair enough, but since they weren't notating their riffs, it's hard to know for certain, isn't it?  I didn't develop that thought as I had intended in the previous comment.
Answer: Metal draws very heavily from modes, especially those with ♭II like the Phrygian.  Because distorted guitar sounds make multi-voice leading impossible (the sound is too muddy), things like traditional cadences are less important in metal.  Tension has to come from melodic motion instead: lots of ♭II, tritones, movement by very unusual intervals, and so on.
The fact that power chords are perfect fifths, and ALWAYS move together, is also a nod to pre-Baroque music.
Many metal players are very keenly aware of this, as well as a connection to Baroque and Romantic instrumentalism.  Because metal lead guitar is so virtuosic, very many have formal classical training (at least some).  Eddie Van Halen gives a specific nod by dropping a little Bach riff in almost every solo he ever does.
Now, those aren't Medieval periods.  But you'd have a hard time finding ANY musical period that isn't represented somewhere in metal music, and consciously so.
Comment: You have to look several centuries before the baroque before you find music that tolerated parallel perfect fifths.
Comment: Parallel organum! *holds up two fingers and thumb and bangs now-hairless head*
Comment: @Timotej Leginus Sorry for the imprecision.  I meant V-I cadences, with both bass motion and a leading tone resolving to the tonic.  "Power chords" in metal almost never have 3rds, so basically any kind of complex voice-leading is impossible.
Comment: Multi-voice leading is perfectly possible with distorted guitars, you just can't put multiple voices on a _single_ guitar.
Comment: What exactly do you mean by "traditional cadences"? I know of the normal cadences (perfect, imperfect, deceptive..), but I also heard about one "medieval" cadence, called the double leading tone. In the post it said something about some voices moving (sharply, flatly or otherwise). Is that what that would be?
Comment: @leftaroundabout  Yes, that's very fair to say.  Soloists can voice very complex passages, especially by arpeggiation, and usually do (something Bach also did a lot).  But I don't think anyone will say that a Kirk Hammett guitar solo sounds medieval, so maybe I get a pass on this one?  :D
Comment: `distorted guitar sounds make multi-voice leading impossible`  Oh... those sound like fighting words!
Comment: Start with a dim7 resolving to a minor tonic.  And make sure you turn the distortion up to 11! :D

What makes this song sound so medieval?


Facebook API , recuperar primeiro nome

Question: Estou utlizando a versão 2.9 do Api Facebook em PHP, meu objetivo é recuperar as informações mais básicas.
Pelo que li  na documentação, a única autorização que precisaria é o email, no qual eu já possuo. Primeiro Nome e Último Nome, não precisariam de autorização adicionais
Porém ao executar
$loader = require __DIR__ . '\..\vendor\autoload.php';
    $token = $_POST['token'];
    include './Facebook/Facebook.php';
    $fb = new \Facebook\Facebook([
        'app_id' => 'meu id aqui',
        'app_secret' => 'meu segredo aqui',
        'default_graph_version' => 'v2.9',
        'default_access_token' => $token
    ]);

    $helper = $fb->getRedirectLoginHelper();

    $response = $fb->get('/me',$token);
    $me = $response->getGraphUser();
    echo json_encode(array(
        "resultado" => true,
        "id" => $me->getId(),
        "name" => $me->getName(),
        "fields" => $me->getFieldNames(),
        "email" => $me->getEmail(),
        "cover" => $me->getField("cover"),
        "firstname" => $me->getFirstName(),
        "lastname"=>$me->getLastName(),
        "picture" => $me->getPicture()

));

Eu somente recebo

id
nome
email

Todos os outros campos são nulos
Ao passar por parametro no get('/me?fields=email,name,id,lastname,firstname'), o PHP emite o erro

Graph returned an error: (#100) Tried accessing nonexisting field (lastname) on node type (User)*

Como recuperar essas informações com a API?
Answer: Use o Graph API Explorer para testar suas queries antes de fazer a programação:
https://developers.facebook.com/tools/explorer/?method=GET&path=me?fields=id,name,email&version=v2.9
Na hora de adicionar mais fields pode conferir os valores corretos, você está usando lastname mas o certo é last_name:
Comment: Funcionou corretamente, obrigado.

Facebook API , recuperar primeiro nome


Unity 2D Collision Detection

Question: I've recently started working on my first 2D game in Unity, but I'm stuck with a collision detection problem. Is there any easy way of getting the collision detection for the sides?  My object has a Rigidbody2D and a BoxCollider2D.
Answer: The Unity OnCollisionEnter2D method gives you a reference to the collider which has come in contact with your gameObject.  Therefore, you can compare the position of your gameObject with the position of the gameObject that has hit you.  For example:
void OnCollisionEnter2D(Collision2D coll)
{
    Vector3 collPosition = coll.transform.position;

    if(collPosition.y > transform.position.y)
    {
        Debug.Log("The object that hit me is above me!");
    }
    else
    {
        Debug.Log("The object that hit me is below me!");
    }

    if (collPosition.x > transform.position.x)
    {
        Debug.Log ("The object that hit me is to my right!");
    }
    else
    {
        Debug.Log("The object that hit me is to my left!");
    }
}

Answer: Let's say your object is A and the thing that just hit your object is B.
Like James Hogle said, you should use compare displacement between B and A in A's own coordinate system. However, what happens if your object is rotated? You need transform.InverseTransformPoint. Then check the quadrant of the collider.
void OnCollisionEnter2D(Collision2D coll) {
    Vector3 d = transform.InverseTransformPoint(coll.transform.position);
    if (d.x > 0) {
      // object is on the right
    } else if (d.x < 0) {
      // object is on the left
    }
    // and so on
}

However, there is still a problem: To be more precise, we should check against contact points of the collision. You should use the coll.contacts property.

Unity 2D Collision Detection


Show that the tangent bundle $TM $ of a variety $M$ is Hausdorff.

Question: I read a Lemma Introduction to smooth manifolds" which says that given a smooth n -manifold , then the tangent bundle  is a smooth 2-manifold, how can I prove this?
Comment: I assume you're familiar with how charts are chosen in $T(M)$, but you want to know why it is actually Hausdorff?  This is what I got from the title, but it's not in the body of the question.
Answer: Let $v$ and $w$ be two distinct points in $T(M)$.  Say that $v \in T_x(M)$ and $w \in T_y(M)$ for some $x, y \in M$.  If $x = y$, then $v$ and $w$ can definitely be separated by an open set in $T(M)$, since locally $v$ and $w$ are given by the last $n$-coordinates in $\mathbb R^n \times \mathbb R^n$.
If $x \neq y$, choose disjoint charts $U$ and $V$ containing $x$ and $y$, respectively.  We can do this because $M$ is Hausdorff.  Then
$$\bigcup\limits_{p \in U} T_p(M) \cong U \times \mathbb R^n$$
$$\bigcup\limits_{p \in V} T_p(M) \cong V \times \mathbb R^n$$
are disjoint open sets of $T(M)$ containing $v$ and $w$, respectively.
Answer: We need to study the 2 possibles cases:
Considering  $\Pi$, the application, such that:
$\Pi: E \rightarrow M$
If:

$\Pi(x) \neq \Pi(y)$

Since $M$ is Hausdorff there are $U,V$ disjoint, such that: $ \Pi (x) \in U $, $ \Pi (y) \in V$
Then $x \in \Pi ^{- 1}(U)$ and $y \in \Pi^{- 1}(V)$,
Also, $U,V$ are disjoint
$ U \cap V \neq \emptyset $
$ \Pi ^{- 1} (U) \cap \Pi^{- 1} (V)  \neq \emptyset. $
If:

$\Pi(x) = \Pi(y) = p$.

By definition for each point $p$, there exists a $p \in U $ neighbourhood of the point that preserves a fiber differencing:
$ \theta: \Pi^{- 1} (U) \rightarrow U \times R^{ n} $.
Then we have:
$\theta(x) = (p, x^{'})$
$ \theta(y) = (p, y^{'})$
Where $ x^{'}, y^{'} $ are vectors in $ R^{n}$
Since $\theta $ is a diffeormorphism, $ x^{'}\neq y^{'} $.
Also $ R^{n}$ is Hausdorff.
The neighbourhoods $ H, U \in R^{n}$ such that $ x^{'}\in H, y^{'} \in V $
Therefore,
$(p, x^{'}) \in U \times H$
and
$(p, y^{'}) \in U \times V$.
Where $ x \in \theta^{- 1} (U \times H)$ and $ y \in \theta^{- 1} (U \times V) $ are disjoint environments.
We concluded that the tangent bundle $TM$ of a manifold $M $ is Hausdorff.


Incorrect time using TimeZoneInfo.ConvertTime()

Question: I'm getting an unexpected DateTime when converting from:
(UTC) Dublin, Edinburgh, Lisbon, London to (UTC-08:00) Baja California
Below is the code I have been using.  I'm expecting serverDateTime to be 29/03/2016 00:00:01 (-8 hours), but instead I get 28/03/2016 23:00:01 - which is a 9 hour difference.
    private static void Main(string[] args)
    {
        ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
        TimeZoneInfo localTimeZone = timeZones.FirstOrDefault(tz => tz.DisplayName.Contains("London"));
        TimeZoneInfo serverTimeZone = timeZones.FirstOrDefault(tz => tz.DisplayName.Contains("California"));
        DateTime clientDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 29, 8, 0, 1);
        DateTime serverDateTime = TimeZoneInfo.ConvertTime(clientDateTime, localTimeZone, serverTimeZone);
    }

My local machine is in the UK, which is currently UTC+1, and Baja - California is currently UTC-7, so I'm expecting to get an 8 hour difference, instead of 9.  What am I doing wrong?
Thanks in advance.
Comment: That's *not* UTC (+00:00), that's simply London's timezone that's already using DST (+1:00). I'll bet that DST rules are different in California
Comment: BTW it's *far* easier to use NodaTime to work with time. There *is* a Windows Timezone that corresponds to UTC but I haven't found the proper index yet
Comment: Why are you converting time?  Convert Time it not required in most cases.  Only time it is really needed is when you enter data that was collected in a different timezone.  All computers store time in UTC and default to using timezone settings when inputting and displaying time.  Converting time you can end up with a time that is not UTC.
Comment: [TimeZoneInfo.Utc](https://msdn.microsoft.com/en-us/library/system.timezoneinfo.utc(v=vs.110).aspx)  already returns the UTC timezone. It's name is plain `UTC` without city names
Comment: @jdweng no they don't. In fact, all times are assume to be *local* times, which is why the OS's timezone setting is important. The *real* fix a) to use DateTimeOffset and not make *any* assumptions about offsets and/or b) use a library like NodaTime that allows you to specify the timezone name instead of an offset, thus avoiding DST rule changes. `Russia/Moscow` hasn't changed but the DST rules for Russia change every other year
Comment: Panagiostis.  Read my response carefully.  Time in PC is stored as a number in UTC.  Otherwise computer would not be able to send data accurately.  Any time sent electronically from one PC to another uses UTC.  Any time input/output is converted to local time using timezone settings.
Answer: A few things:

"(UTC-08:00) Baja California" refers to Baja California, Mexico - not California, USA.
This zone entry follows Mexican DST rules, which doesn't start DST until April 3rd this year.  Thus this entry is on UTC-8 still, explaining the time difference you observed.
This particular entry is actually wrong in Windows, as it turns out that the entire state of Baja California follows USA rules for daylight saving time, not Mexican rules.

There is an extensive multi-thread discussion of this in the tz mailing list archives in October and November 2015.  This resulted in the corresponding IANA zone America/Santa_Isabel being deprecated with release 2016a.  It now links to America/Tijuana instead, which already had been following USA DST rules.
Microsoft has not yet made a similar change to its data, but it is likely in a future update to the Windows time zone data.  (I have already communicated this to the appropriate personnel.)  In the meantime, use "(UTC-08:00) Pacific Time (US & Canada)" - even if you're talking about Baja California, Mexico.

Don't try to look up a time zone by its DisplayName.  Those values will be different depending on operating system language.  Instead, use TimeZoneInfo.FindSystemTimeZoneById.  The Id properties are not localized.  Additionally, Microsoft considers the Id values to be stable identifiers, and thus they will not change with future updates.  The DisplayName values have been modified in the past, and could indeed change in the future.

Use the ID "GMT Standard Time" for "(UTC) Dublin, Edinburgh, Lisbon, London"
Use the ID "Pacific Standard Time" for "(UTC-08:00) Pacific Time (US & Canada)"
The ID "Pacific Standard Time (Mexico)" is for "(UTC-08:00) Baja California" - but for the reasons I described, don't use this entry.

Really, you shouldn't be concerned with the time zone on the server at all.  The server should only be concerned with UTC.  (note that London is not UTC, since it switches for BST in the summer)
I'm not sure what you're intention was with this line:
DateTime clientDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 29, 8, 0, 1);

Pulling the month and year from DateTime.Now is going to use the server's time zone.  Then you combine with fixed day of 29 and fixed time at 8:00:01.  This will fail in February of a non-leap year (when there are only 28 days in the month), and also could give bad dates when the server's date is not in the same month and year as the client's (such as near the transition from one month to another).


ReactJS - Condicional em um atributo HTML

Question: Estou tentando fazer uma função que atribua um número limitado de casas decimais em um input de 'quantidade' dependendo de qual será o valor de um outro input chamado 'unidade'
Caso o input de unidade seja = 'L', só poderia ser permitido enviar no campo de 'quantidade' valores com 2 casas decimais, e caso o input seja 'CX' ou 'UN', só deveria ser permitido números inteiros.
Não sei como consigo pegar o 'value' do campo de 'Unidade' e como designar que o campo 'Quantidade' só pode ser inteiro ou com 2 casas decimais... Estava tentando utilizar do atributo 'step' mas também não consegui resolver...
Segue meus dois inputs:
<input
   onChange={handleInputChange}
   value={quantidade || ''}
   step={quantidadeValue}
   type="number"
   name="quantidade"
   id="quantidade"
   required />

   Quantidade

Selecione uma opção
<select
   onChange={handleInputChange}
   value={unidade || ''}
   name='unidade'
   id="unidade">
      <option selected>Unidade</option>
      <option value="UN">UN</option>
      <option value="L">L</option>
      <option value="CX">CX</option>
</select>

Answer: No handleInputChange cujo o qual você não informou o que tem e é importante que você poste um exemplo de código completo, você pode editar o valor do campo para substituir ou formatar a resposta dela conforme o que houver no valor da variavel unidade.
O mais estranho para mim nesse código é que o onChange dos 2 componentes estão usando a mesma função, sendo que elas deveriam ser diferentes.
No onChange do componente de unidade você pode deixar padrão, mas o onChange do componente de quantidade você precisa fazer uma função para lidar com o valor inserido.


Solving a second order non-linear ODE (rocket height function) $h''(t)=\frac{F}{m+k-r\cdot t}-\frac{G\cdot M}{(R+h)^{2}}$

Question: I've talked to a few people, and most of them think that it is unlikely that there is an exact solution to this differential equation.
Here is the equation:
$$h''(t)=\frac{F}{m+k-r\cdot t}-\frac{G\cdot M}{(R+h)^{2}}$$
$F,m,k,r,G,M,R$ are all constants. I'm trying to find solve for $h(t)$, which represents the altitude of a rocket. If it makes it any simpler, I'm only trying to find $h$ when $t=\frac{k}{r}$. I'm also wondering whether an approximation can be obtained, if there are no solutions.
Background (Skip if you want)
Imagine a single stage rocket with a dry mass of $m$ which produces a fixed thrust of $F$ Newtons. It carries with it $k$ kilograms of fuel and uses $r$ kilograms of fuel per second. Using Newton's 2nd Law $F=m\cdot a$, and assuming the rocket simply flies straight up, the acceleration of the rocket is:
$$a(t)=\frac{F}{m+k-r\cdot t}-g$$
where $t$ is the elapsed time in seconds and $g$ is the downwards acceleration due to gravity.
I would like to find the height of the rocket when its fuel is expended (when $t=\frac{k}{r}$). However, I also want the equation to account for the decreasing gravitational force as the rocket increases in altitude:
$$a(t)=\frac{F}{m+k-r\cdot t}-\frac{G\cdot M}{(R+h)^{2}}$$
$G$ is the gravitational constant, $M$ and $R$ is the mass and radius of the earth respectively, and $h$ is the altitude of the rocket. Since acceleration is defined as the second derivative of displacement, or in this case altitude or height, the resulting equation is:
$$h''(t)=\frac{F}{m+k-r\cdot t}-\frac{G\cdot M}{(R+h)^{2}}$$
Comment: why is it a soft question the equation is non-linear
Comment: What are the initial or boundary conditions?
Comment: @MariuszIwaniuk The function is valid for $0\geq t \geq \frac{k}{r}.$ At $t=0$, the rocket is on the ground, therefore $h(0)=0$. Thanks.
Comment: and the next condition ? I think $h'(0)=0$ ?
Comment: Do you provide a values of constans:`F,m,k,r`?
Comment: @MariuszIwaniuk An example of values for `{F,m,k,r}` might be `{68000,2340,3000,68}`. Oh and yes $h'(0)=0$.
Answer: At first we solve by numeric method.(Analytically can't be solved. Maple and Mathematica can't solve)
Mathematica code:
G = 6.67408*10^-11;
M = 5.9722*10^24;
R = 6378.14*1000;
F = 68000;
m = 2340;
k = 3000;
r = 68;
t0 = k/r // N

when $t=k/r$ gives: 44.11764706 second.
$$h''(t)=\frac{F}{k+m-r t}-\frac{G M}{(h(t)+R)^2}$$
sol = NDSolve[{h''[t] == F/(m + k - r *t) - (G*M)/(R + h[t])^2,
h[0] == 0, h'[0] == 0}, h, {t, 0, t0}];
((h[t] /. sol) /. t -> t0)

putting numeric values to solution:
Rocket will lift  at the height: 6192.405405 meters (6.2 km).

At second we will a approximation at point h=0 expanding with series:
$$\frac{G M}{(h(t)+R)^2}=\frac{G M}{R^2}-\frac{2 (G M) h(t)}{R^3}+O\left(h(t)^2\right)$$
putting to equation:
$$h''(t)=\frac{F}{k+m-r t}+\frac{2 G M h(t)}{R^3}-\frac{G M}{R^2}$$
With help CAS we can solve:
$h(t)=-\frac{R e^{-\frac{2 \sqrt{2} \sqrt{G} \sqrt{M} (k+m+r t)}{r R^{3/2}}} \left(\sqrt{2} F \sqrt{R} \text{Ei}\left(-\frac{\sqrt{2}
   \sqrt{G} (k+m) \sqrt{M}}{r R^{3/2}}\right) e^{\frac{\sqrt{2} \sqrt{G} \sqrt{M} (3 k+3 m+r t)}{r R^{3/2}}}-\sqrt{2} F \sqrt{R}
   \text{Ei}\left(\frac{\sqrt{2} \sqrt{G} (k+m) \sqrt{M}}{r R^{3/2}}\right) e^{\frac{\sqrt{2} \sqrt{G} \sqrt{M} (k+m+3 r t)}{r
   R^{3/2}}}-\sqrt{2} F \sqrt{R} e^{\frac{\sqrt{2} \sqrt{G} \sqrt{M} (3 k+3 m+r t)}{r R^{3/2}}} \text{Ei}\left(-\frac{\sqrt{2} \sqrt{G}
   \sqrt{M} (k+m-r t)}{r R^{3/2}}\right)+\sqrt{2} F \sqrt{R} e^{\frac{\sqrt{2} \sqrt{G} \sqrt{M} (k+m+3 r t)}{r R^{3/2}}}
   \text{Ei}\left(\frac{\sqrt{2} \sqrt{G} \sqrt{M} (k+m-r t)}{r R^{3/2}}\right)-2 \sqrt{G} \sqrt{M} r e^{\frac{2 \sqrt{2} \sqrt{G} \sqrt{M}
   (k+m+r t)}{r R^{3/2}}}+\sqrt{G} \sqrt{M} r e^{\frac{\sqrt{2} \sqrt{G} \sqrt{M} (2 k+2 m+r t)}{r R^{3/2}}}+\sqrt{G} \sqrt{M} r
   e^{\frac{\sqrt{2} \sqrt{G} \sqrt{M} (2 k+2 m+3 r t)}{r R^{3/2}}}\right)}{4 \sqrt{G} \sqrt{M} r}$
 sol2 = DSolve[{h''[t] ==
 F/(m + k - r *t) - (G M)/R^2 + (2 (G M) h[t])/R^3, h[0] == 0,
 h'[0] == 0}, h[t], t] // FullSimplify
 h[t] /. sol2 /. t -> t0

 (* {{h[t] -> -(1/(4 Sqrt[G] Sqrt[M] r))
E^(-((2 Sqrt[2] Sqrt[G] Sqrt[M] (k + m + r t))/(r R^(3/2))))
  R (E^((Sqrt[2] Sqrt[G] Sqrt[M] (2 (k + m) + r t))/(
    r R^(3/2))) (-1 + E^((Sqrt[2] Sqrt[G] Sqrt[M] t)/R^(
      3/2)))^2 Sqrt[G] Sqrt[M] r +
   Sqrt[2] F Sqrt[
    R] (E^((Sqrt[2] Sqrt[G] Sqrt[M] (3 (k + m) + r t))/(
       r R^(3/2))) (ExpIntegralEi[-((
           Sqrt[2] Sqrt[G] (k + m) Sqrt[M])/(r R^(3/2)))] -
         ExpIntegralEi[-((Sqrt[2] Sqrt[G] Sqrt[M] (k + m - r t))/(
           r R^(3/2)))]) +
      E^((Sqrt[2] Sqrt[G] Sqrt[M] (k + m + 3 r t))/(
       r R^(3/2))) (-ExpIntegralEi[(
           Sqrt[2] Sqrt[G] (k + m) Sqrt[M])/(r R^(3/2))] +
         ExpIntegralEi[(Sqrt[2] Sqrt[G] Sqrt[M] (k + m - r t))/(
          r R^(3/2))])))}}*)

putting numeric values to solution:
Rocket will lift  at the height: 6192.406503 meters.
The difference form numerics and analytically is very small about 1 millimeter!

Another approximation.See-> Altitude:
$$h''(t)=\frac{F}{k+m-r t}-g$$
where $g$ is standard acceleration of free fall.
g = (G*M)/R^2
(* 9.798004977 *)

and solution:
$$h(t)=\frac{r t (2 F-g r t)+2 F (k+m-r t) (\log (k+m-r t)-\log (k+m))}{2 r^2}$$
sol3 = DSolve[{h''[t] == F/(m + k - r *t) - g, h[0] == 0, h'[0] == 0},
h[t], t] // FullSimplify
(h[t] /. sol3 /. t -> t0)

(* {{h[t] -> (r t (2 F - g r t) +
2 F (k + m - r t) (-Log[k + m] + Log[k + m - r t]))/(2 r^2)}}*)

Rocket will lift at the height: 6190.114097 meters.
The difference form numerics and analytically is  about 2 meters!
Comment: Thanks for the comprehensive answer, I'm still testing it out. Just to clarify, when you say that "the rocket will lift at height x", you mean when $t=\frac{k}{r}$ right? Because the rocket lifts from 0 meters, and $t=\frac{k}{r}$ is the height once fuel is expended.
Comment: Yes You are right, at time $t=\frac{k}{r}$ "the rocket will lift at height x".


Example of function with these features

Question: I am looking for an actual example of a convex function which has the following properties.
$f''(x)>0$
$f'(0)\approx0$
$f'(1)\approx\infty$
It's easy to come up with an example which satisfies the first two:
$f(x)=x^{2}$
But the last one is not easy.
Does anyone have any idea?
Comment: What does it mean to be roughly infinity?
Comment: perhaps he means the limit of the function?
Comment: If you are looking for a sequence $\{f_n\}$ satisfying the first two properties such that $f'_n(1) \to \infty$ there  is a very simple example: $f_n(x)=nx^{2}$.
Answer: You didn't specify a domain, but if $[-1,1]$ is OK then $\sec(2x/\pi)$ has the required properties.
Answer: The function $$f(x) = 1-\sqrt{1-x^2}$$
satisfies
$$f'(x) = \frac{x}{\sqrt{1-x^2}}
\;\;\text{and}\;\;
f''(x) = \frac{1}{\sqrt{1-x^2}^3}$$
and its domain is the closed interval $[-1,1]$.
Answer: Consider $f:(-\infty,1)\to(-\infty,\infty)$ defined as
$$f(x)=-\log(-x+1)$$
Comment: This does not satisfy the second condition.
Answer: You do not specify a domain. But from $0$ to $π/2$, the function $\tan x$ satisfies all your requirements nicely.
The domain is an important part of any function. Are you working with complex numbers or just real ones? In what domain do you need this function to operate?
Also, within what range (assuming you're working on the real line) do you want the approximation $g(x)\approx0$ to fall?

Example of function with these features


How do we programmatically place a section and then a block in that region on module install?

Question: We are looking for the best way to export a defined/built layout with inline blocks and then use that to programmatically set both them during a module install.
eg.

module install

create node in content type
apply section
create and apply block to section in node

Currently we are having to print the array, strip UUIDs.. then attach them to the layout field value of the node we create. Which can lead to issues if not cleaned up correctly.
Comment: Did you solve this? Can you post an answer?
Answer: Put this code in an .install file:
<code>// Create a Home web page with alias 'home'.
  $node = Node::create([
    'type' => '<node_type>',
    'langcode' => 'en',
    'uid' => 1,
    'title' => 'Home',
    'status' => 1,
    'path' => [
      'alias' => '/home',
      'pathauto' => PathautoState::SKIP,
    ],
  ]);

  // Variable to hold the sections for this node.
  // Defaulting to have a blank section first.
  $sections[] = new Section('layout_onecol');

  // Create a new section.
  $section = new Section('layout_onecol');

  // Config for the multi-type list block.
  $pluginConfiguration = [
    'id' => '<block_id>',
    'provider' => 'entity_block',
    'label_display' => FALSE,
    'view_mode' => 'default',
  ];

  // Create a new section component using the node and plugin config.
  $component = new SectionComponent($node->uuid(), 'content', $pluginConfiguration);

  // Add the component to the section.
  $section->appendComponent($component);

  // Add the section to the sections array.
  $sections[] = $section;

  // Set the sections.
  $node->layout_builder__layout->setValue($sections);

  // Save the node.
  $node->save();
</code>
Comment: You can't just "put this code inside a .install file" and expect it to work, right? Wouldn't you need to put it inside a [hook_install()](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21module.api.php/function/hook_install/8.2.x) function?
Comment: This code will result in:
Call to a member function setValue() on null


List selection in Ringtone shows a blue color for selected item. What color code is that?

Question: Do anyone know the color code for that blue selected text, as it is in Ringtone list?
thanks.
Answer: textfield.textColor=[UIColor colorWithRed:53/255.0 green:80/255.0 blue:129/255.0 alpha:1.0];
happy coding...


Minimum Samples to Identify Box (Coupon Collector Extension)

Question: I am thinking on the follow probabilistic problem setting:
Say we have $n$ boxes, each of which has an affiliated set of $k$ balls. We aim to distribute these balls across the boxes in the most fair manner (each receiving an equal number of balls). The contributed balls are broken down as follows:

The first $n-1$ boxes each contribute $k$ balls which can only be given to themselves (call them ''specific'' to these boxes). As such, these $(n-1)k$ balls have no ambiguity as to where they can be distributed.
For the final box, we have $k$ balls which each have a probability equal to $1/2$ of being "specific" to that box or non-specific (can be put in any box).

If we are given all the balls at once (an ''offline'' setting), we can trivially distribute so that each box has $k$ balls.
My question is this, somewhat a coupon collector problem:
If the balls are arriving one-by-one (randomly), how many do we have to see before we can identify which box is the unique "final" box (or with high probability make this conclusion)? I have analyzed this for the setting where the final box instead contributes only non-specific items (or the probability of being specific is $p=0$), which is almost exactly a coupon collector problem (once we have seen one of each specific item, we know the box that is not specific). However, for the more complex case that the special box has some specific items, it seems that we would need to sample more to identify this box?
EDIT: It is also important to note that when $k=\infty$ we are much closer to a coupon collector instance. Additionally, with $k=1$ the problem is trivial so we are assuming $k$ is large in some sense.
Comment: If we see an item, do we know whether it's specific? (If not, how do we know which is the final box once we've seen one of each specific item?)
Comment: I'm not sure exactly what you're asking. If you want to identify the final box with certainty, clearly you can't, since it might produce only specific balls like all the others. If you want what you wrote in parentheses ("or with high probability make this conclusion"), what exactly are you looking for? The expected number of balls until the posterior distribution for identifying the final box (presumably given a uniform prior) reaches some probability threshold? Or its peak as a function of the number of balls?
Comment: @joriki yes, sorry. When the ball is observed we are given the information as to where it can be placed, ie. either in exactly one of the bins or in any bin.
Comment: @joriki the peak as a number of balls is what I am thinking. Sorry if it ill posed, I have made this construction in working towards a hardness result. My hope is that I can make some argument that we need the input system to be large enough to have a hope at identifying the one unique box (thus, after this point, we know all non-specific items should be put in this box to maintain fairness for the remainder of the sequence).
Answer: This is obviously a complicated problem, but a rough estimate is available for $k=\infty$. In that case, we expect to need $n\log n+(m-1)n\log\log n+O(n)$ balls to have at least $m$ specific balls in each normal box (see Wikipedia). The expected number of specific balls in the final box at this point is
$$\frac1{2n}\left(n\log n+(m-1)n\log\log n+O(n)\right)=\frac12\left(\log n+(m-1)\log\log n\right)+O(1)\;.$$
For this to be less than $m$, we need
$$\frac12\left(\log n+(m-1)\log\log n\right)\lt m$$
$$\rightarrow m\gt\frac{\log n-\log\log n}{2-\log\log n}\;.$$
This diverges for $\log\log n=2$, that is, for $n=\mathrm e^{\mathrm e^2}\approx1618$. Beyond that point, the number of specific balls in the final box grows faster than the minimal number of specific balls in the normal boxes, so you can never hope to reliably identify the final box.
If $k$ is finite, you need to see an appreciable proportion of the $kn$ balls until it becomes sufficiently likely for the underpopulated boxes to be filled.


Como posso pegar a data do BD já formatada usando as funções Max e Date_Format Juntas

Question: Estou tentando buscar a maior data cadastrada em meu BD, estou tentando usar as funções MAX e DATE_FORMAT juntas e o resultado da pesquisa não é o esperado, tenho essas datas cadastradas:

2016-10-24
2016-10-25
2016-10-26
2016-10-27
2016-10-28
2016-10-31
2016-11-01
2016-11-03
2016-11-04
2016-11-07
2016-11-08

O que a consulta me retorna é o dia 2016-10-31 e deveria ser 2016-11-08, entendo que não estou executando a consulta de forma correta, o que estou fazendo no momento é isso:

SELECT MAX(DATE_FORMAT(Data,'%d/%m/%Y')) as DataInicial FROM calendarioDolar
Answer: Você deve primeiro encontrar a data usando o MAX e só após isso formatar, senão o banco de dados entenderá que deve procurar usando a ordem alfabética. Corrigindo a posição teriamos:
SELECT DATE_FORMAT(MAX(Data),'%d/%m/%Y') as DataInicial
  FROM calendarioDolar

Comment: Estou aguardando os 4 min para aprovação, tem um limite de tempo entre a resposta e a aprovação.
Comment: Olá @Sorack, muito obrigado pela dica, resolveu meu problema.
Comment: Disponha! Vou adicionar uma breve explicação. Se você puder aprovar como resposta correta será que de grande valia para quem pesquisar pelo mesmo problema


Modifying the covariance of Brownian motion, what Gaussian process do we get?

Question: If $(B_t)$ is a Brownian motion, then $Cov(B_t,B_s)=min(t,s)$.
Take a Gaussian process $(X_t)$ with mean $0$ and covariance $Cov(X_t,X_s)=f(min(t,s))$ for a given function $f$ such that the covariance is still positive definite. Is $X$ related to Brownian motion ?
For example, let's take an easy function: $f(x)=x+1$, then clearly $X_t=B_{t+1}$, or more generally, if $f$ is monotone increasing, then $X_t=B_{f(t)}= \int_0^t \sqrt{f'(s)} \, dB_s$ (where the last equality is valid under integrability/differentiability conditions).
But what happens when $f$ is not monotone ? For example, $Cov(X_t,X_s)=min(t,s)(1-min(t,s))$. This is a covariance function on $[0,1]$. Can we describe $X$ using Brownian motion on $[0,1]$?
Idea: decompose $f$ on intervals on which it is increasing and decreasing. Use the above for the increasing parts. But what happens when $f$ is decreasing ? For our example that would be $f(x)=x(1-x)$ on $[0.5,1]$ ?
Comment: Oops, you're right.
Comment: Is that decreasing f a covariance function? Doesn't the argument here (https://math.stackexchange.com/questions/266222/brownian-motion-covariance-max-instead-of-min?rq=1) show that it is not the case? (Deterministic at t=1 but covariance of 0 and 1 are 1?
Comment: @E-A Corrected the typo, thanks
Comment: The function $f$ must be monotone and even it must be increasing by definition. Effectively, from the definition $$B_{f(t)} = \int_0^t\sqrt{f'(s)}dB_s$$
we must have $f'(s) \ge 0 $ or $f(t)$ is an increasing function.
$$$$
So, if you really want to construct a process with $f$ not monotone. You should define completely all definitions relating the Brownian motion.
Comment: @W.Volante correcting the typo does not help since the same problem still holds; deterministic at t=1 but Cov(X_1, X_{1/2}) = 1/4. I don't think that is a valid covariance function. Indeed, as is said in the comment above, monotonicity may be necessary.
Comment: (As a reference, Brownian bridge is \min(s,t) - st in case your example was inspired by that)
Comment: Related: https://math.stackexchange.com/questions/264104/covariance-of-brownian-motion-like-processes
Answer: The function $f(x)=x(1-x)$ applied to $\min(x,y)$ is not a covariance function since it is not positive definite on $[0.5,1]$. To see this, just calculate the determinant of the "covariance" matrix $C$ of the points $v=0.6$ and $w=0.8$. You find $C(v,v)=0.6*0.4=0.24$, $C(w,w)=0.8*0.2=0.16$ and $C(v,w)=f(0.6)=0.24.$ Now $\det C= 0.24 * 0.16 - (0.24)^2<0.$
This example gives already a good idea of what is going on or better going wrong with non-monotonic $f$. In fact I claim:
If $f$ is such that there exist points $v,w$ with $v< w$ and $f(v)> f(w)$ then $C(x,y)=f(\min(x,y))$ is not positive definite.
The first necessary condition is $$C(x,x)=f(x)>0$$ for all $x$ in the domain of $f$. We assume this holds and calculate
$$C(v,v)C(w,w) - C(v,w)^2=f(v)f(w) - f(v)^2 = f(v)( f(w) - f(v))<0$$ by assumption on $f$.


Performance issue with moving html with javascript on mobile device?

Question: What is the likely performance impact for mobile devices if I use javascript to move some html from the bottom to the top of the page?
I want to create a menu like the boston globe where on mobile devices you just have a menu button, and clicking it makes the menu appear.
The issue is that my menu is at the bottom of my page. So I could absolutely position it at the top, hide it, and then reveal it when you click the button. The issue is that it will cover the content underneath it. I cant change the source order of my html, so the only solution i can think of is the use JavaScript to move the entire menu. Thanks
Answer: Most mobile devices that you'd probably be looking to target would have quite decent JS engines.  In my experience the JS performance on mobile devices is quite impressively fast so I wouldn't worry about the performance impact of moving some HTML elements around the page.


Is there a way to create a pre-commit hook that will reject the commit in case the new revision wont compile?

Question: We would like to implement a policy that will force developers to commit only changes that will compile.
Is there a way to do such thing using pre-commit hook?  If not, I'll be happy to hear any recommendation or workaround that will maintain the source integrity.
Answer: Having the pre-commit hook kick off a build would be complicated, because the repository does not yet have a revision with the state you want to check at that point. The repository does have a pending transaction which you can inspect with svnlook; this can be used to implement some rules but there is no easy svnlook export command to do a full build.
The pre-commit would also have to wait for the build result before rejecting or completing the commit, which will slow things down tremendously. I imagine this will encourage developers to do "one big commit at the end of the day" instead of doing many smaller (=reviewable) commits as appropriate.
solution 1: don't reject, roll back
Do what the rest of the world does: set up a continuous integration server (like CruiseControl, Team Build, etc.) which does a build for each commit. If the build fails, ridiculously loud alarms are triggered an email is send out. Any developers who feel the build failure gets in their way can then easily revert the changes.
solution 2: feature branches and integration manager
The trunk (or some other branch) is considered "blessed". Developers have read access to it but they do not make changes to it directly. Instead, all changes are done on a feature branch where one can commit freely. When a change is ready, the developer makes sure it merges cleanly to the trunk by merging trunk changes and resolving conflicts. He then notifies the integration manager. The integration manager can then perform quality control (like checking that things still build) and does a svn merge --reintegrate to push the changes to the trunk. A bit heavy weight, but some projects use this process.
Answer: Others have addressed weather it's a good idea, so I'll only explain how to do it
in pre-commit, which is a shell script in this example (and usually?) but could be a program if you want:
repo="$1"
tx="$2"

# "magic" is a cut or sed command that fits your repository structure
# to find the tag/branch/etc root you need to compile the project
relative_url=$(svnlook dirs-changed -t "$tx" "$repo" | head -1 | magic)

# get a clean copy of the code
# note that this caches e.g. '.o' files from previous commits
# usually making subsequent builds faster
build_dir="~/testcommit/$relative_url"
mkdir -p "$build_dir"
svn co "file://$repo/$relative_url" "$build_dir"
cd "$build_dir"
svn revert -R .
svn up

# update it to match what the user tries to commit
diff_file="/tmp/testcommit."$$".diff"
svnlook diff -t "$tx" "$repo" > $diff_file
# you may have to adjust 'p1' to fit your repository depth
patch -p1 < $diff_file

# adjust to fit your needs
make

if [ some-test-fails ]
then
  # stdout is always discarded
  # stderr is shown to the user if the hook fails
  echo "error message to the user" 1>&2
  exit 1
fi

# allow the commit
exit 0

Answer: I don't think what you want is possible with SVN.
Tell developers that it's their JOB to commit working code. Their cycle should be:

Make changes
svn update
Run the build, which should include tests
Repeat 1 through 3 until it builds correctly
Commit changes with a meaningful comment.

Set up a Continuous Integration server like Hudson that sends out emails when a build is broken. Shame any developer that breaks the build, even yourself. Reprimand any developer that continually breaks the build.
Comment: i'd try to be a little bit more positive and stay away from stuff like "reprimanding and shaming" developers.  remember we all have to work together and everyone makes mistakes.
Answer: You probably should not do this. Committing should be fast so that developers can quickly and easily commit many small changes. Trying to do a full build before accepting every commit is going to make the commit process take a significant amount of time and disrupt developers' workflow.
Answer: You don't really need a hook for this; you can use your CI server to note that a build failed, and revert the new files. In this way the build would be self-protecting, and it would be kind of funny, IMHO :)
Further, you could just notify the developers/everyone, they their relevant commit fails.
Generally, you solve this via a more elaborate build system (nightly builds, whatever).
I'm interested though, why isn't it possible just to tell them all not to commit until it builds? Are they offshore?
Comment: you got it - our dev team is spread across 3(!) continents. we get broken builds from time to time. I think I'll go for the CC solution thogh..


Can I change or remove parentheses in a proposition consisting of conjunctions?

Question: Can I rewrite the first line as the second?
$$(A \land \lnot B) \land (C \land \lnot D)\tag{1}$$
and $$A \land \lnot B \land C \land \lnot D\tag{2}$$
Comment: Since $\land$ is associative, if you agree that $\lnot$ is done before all else, then yes.
Comment: check the associative law for the conjunction.
Comment: This isn't technically about mathematics either, since you haven't defined what you mean when you use ^ multiple times without grouping.  If you're already assuming ^ is associative then there's not really a question here, unless you're asking about a specific programming language, in which case this isn't a math question.
Comment: @ErickWong - I think it's safe to assume that the OP is asking about the **convention of operational order** in propositional calculus, as per the tags. i.e. the `BIMDAS' for logic.
Comment: @Myridium That's definitely one possibility that hadn't occurred to me, but a lack of inner parentheses in the first line suggests that the OP is not concerned with the relative precedence of negation and conjunction.  My impression was that OP is asking whether the two expressions are equivalent according to some fixed interpreter, and it still isn't clear to me what OP intends by the unbracketed use of the conjunction operator (it is pairwise conjunction, or n-ary?)
Comment: @ErickWong - I think **it still isn't clear to me what OP intends by the unbracketed use of the conjunction operator** is exactly what the OP is asking-- what does the second expression mean? (They probably suspect the answer, or otherwise read it somewhere). Conjunction is an associative operator, so there is a natural extension to make it $n$-ary as well. This means the brackets can be safely omitted. The OP is currently grappling with this concept I think.
Answer: Conjunction ("and", denoted "$\land$"), is indeed associative.
That means,  you can move or remove parentheses among consecutive conjunctions within a proposition without changing the truth-value of that proposition.  So yes,
$$(A \land \lnot B) \land (C \land \lnot D) \equiv A \land (\lnot B\land C) \land \lnot D \equiv A\land \lnot B \land C \land \lnot D$$
(Note that conjunction is also commutative, meaning $A\land B \equiv B\land A$)
In fact, see the Wikipedia entry addressing properties of logical connectives, for a summary.


Get element by id somar dois parágrafos

Question: Quero somar os dois parágrafos com JavaScript (tag ou class), mas o resultado é sempre NaN.

function calcular() {
    const num1 = document.getElementsByClassName("n1").value;
    const num2 = document.getElementsByClassName("n2").value;
    const elemResultado = document.getElementById("demo");
    const soma = parseInt(num1)+parseInt(num2);
    elemResultado.innerText = "O resultado é :"+soma;
}
input{
    size: 50px;
}

body{
    margin-top: 100px;
    margin-left: 100px;
    margin-bottom: 100px;
    margin-right: 100px;
    border-style: double;
}
h1{
    font-family: algerian;
}
p#demo{
    background-color: white;
    font-size: 30px;
}

Some os valores abaixo:

 2

 5

 <button onclick="calcular();">Clique para calcular</button>
Comment: `getElementsByClassName` retorna uma "lista" de elementos e não apenas 1
Comment: Você está pegando os elementos de forma errada, dá uma revisada no seu **HTML**.
Comment: como eu faço pra retornar 1?
Comment: @BKiller `getElementsByClassName` retorna sempre uma "lista", mas se apenas está interessado no primeiro elemento pode aceder a ele através da sintaxe de array com `[0]`, assim `document.getElementsByClassName("n1")[0].value`
Answer: Seu código tem três problemas:

Para adicionar classes ao HTML usa-se o atributo class, passando uma lista separada por espaços, por exemplo,
document.getElementByClassName retorna um NodeList, ou seja, uma lista de elementos, ao acessar a propriedade value retorna undefined
Para pegar o texto de um elemento que não seja uma entrada (input, select, etc) use innerText ou innerHTML

Código corrigido:

function calcular() {
    const num1 = document.getElementsByClassName("n1")[0].innerText;
    const num2 = document.getElementsByClassName("n2")[0].innerText;
    const elemResultado = document.getElementById("demo");
    const soma = parseInt(num1)+parseInt(num2);
    elemResultado.innerText = "O resultado é :"+soma;
}
input{
    size: 50px;
}

body{
    margin-top: 100px;
    margin-left: 100px;
    margin-bottom: 100px;
    margin-right: 100px;
    border-style: double;
}
h1{
    font-family: algerian;
}
p#demo{
    background-color: white;
    font-size: 30px;
}

Some os valores abaixo:

 2

 5

 <button onclick="calcular();">Clique para calcular</button>

Uma ideia que pode ser interessante, em vez de pegar o primeiro elemento com a classe n1 e n2, você pode pegar todos os elementos com a classe n e usar um loop para soma-los:

function calcular() {
    const num = document.getElementsByClassName("n");
    const elemResultado = document.getElementById("demo");

    let soma = 0;

    for (let n of num) {
        soma += parseInt(n.innerText);
    }

    elemResultado.innerText = "O resultado é :"+soma;
}
input{
    size: 50px;
}

body{
    margin-top: 100px;
    margin-left: 100px;
    margin-bottom: 100px;
    margin-right: 100px;
    border-style: double;
}
h1{
    font-family: algerian;
}
p#demo{
    background-color: white;
    font-size: 30px;
}

Some os valores abaixo:

 2

 5

 3

 <button onclick="calcular();">Clique para calcular</button>

Get element by id somar dois parágrafos


Proving $\ln\left(\frac{b+1}{a+1}\right)<S<\ln\left(\frac{b}{a}\right)$ given that $tS=Hb−Ha=\sum_{i=a+1}^b\frac{1}{i}$

Question: Given positive integers $a$ and $b$ with $b>a$, and $S=S_b-S_a=\sum\limits_{i=a+1}^b\dfrac1i$, how do I prove that $\ln\dfrac{b+1}{a+1}<S<\ln\dfrac ba$?
This is what I've tried so far: I know that S is greater than the surface beneath [a, b] but less than the surface beneath [a + 1, b + 1], by drawing blocks of height 1/i beneath or above the graph of y = 1/x. How do I put this into math? I've used $\displaystyle\int_s^t\frac{\mathrm dx}x=\ln\frac ts$, but I'm still stuck on how I should put it into a whole coherent piece.
Comment: This is not "abstract algebra".
Comment: The correct statement would be "S is **less than** the surface beneath [a, b] but **greater than** the surface beneath [a + 1, b + 1]." If your write the "surface" as an integral then you are done.
Answer: Consider the "step" function given by $s_1(x)=\frac{1}{k}, \quad x \in [k,k+1[$. Since $s_1(x) \ge \frac 1x$, the same inequality holds for the respective integrals, i.e
$$
\int_{a+1}^{b+1} s_1(x) dx \ge \int_{a+1}^{b+1} \frac 1x \, dx
$$
Now, the LHS is your sum $S$ and the RHS is $\log \frac{b+1}{a+1}$. So, we conclude that
$$
\sum_{i=a+1}^b \frac{1}{i} \ge \log \frac{b+1}{a+1}.
$$
The other inequality can be obtained in a similar manner by considering $s_2(x) = \frac{1}{k+1}, \quad x \in [k,k+1[$.


Header and many components missing in Open Social

Question: Just installed Open Social:
https://www.drupal.org/project/social
The problem is that there is no content on the front page. No header or other blocks. I have reviewed videos of installation on YouTube, and notice that there is a header, and many other blocks available by default immediately after installation. Why does my new instance of Open Social have nothing on the home page?
I followed the install instructions on the module page:
https://www.drupal.org/project/social
Answer: Generating demo content is optional but recommended.
Follow these instructions on generating demo content (Drush support only for now).
Still stuck? Explore the thorough guide to installing and updating which includes help for working with Docker.
OR
drush command to add demo content
<code>drush demo-content-add file user group topic event event_enrollment comment post like
</code>


Busca binária recursiva por string em C

Question: O enunciado do exercício pede-me que procure uma string num array ordenado de strings, usando a procura binária(comparar a string com o elemento a meio do array e depois comparar a string com um elemento à esquerda ou à direita). Também pede para fazer um código de forma recursiva e outro de forma iterativa. Então o código:
int procuraBinRec( char *p, char *ps[], int N, int offset )
{
    if( N < 1 ) return 0;
    int xN = N / 2;
    int x = strcmp( p,ps[ xN ] );
    if( x == 0 ) return offset + xN + 1;
    char* ps1[ xN ];

    for( int i = 0; i < xN; i++ )
    {
        ps1[ i ] = malloc( MAX_LINE + 1 );
        strcpy( ps1[ i ], ps[ i ] );
    }

    char* ps2[N - xN];

    for( int i = 0; i < N - xN - 1; i++ ) {
        ps2[ i ] = malloc( MAX_LINE + 1 );
        strcpy( ps2[ i ], ps[ i + xN + 1 ] );
    }
    if( x < 0 ) return procuraBinRec( p, ps1, xN, offset );
    else return procuraBinRec( p, ps2, N - xN - 1, offset + xN + 1 );
}

Encontrei esta resolução do exercício mas não consigo entender:

O que é o offset.
O que os ciclos for fazem.
O MAX_LINE já está definido anteriormente.
Answer: Esta função de busca binária recursiva tem vários problemas e algumas atipicidades.
A função cria desnecessariamente dois subvetores ps1 e ps2 em cada execução, utilizando os loops for para copiar os dados do vetor original para estes subvetores (o que responde sua primeira pergunta). Estes subvetores foram criados para serem repassados nas chamadas recursivas, mas isto é desnecessário, uma vez que pode-se continuar buscando no vetor original. Também há um grande vazamento de memória, uma vez que este monte de vetores criados a cada chamada recursiva nunca é desalocado. Por fim, devemos eliminar os loops for e usar o próprio vetor original.
Geralmente em uma busca binária por p, tenta-se descobrir j tal que v[j-1] < p <= v[j]. Ou seja, mesmo não achando o índice do valor exato, se acha o índice do valor maior mais próximo. No caso da sua função, a intenção é diferente, pois retorna-se 0 quando não se encontra p.
Os índices de vetores em C vão de 0..N-1, porém na sua função o valor retornado não é a posição do vetor na liguagem C, mas sim a posição no vetor com índices de 1..N.
A cada chamada recursiva a função atuará em um subvetor, na metade inferior ou na metade superior da posição N/2. Quando se atua no subvetor na metade superior, precisa-se saber qual a posição que aquele subvetor começava no vetor original. Isto é o offset, ou seja, o deslocamento do subvetor a ser processado (o que responde a sua segunda pergunta).
Espero ter esclarecido suas dúvidas. Sugiro então uma versão otimizada e bastante comentada da função:
/* --- Função de busca binária ---
Parâmetros:
    p      -> elemento buscado
    ps     -> subvetor ordenado de busca
    N      -> quantidade de elementos no subvetor
    offset -> deslocamento do subvetor no vetor original
Retorno:
    se elemento não encontrado -> 0
    se elemento encontrado     -> índice no vetor entre 1..N */

int procuraBinRec(char *p, char *ps[], int N, int offset)
{
    // retorna 0 se tamanho do vetor é zero elementos (elemento p não encontrado)
    if(N < 1) return 0;

    // índice para divisão binária do vetor
    int xN = N / 2;

    // 0 se p == ps[xN], negativo se p < ps[xN], positivo se p > ps[xN]
    int x = strcmp(p, ps[xN]);

    // se p é exatamente o elemento do meio (p == ps[xN]), então retorna:
    // = o deslocamento do subvetor dentro do vetor original (offset)
    // + intervalo até o meio do subvetor (xN) +
    // + 1 porque se quer que os índices na resposta sejam de 1 a N
    if(x == 0) return offset + xN + 1;

    // se p < ps[xN] processa subvetor da metade inferior
    else if( x < 0 ) return procuraBinRec(p, ps, xN, offset);

    // se p > ps[xN] processa subvetor da metade superior
    else return procuraBinRec(p, ps + xN + 1, N - xN - 1, offset + xN + 1);
}

O desempenho das duas funções, se comparado, apresentará uma grande diferença no tempo de execução e no consumo de memória. Podemos fazer alguns teste simples para verificar esta afirmação.
Durante todos os testes utilizei os seguintes parâmetros:

MAX_LINE = 80 caracteres
N = 50.000.000 elementos
p = a primeira string do vetor (péssimo caso)

Utilizei um código similar ao esboçado abaixo para testar o tempo de execução das funções:
#include <time.h>
...
clock_t t;
t = clock();
int x = procuraBinRec(p, ps, N, 0);
t = clock() - t;
printf("tempo = %.5lf s\n", ((double) t)/CLOCKS_PER_SEC);

No meu computador, sem ocorrer swap, compilando com o gcc -O0, obtive os seguintes resultados:
Função da pergunta = 5.76911 s
Função da resposta = 0.00011 s

A diferença de consumo de memória entre as duas funções também foi grande. Fazendo as medições usando o programa time:
$ command time -f MaxRSS=%M ./bb

Obtive os resultados:
Função da pergunta: MaxRSS = 9.962 MB
Função da resposta: MaxRSS =   197 MB

Outra forma que utilizei para medir o consumo de memória foi com o programa valgrind. No caso, usei o massif-visualizer para gerar os gráficos a seguir:
valgrind --tool=massif ./bb
massif-visualizer massif.out.pid

Comment: resposta muito boa! código muito bom!
Comment: Obrigado @zentrunix, adicionei ao final da resposta uma parte sobre comparação de desempenho das funções.

Busca binária recursiva por string em C


Check for specific sequences in list

Question: So, I have to check if to check if a sublist is present within the list and has to appear in the list in that order as well. If sublist is present in the list the function should return true. and if not it should return false. I created a function attempting to do this, can someone tell me if im on the right track or what I should fix, b/c right now it isn't working.
def subfunc(L,sublist):

  for i in range (len(L)):
        if L[i:i+len(sublist)] == sublist:
              print "true"
        else:
              print "false"

for example if the sublist was [3,4] and the list was [0,1,2,3,4,5] it should return true. In the case that the sublist was [5,1] it should have returned false.
Comment: "it should have returned false" - returned or printed?
Answer: >>> def check(L, subL):
...   for i in range(len(L)-len(subL)+1):
...     if L[i:i+len(subL)] == subL:
...       return True
...   return False
...
>>> check(L, [4,5])
True
>>> check(L, [3,4])
True
>>> check(L, [5,1])
False

Comment: `check([0,1,2,3,4,5], [4,5])  # --> False`?
Comment: @martineau: Sorry. Fixed the off-by-one!
Answer: Your main problem is the fact that you're giving out a value (true or false) for each position. Not finding the sublist on the first position does not mean it won't be found later, so you should wait until you either find it (stop the iteration and return True on the first position when you do find it), or you are sure you didn't (return False after you've gone through all elements, and they "weren't it").
Answer: You were close!
def subfunc(L,sublist):
    for i in range (len(L)-len(sublist)+1):
        if L[i:i+len(sublist)] == sublist:
              return True
    return False

False needs to be outside of the loop, so if the loop finishes without success then false will be returned. Also, you only want to loop til len(L)-len(sublist)+1.
Comment: You were close, too. `subfunc([0,1,2,3,4,5], [4,5])  # --> False`
Comment: @martineau my bad, fixed now! cheers
Answer: This seems to work and handle the edge cases:
def subfunc(L,sublist):
    sublen = len(sublist)
    for i in xrange(len(L)-sublen+1):
        if L[i:i+sublen] == sublist:
            return True
    return False

L = [0,1,2,3,4,5]
print subfunc(L, [0,1])  # --> True
print subfunc(L, [5,1])  # --> False
print subfunc(L, [4,5])  # --> True

Check for specific sequences in list


Help explain linear algebra/differential calculus theorem in simpler terms.

Question: On a previous question, I got something related to linear algebra and linear algebra, but having no background in linear algebra and a little background in vector calculus(mainly from physics), I  couldn't understand it. Can somebody explain this theorem in simpler terms, you need not explain all linear algebra:

Let $M$ be a diffrentiable manifold. Let $\bf G$ be a finite group of smooth maps from $M$ to $M$. Let P be a point in $M$ fixed by $\bf G$, and let $f$ be a diffrentiable function on $M$ invariant under $\bf G$. Assume that the action induced by $\bf G$ on the tangent space at $P$ is (nontrivial) and irreducible . Then $P$ is a critical point of $f$; and if this critical point is nondegenerate, it is a local maximum or minimum of $f$.

*I have marked words that I don't know with bold character.
What I could understand:

Maybe $M$ is some kind of vector with more than 3 components and it is diffrentiable(how can a vector be diffrentiable?).$\bf G$ is some kind of function from set $M$ to itself as if a function from $\mathbb R$ to itself. And $f$ is some function which is diffrentiable under $M$ and it remains unaffected by rotation of space, i.e. interchange of variables. As we have tangents on $2D$ graphs, we have some kind of tangent vectors onn multidimensional spaces. Maybe at $P$ the $f$ has a critical point(maybe where it's convexity changes, or a point of local maxima/minima).

Can someone guide me in right direction
Comment: The words you highlighted are not linear algebra terms, but for most of them differential geometry. Differential geometry relies heavily on linear algebra but is a different topic. I strongly recommand you to study linear algebra before (or at least in parallel) the study of differential geometry. BTW, could you give a link to the other question you mention at the beginning of your post?
Comment: For the question "Can someone guide me in right direction?", wikipedia has a good introduction to manifolds I think.
Comment: Yeah, this is not a linear algebra theorem.  This has to do with calculus. I'm not sure I understand the significance of the group $G$, to be honest. Maybe it plays the role of a coordinate chart?  But usually you would simply take the gradient of $f$ and see if it's the zero vector to find a critical point. This theorem must be an intensely rigorous way to do that, but I can't appreciate some of the formal machinery being used.
Answer: This is not a linear algebra theorem. The study of differentiable manifolds is differential geometry, which relies on concepts from linear algebra.
From your questions, you appear to be a high-school student, probably studying calculus. Let me assure you that this theorem is quite advanced, and you're at least a few months of study away from understanding these terms.
I assume that you were looking for some theorem about maxima and minima of functions, as is standard in a calculus class approaching differentiation. What you have found is far, far more complicated than what you need. You should ask about what you're really trying to prove or learn.
Also, in your interpretation of the theorem, you appear to have more or less guessed at things. Why do you think that a finite group of smooth maps is the same as a function? I suggest not guessing at what advanced terms mean --- this may implant false knowledge in your mind, which you'll have to debug later on. Beyond that, you don't have to guess. There's a better way to interpret the theorem: look up the terms you don't understand. Great resources for this include: Wolfram Mathworld, Wikipedia, etc.
Comment: someone suggested me to read [this](http://www.maa.org/sites/default/files/pdf/upload_library/22/Ford/Waterhouse378-387.pdf) after I asked [this](http://math.stackexchange.com/questions/911276/symmetry-in-inequalities)


Arco sulla tastiera

Question: Does anybody know what the expression arco sulla tastiera above a group of 3 notes on a score for violin voice mean and how you will play them on the violin ?
Concerning the notes, all of them have on the top of the stem 2 oblique lines and the first note is connected with the second one with both an arc and a strait line. So does the second note with the third one.
Thanks for your comment.
Answer: arco sulla tastiera would be with the bow on the fingerboard, or something close, translated literally. So, you'd play it just as you would normally, just on the fingerboard rather than near the bridge. Resulting in a lighter, more airy sound.
Regarding the other markings of the notes, I'm not entirely sure what you mean, is there a possibility you could upload a picture? The arc and straight line could mean it is to be played legato and, depending on where the line is situated, a glissando, but with your explanation I'm not entirely sure. The two oblique lines on the stem could be an abbreviation for you to play semiquavers for the duration of the note but that wouldn't fit particularly well with a glissando, and again, I'd need to see the exact markings to be certain.

Arco sulla tastiera


Local IIS Website Errors

Question: I am using Visual studio web developer 4.0, in which I am creating a locally ISS hosted website.
My problem is while I am opening the website from visual studio I am getting errors such as:
ASP.NET 4.0 has not been registered on the webserver. You need to manually configure your web server for asp.net 4.0 in order for your site to run correctly...

When I am trying to serve a debug website I am getting the error:
Unable to start debugging on the server. Could not start asp.net debugging. More information my available by starting the project without debugging.

Then I navigated to my startup page without debugging and then the error in browser is
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

I have tried registering asp.net with aspnet_regiis -1. I'm using windows 8.
Comment: Did you really use -1 or actually -i?
Answer: You have two options:

Manually configure web server for asp.net 4.0
Reinstall .NET framework

Number two is recommended.

Local IIS Website Errors


Custom Fieldable panels pane template rendering the Field collection items

Question: I am using Fieldable Panels Panes (FPP). I created a custom FPP and I am using  Field Collection items into my custom FPP.
I want to customize the rendering of Field collection item fields in my FPP template file.
For example: fieldable-panels-pane--my_custom.tpl.php is my tpl file, where I am unable to customize my_field_collection_items fields seperately by using some classes.
Is there a way to customize these fields and render the output in desired way?
Answer: I found the answer. Actually, by using $elements in .tpl file, we get all variables and also all fields as an array. You can use it to render the output you want to.


Building whistling muscles

Question: I happen to inherit the ability of emotionally creative whistling to good music. To prove my point, here's a piece to which I whistle:
https://app.box.com/s/grkromn1brjksou5qecwgs9w6odwi7ik
My problem: When I was younger, I whistled up to 13 hours non-stop, but now that I stopped for many years (and at 77), I'm only able to whistling about 5 minutes strong enough and then I feel that I'm losing muscle strength.
I guess physio therapists know how to go about to regain muscle strength. My reasoning leads me to gradually build up my whistling muscles, such as whistling only for 5 minutes daily 3-5 times for about 2 weeks and then increase the time to 10 for another 3 weeks etc.
Yesterday I started and straight away felt my muscle signaling some changes. I wonder if taking Collagen or other muscle building supplements might be helpful?
I would be grateful for some professional advice, because here we have got an orchestra, which would like to have me perform.
Comment: Wow! My first thought was that man people claim they can whistle and many can't. But man – you can! I really like your whistling! Hope you find a solution.
Answer: @DrSvanHay has convinced me to open an unknown executable archive on a note that looks like (not that I thought it was) a hustle...
77yo and how many months? ;-)
I'm a pro whistler looking for people/places to jam with same as yourselves (R and L brain and diaphragm-gangliation), even on the phone (POTS!) if necessary.
I hope you'll think twice about your schedule. Even with good THC and focus, I would say "weeks" should have been "days" (although the schedule for each day sounds rightish) I don't know your hormonal regime and I'm looking into building muscle with chemical aid (pre-60s) myself, but generally, I'd say one really needs to push for longer by 20 secs every other session, until you get so much burn that you need to skip two full sessions. The focus is to feel each little twinge of distress with, differentiating from true stop-now WARNING alerts, by pushing very hard and then overdoing by a bit just as hard but very slowly/slightly.
If you really had to skip a full additional day or two, beyond 1, well THEN I'd drop back most of a minute, and start adding 3 secs per session again next time, possibly now only every two sessions (sets, in muscle-building speak).
You need to get intimate with "pleasurably-quite-sore" and know how long it will "almost kill" after a workout to make your jowlage (tongue too? I'll have to hear your styles) and lippage grow musclebulk fastest.
I've only ever done this on legs, so I don't know how sore would even feel, cheekwise. I whistle for 2-5 hours maybe, without tiring, but I'll vary my genres/dynamics and never did it as a career quite yet.
I heard 2009-era advise or read in a mag thenabouts, that very-precise (like... 20-35 mins before or rather, I'm remembering now... after??) timed-intake of your tunafish or proteinshake or proteingoopack or whatever, is key. Some paper showing high-pro-level bodybuilders who ate their protein exactly-ish (w/in 10mins or so of "optimal" which was, I think 25-35 minutes after last weightlift that day, bulked in the critical pre-tournament penultimate week(s?) by 20% or some such hugely advantageous amount, faster, than their competitors who missed the protein-reuptake ingestion target by not much more... like "anything more than 30 mins").
If I were/am(?) you, I'd read up on the research... been years since the Gym, so I'm ready to listen if you look it up, too). It's supposed to hurt every time, and for big muscles, they only generally recommended one work half one's body's groups each day, with the half off rotation being the one hard at work building muscle-fiber by/while repairing the microtears that help make way for more. So, yeah, on seccond-thought, I'd definitely work to the slightest bit beyond exhaustion ("that last forced half-rep") on the last time each day, and skip the next day, for at least a fortnight, before trying any every-day testing... we'll have to do our own research on whistle-muscles, no doubt, but what works for other muscles is the thing I'd try first.
Can't wait to hear your file! Cheers! Thanks for inspiring me to start excercising, today, for real!
Let me know if you have/recommend BandCamp or SoundCloud, and I'll sign up and meet you there. (Or wherever there's a similar site with a record-together-online function added to it?)

Building whistling muscles