cpu_shares,cpu_period and cpu_quota in flavours customization of Openstack

Question: I am reading openstack cloud administrator guide. On page 47 in Flavors customization topic following terms are defined.
The optional cpu_shares element specifies the proportional weighted share for the domain.
If this element is omitted, the service defaults to the OS provided defaults. There is no unit
for the value, it's a relative measure based on the setting of other VMs. For example, a VM
configured with value 2048 will get twice as much CPU time as a VM configured with value
1024.
The optional cpu_period element specifies the enforcement interval(unit: microseconds) for
QEMU and LXC hypervisors. Within period, each VCPU of the domain will not be allowed
to consume more than quota worth of runtime. The value should be in range [1000,
1000000]. A period with value 0 means no value.
The optional cpu_quota element specifies the maximum allowed bandwidth(unit:
microseconds). A domain with quota as any negative value indicates that the domain has
infinite bandwidth, which means that it is not bandwidth controlled. The value should be
in range [1000, 18446744073709551] or less than 0. A quota with value 0 means no value.
You can use this feature to ensure that all vcpus run at the same speed. An example:
nova flavor-key m1.low_cpu set cpu_quota=10000
nova flavor-key m1.low_cpu set cpu_period=20000

In that example, the instance of m1.low_cpu can only consume a maximum of 50% CPU of
a physical CPU computing capability.
My Questions
What is cpu_period. In above example what does value 20000 indicating.
What is cpu_quota. In above example what does value 10000 indicating.
Can anyone please elaborate with example ?
Answer: In the given example cpu_period is 20,000 microseconds, cpu_quota 10,000 microseconds.
For each 20,000μs period of time m1.low_cpu is permitted to use 10,000μs of processor time.
Source: I read the quoted text 3 times.
Comment: " Within period, each VCPU of the domain will not be allowed to  consume more than quota worth of runtime ". If we are assigning 20,000 microseconds out of 1000000 microseconds what does it means. It will consume 20% of total ? what is relationship between cpu_period and cpu_quota ?
Answer: (Adding a clarifying answer based on the follow up question by Zain)
You are correct in your conclusion. Referring to new --cpus setting which is basically a factor of the cpu_period and the cpu_quota, the documentation tells us that:

.. if the host machine has two CPUs and you set --cpus="1.5", the
  container is guaranteed at most one and a half of the CPUs. This is
  the equivalent of setting --cpu-period="100000" and
  --cpu-quota="150000". Available in Docker 1.13 and higher.

So for their example, this means that for CPU usage during 100% of total CPU period, 150% of one CPU power can be used. This is pointless for one CPU because its not possible so in that example there are 2 CPUs and therefore logically the 50% excess in that example goes to the second CPU. A simpler way to think of that example is basically a total of 75% of total CPU power for a 2 core system. In other words:
(1.5 / 2) * 100 = 75% .. where 1.5 is --cpus and 2 is the number of CPU cores.
Scaling up the number of CPUs while keeping the --cpus setting the same would effectively not allow the container to scale up along with the machine. If scaling is desired then this number must be a factor of the desired power and number of available CPUs.
Given your example, if you always wanted to cap your container to 20% of what ever total CPU resources are available you would set --cpus to: (number of CPUs) x (20/100) .. or just .. number of CPUs x 0.2
I would point out that this new --cpus setting was available after the initial question was posted and is now the setting that is recommended to be used instead of a combination of --cpu-period and --cpu-quota. Clearly it makes things simpler to understand.


É possível usar if else em consultas MySQL?

Question: Eu estive pesquisando na internet e ouvir rumores que e possível usar if else em consultas MySQL mas não vi nada de concreto a respeito. É possível mesmo? Se sim, como?
Eu quero fazer uma consulta em três tabelas distintas em busca da coluna nome eu tenho a seguinte query como exemplo
SELECT `PAIS`.nome, `FILHOS`.nome, `NETOS`.nome FROM `PAIS`, `FILHOS`, `NETOS` WHERE `PAIS`.nome LIKE '%MATILDE%' OR `FILHOS`.nome LIKE '%MATILDE%' OR `NETOS`.nome LIKE '%MATILDE%'

Essa query vai fazer uma consulta nas três tabelas PAIS, FILHOS, NETOS buscando por '%MATILDE%' no campo nome
Agora eu quero fazer como nesse exemplo mas com SE
SE encontrar '%MATILDE%' na tabela NETOS CONCATENAR
CONCAT(' É FILHA DE ', FILHOS.nome),
CONCAT(' E NETA DE ', PAIS.nome)

SE encontrar '%MATILDE%' na tabela PAIS CONCATENAR
CONCAT(' É MAE DE ', FILHOS.nome),
CONCAT(' E AVO DE ', NETOS.nome)

Eu quero implementar algo mais ou menos assim.
Comment: Cite onde tem esse rumor.
Comment: Podes explicar que tipo que query precisas de correr?
Comment: ELSE eu nunca vi. O IF eu uso em algumas respostas no site. Uma delas é essa: http://pt.stackoverflow.com/a/127134/70
Comment: se vc pesquisar ai gogre se acha @bigown > https://talibamartins.wordpress.com/2007/09/20/if-e-case-no-mysql/
Comment: Possível duplicata de [consulta recursiva em tabelas relacionadas usando foreign keys](http://pt.stackoverflow.com/questions/134823/consulta-recursiva-em-tabelas-relacionadas-usando-foreign-keys)
Comment: O que diferencia os "netos" na relação entre pais e filhos? Pois netos podem ser pais como podem ser filhos. Mesmo tento o mesmo sobrenome.
Answer: No tipo de consulta que você pretende fazer, você pode resolver com uma subquery:
set @nome:='MATILDE';

SELECT CONCAT(' É MÃE DE ', f.nome) as filha,
       CONCAT(' É FILHA DE ', p.nome) as mae,
       CONCAT(' É AVÓ DE ',(SELECT nome from PAIS where nome like '%@nome%')) as neta,
       CONCAT(' É NETA DE ',p.nome) as avo,
    FROM `PAIS` p,
         `FILHOS` f,
         `NETOS` n
  WHERE `p`.nome LIKE '%@nome%'
     OR `f`.nome LIKE '%@nome%'
     OR `n`.nome LIKE '%@nome%';

E usar a condição IF para ignorar a concatenação, já que nem sempre poderão haver filhas, netas, mães e avós no mesmo banco de dados, você pode fazer um filtro:
   SELECT  IF(f.nome IS NOT NULL, CONCAT(' É MÃE DE ', f.nome), null) as filha,
           IF(p.nome IS NOT NULL, CONCAT(' É FILHA DE ', p.nome), null) as mae,
           IF((SELECT nome from NETOS where nome like '%@nome%') IS NOT NULL, CONCAT(' É AVÓ DE ',(SELECT nome from NETOS where nome like '%@nome%'), null) as neta,
           IF(p.nome IS NOT NULL, CONCAT(' É NETA DE ',p.nome),null) as avo,
        FROM `PAIS` p,
             `FILHOS` f,
             `NETOS` n
      WHERE `p`.nome LIKE '%@nome%'
         OR `f`.nome LIKE '%@nome%'
         OR `n`.nome LIKE '%@nome%';

Obs: sua pergunta ficou confusa, pois na relação que você apresenta, não ficou claro o que diferencia as "netas" na relação entre pais e filhas. Pois netas podem tanto serem mães como podem ser filhas. Mesmo tento o mesmo sobrenome, uma mãe poderá vir como sendo neta dela mesma se considerar somente a relação de nome.
Comment: voce chegou ao ponto  que eu estava qurendo se voce ver na minha outra pergunta voce vai ver essa busca eu fiz pelo campo nome mas eu criei uma tabela relacionando as na outra,  voce pode ver http://pt.stackoverflow.com/q/134823/45474 voce acha que tem como trazer essa relacao do banco de dados usando FK? @Ivan Ferrer
Comment: Acredito que sim... é bem tranquilo.
Answer: Em SQL é possivel usar o CASE ELSE
CASE WHEN aaa = bbb THEN xxx ELSE zzzz END

Exemplo:
SELECT a, b, c, (CASE WHEN aaa = bbb THEN xxx ELSE zzzz END) AS d
FROM table

É compativel com SQL 92, funciona em SQL SERVER e MySQL
Answer: Isto é uma função quase igual ao que existe no Excel, ou como mais estamos acostumados na programação, funciona análogo a um operador condicional. O ELSE é consequência porque o primeiro argumento da função é a condição, o segundo é a expressão que ele deve retornar se a condição é verdadeira e o terceiro argumento é o que retornará se a condição for falsa, portando o que "seria executado" no ELSE.
Documentação.
Então não é usado como controle de fluxo efetivamente, mas apenas como parte de um cálculo de valores (é como o operador condicional). Só dá para fazer coisas simples.
No comentário do Bacco tem exemplo de uso real.
Até existe o IF/ELSE pra controle de fluxo, mas não para usar em consultas SQL, aí é para programar funções e procedures.
Ali dá pra ver que pode usar um CASE também que funciona de forma semelhante, só que pode ter várias opções, ou seja, para cada valor achado na expressão principal (provavelmente uma coluna) haverá o retorno de um outro valor correspondente. è possível usar um ELSE nele também.
Então não chamaria de rumor, foi uma informação passada por alguém ser dar maiores fundamentos e referências. Sempre que possível consulte a documentação oficial. Ou pergunte aqui :)
Coloquei no GitHub para referência futura.


Adding autocomplete to a CCK text field

Question: I have a form with a field which I would like to be an autocomplete field.
I've tried the form_alter hook:
<code>function autocomplete_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == office_node_form) {
    $form['field_office_name'][0]['#autocomplete_path'] = 'autocomplete';
  }
}
</code>
The autocomplete path is correct because I use it elsewhere for another field in another form but the field it's not working as autocomplete.
Anything else I should change in the form_alter hook in order to make it work?
Answer: Why don't you try Autocomplete Widgets for Text and Number Fields
This module adds 3 autocomplete widgets for CCK fields of type Text and Number.
Autocomplete for allowed values list: This widget can be used for Text and Number fields and it takes candidate values from the defined list of Allowed values of the fields. You can even generate your allowed values list using PHP, so the limit to provide a widget with autocomplete features is your imagination!
Autocomplete for existing field data: This widget can be used for Text only and it takes candidate values from existing values in the database for that field.
(7.x only) Autocomplete for predefined suggestions: This widget can be used for Text only and allows an admin to provide a list of suggestions but still allows users to enter anything they want in a text field. Use this widget to help avoid (but not prevent) variations of the same value. Ex: burger, hamburger, Burger ...
(7.x only) Autocomplete for existing field data and some node titles: This widget works just like the "existing field data" widget above except it will also suggest node titles for nodes of a specific content type(s).
Answer: Replace your code:
<code>$form['field_office_name'][0]['#autocomplete_path'] = 'autocomplete';
</code>
With:
<code>$form['field_office_name'][0]['value']['#autocomplete_path'] = 'autocomplete';
</code>

Adding autocomplete to a CCK text field


Angular Material Datepicker get string instead of object toString

Question: I've created an Angular shared component representing an Material Datepicker.
<code>@Component({
  selector: 'm6smart-form-datepicker',
  templateUrl: './form-datepicker.component.html',
  styleUrls: ['./form-datepicker.component.scss'],
  providers: [{provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => FormDatepickerComponent), multi: true,},],
})
export class FormDatepickerComponent implements ControlValueAccessor {
  @Input() formInput!: FormDatepickerInput;

  onChange: any = () => {};
  onTouch: any = () => {};
  value: string | undefined;
  disabled: boolean = false;

  constructor() {}
  writeValue(obj: any): void {this.value = obj;}
  registerOnChange(fn: any): void {this.onChange = fn;}
  registerOnTouched(fn: any): void {this.onTouch = fn;}
  setDisabledState(isDisabled: any): void {this.disabled = isDisabled;}
}

<mat-form-field (click)="picker.open()" appearance="fill">
  <mat-label>{{ formInput.label }}</mat-label>
  <input matInput [matDatepicker]="picker" [(ngModel)]="value" (ngModelChange)="onChange($event)" [required]="formInput.required" disabled autocomplete="off" />
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker disabled="{{ formInput.disabled ? formInput.disabled : false }}"></mat-datepicker>
</mat-form-field>
</code>
After creating an 'UntypedFormGroup', I included my component in an Angular page. While the component itself works fine, I am facing an issue when trying to retrieve the values from the form.
Instead of getting the formatted date that I see in the input field, I'm getting the date object's 'toString' value (ex: Wed May 10 2023 00:00:00 GMT+0200).
I've looked online and in the documentation for a solution, but most of them rely on the deprecated Moment.js library. Could you suggest a solution for this problem?
Answer: I would recommend using date-fns. It is much more versatile than moment.js and well supported:
https://date-fns.org/docs/Getting-Started
You can then use the format function:
https://date-fns.org/v2.30.0/docs/format
Example:
const result = format(this.formInput.value, 'MM/dd/yyyy')
//=> '05/09/2023'
Comment: Thank you. I was hoping that we could make some changes to the component so that it returns the accurate value.


Is it necessary to be a performing musician to be a music producer?

Question: Is it necessary to be a performing musician to be a music producer?
I have some years experience playong guitar and keyboard. I just know how to play Gymnopédie nº 1 by Satie. On these two instruments I don't have really good practice and execution.
I'm trying to improve just my music knowledge and get a really strong music theory background and mixing technique.
To learn how to play an instrument like a pro, I have to spend a lot of time and do too much practice. I want to focus my time on the knowledge.
Can I be a good producer doing things like that or do I also have to be a pro instrumentalist?
Comment: No. But it definitely helps.
Comment: What kind of music do you want to produce?
Comment: @topoReinstateMonica I really want to be an eclectic producer, able to produce several style of music. I started to produce electronic music and some hip hop/R&B beats. Now I'm trying to open my mind, listening several style,
from classical music to ragtime. I feel more musical now, and that's make me think about the side of beeing a  performing musician.
Comment: I think we're getting into a translation problem. When I say "producer", this is more along the lines of product manager for the recording, while you're talking more about being a person who writes or plays musical compositions. Is that really what you mean by that term?
Answer: I find them quite opposite. Most of what happen in a live performance is not captured inside a studio room (that's why many bands like Kiss wanted to release a Live album instead of a studio one).
Recording VS Performing
Focus on sound VS focus on stage
Creation VS Maintenance
In here where I live people often differ Stage Musicians and Studio Musicians. Some musicians are great at studio and aweful on stage, others vice versa.
But both sides can benefit from each other. Gigs are experience for which songs work better for audience and how (if a song is good on a show or driving a car to a work day). For example Dave Grohl wrote Enough Space thinking of the crowd jumping and crashing the floor.
The job of a producer is translate ideas in sounds. The job of a performer is giving the best experience for his/her audience. The opposites attract each other.
Comment: I really want to be an great music producer, so I studying a lot of music, like styles, theory and so on. But I feel a bit strange with the idea of be an theoretical musician and don't really know how to play an instrument like a pro, you know?
Comment: Few orchestral composers can play all instruments in an orchestra. They know how to voice each instrument & how a player will make it sound "right". Production is very similar.
Answer: I producer's job is not to play but to help structure music that is sell-able to mass audiences.  The fact is that with NO musical background it would be hard to convince people that you know good music or how to structure music.  On the other hand there are many great musicians, real virtuosos, who have no idea how to structure a song or what sound "good", they just play well.  My point is that sometimes people are gifted with a good ear, or have their finger on the pulse of musical trends because the listen to a lot of music.  That is what makes a good producer.  You still need to have an idea about music but you don't really need to be a musician to have good musical taste.
Answer: I've always considered the musicianship of producing to be…
"You don't need to be able to play a part yourself, so long as you know exactly how it is that playing it just right differs from playing it averagely."
You need to have a feel for it.
Technically, to be a producer you don't need to be a player at all, or even a sound engineer, but if you're not your decisions may not be as good as if you were.
You need to be able to recognise the difference between the arrangement being wrong & the mix being wrong.
You need to recognise when something is right or wrong & intuitively know what needs to be done to fix it… or indeed when to abandon the idea & move on to something else.
You need the 'genius' idea that takes someone else's session & brings it up from average to great.
What you don't want to be is the guy who just records exactly what the band brings in through the front door. That's not production, that's engineering.
Answer: Absolutely not. Although there's an argument to be made that production is its own kind of musicianship...
Most famous producers aren't performing professional musicians, and that's partly because the mindset is so different. As a pro musician, you worry about technique and executing the music live. As a pro producer, you're not worried about technique and execution, you're worrying about getting a great sound. You wouldn't be worried about nailing the rhythms down perfectly so much as you would be worried about keeping the mix from being muddy.
With zero musical knowledge, being a producer would be difficult. A basic level of musicianship can be a strong tool, since the end result is still music, but by no means do you need to be a Carnegie Hall pianist to put some keys in your EDM track.
I definitely think continuing to practice the instruments you play will be helpful to you, but you probably don't need to concern yourself with being a pro-level instrumentalist. In fact, it's quite common for instruments to be programmed into produced music, where the producer would write the part and the computer would execute it in the song. A knowledge of instruments is helpful for writing those parts, but not strictly necessary.
Composers usually don't play every instrument that they write for at the professional level, and in fact often can write parts for instruments they have never played, simply because they know the sound of that instrument so well. The same is true of producers; if you know the sound of what you want well and have it internalized, you can produce good music.


My pick gets stuck and I'm trying to fix it with downward pickslanting. ( ~ 8 months of playing )

Question: I've been playing for 8 months and I think that this is a common newbie problem: my pick gets stuck. I started to analyze my picking motion/hand and I realised that the pick is too flat ( perpendicular to the strings). I have watched some videos about pickslanting and I'm trying to learn downward pickslanting. Everything is fine with some licks/patterns but when I try to play the songs that I already know with this technique ... everything falls apart.
I'm trying to follow this lesson: https://www.ultimate-guitar.com/lessons/guitar_techniques/complete_guide_to_downward_pickslanting.html
The main things I learned from this lesson are:

You switch strings on an upstroke.
You start with a downstroke.
You do some legato in order to make the first 2 points work.

The problem is that I encounter a lot of patterns where this doesn't work. Am I missing something?
I know that there are players that use only downward pickslanting, how do they do it?
Comment: I suggest you go back to Troy Grady's original outline for this topic, [_Cracking The Code_](https://youtube.com/playlist?list=PLQXEjMNYjt2xBu99q1O9SVN4Eq0mDv50C)
Comment: You may find a training pick helpful. 'Stylus' is the name of one and I used it to good advantage.
Comment: @KeithPayne, I knew these existed.  I could swear I had a yellow one in the 80s.  Even if the company wasn't making them then it could have been a prototype I got at a NAMM convention.
Comment: @KeithPayne Just order a set.
Answer: I may be barking - up the wrong tree here, but watch windscreen wipers working next time it rains. They do what's called feathering. They change angle on the glass after each stroke. Otherwise they judder like crazy. Also notice they hinge easily.
You probably hold the pick too tightly - most beginners do it - for fear of it flicking out of your fingers. For normal playing, hold it only as tight as need be to stop that happening. That means it will flex back and forth as you change direction. Strum in the same sort of way. And, leave only the tip showing. Sometimes beginners will have a quarter of the pick sticking out. Also consider what you're holding it with. Players vary a lot, thumb/index, thumb/index/middle, thumb/middle, etc.
There are times when the pick needs to be solid - raking comes to mind.
And I don't agree with the things you learned in that lesson!
I find most times when I'm playing, that the pick is flat against the string, not like in your picture, so that technique isn't for all playing.
Answer: Looks like you stumbled onto an advanced technique and skipped the small note about the basic technique that underlies it.  In the article you linked: "the most important part about all of this is positioning your hand so that the pick is angled in the right direction" - referring to the fact that the pick should not be parallel to the strings (as shown in this image.)
Answer: I would disagree with the answser that shows a slant.
If you've been playing for 8 months you still have not developed real deep muscle memory for correct movement.  "Tricks" will cheat you out of good technique and tone in the long run.
I've been playing for almost 45 years, and shred.  I flat pick.  As you analyze your pick orientation also analyze your pick shape, material, and thickness (stiffness).  The pick is everything.  I'd take the time to procure a variety of pick sizes, shapes, etc.  If the pick is tapered it is "slanted" by default no matter how you hold it.
At the end of the day practicing with slow controlled relaxed movements over a long period of time (that is years, not for 8 hours straight in one day) will produce amazing clean speed.
And your observation is very astute!  Some picking patterns will not be easy with the slanted pick posture.  When engaging in alternate picking, consecutive picking, sweeping, etc, you will find slight variations in posture may help.  So don't worry if that is the case.  The hand is a very complex structure with many degrees of freedom.  Slight rotations in different directions may be needed to get good tone, etc.  But I would suggest that a good starting point is flat picking, just as you are doing.
As far as the list of things you provided from the lesson (which I'm not inclined to watch) these do not seem like a universal recipe for good picking.  It may apply to one style.  But in reality people often switch strings on a down stroke and start on an up stroke. In fact learning to start on an up stroke is key to learning how to optimize picking patterns.
You are a beginner.  I'd recommend taking it slow, controlled and relaxed and most of all accurate.  In time your body will learn to play anything at any speed in that frame of mind+body.
Comment: True. I'd also advocate having a break from watching on-line 'tutorials', and just plough your own furrow...
Comment: Or taking real lessons.  Even if an online tutorial is well made and the player is good they cannot watch you and give feed back.
Comment: Real one to one lessons are the way to go, but right now, that's risky to impossible. I've started to do some on Wattsapp, but I much prefer teaching face to face, Answers are immediate, rather than not even possible!
Comment: "practicing with slow controlled relaxed movements over a long period of time ... will produce amazing clean speed" : Troy Grady says that playing slow and playing fast are two different techniques with different movements, like walking and running. And you don't learn to run by walking faster, you have to enter a different operating mode. https://forum.troygrady.com/t/the-building-speed-question/11257 The consensus seems to be that slow mode movements don't necessarily translate over to fast mode, so you have to have a method for verifying if your picking motions are "fast-friendly".
Comment: That consensus is not proof.  I would cite Kenny werner, effortless mastery.  It works for me.
Comment: The analogy between picking and running is completely false.  There is no scientific evidence of this similarity.  Different movements on different time and distance scales.


How can one do "two series" Fourier analyses in R?

Question: In Statistica one can do a "two series"/bivariate/cross spectrum Fourier analysis to examine the coherency, gain, and phase spectrum across a pair of signals.  It is probably a failing on my part, but my attempts to use those search terms to come up with similar values from R have come up blank.  What functions/packages should I review in more detail?  Can you provide some simple examples?
Comment: I've used various EEG analysis packages to accomplish the same thing, but never in R -- see if the "bivariate" snippet here is what you are looking for http://stat.ethz.ch/R-manual/R-patched/library/stats/html/spec.pgram.html
Comment: Close, but it doesn't seem like it calculates gain.
Comment: I'm not sure how to do that using R.
Answer: The same familiar spectrum instruction yields cross-spectra. coherency and phase when used on a bivariate time series. Look at this sample code. dIPC and Crudo are respectively (differenced) consumer price index and oil price.
We first build a bivariate time series (out of ordinary ts time series) with ts.union, then invoke spectrum.
datos <- ts.union(dIPC,
           Crudo)
datos <- window(datos,
           start=c(1979,1),
           end=c(2002,1))
sp <- spectrum(datos,
           main="Petróleo e IPC",
           spans=rep(3,5))

We only need now to plot coherency and phase. I find it useful to align them one below the other with
par(mfrow=c(2,1))

and then do the plots:
plot(sp,plot.type="coh")
plot(sp,plot.type="phase")

Comment: You can dig the source of spectrum, and you will find that cross-spectra are computed in an object of name pgram. Or, since the coherency is defined as the cross-spectrum divided by the square root of the product of univariate spectra (i.e. f12 / sqrt(f11*f22) ), you can find what you want the two gains as tou define them by multiplying the squared coherency by either univariate spectra.
Comment: What does (differenced) mean in this context?  Is it just a characteristic of your data, or does it represent something I must do to my data before analysis?
Comment: You difference series x(t) by replacing it with dx(t) = x(t) - x(t-1). Since spectral analysis is intended for stationary random processes, this is a way of bringing non stationary data to near stationarity. Only needed if strong trends are apparent.
Comment: How is gain calculated from this output?
Comment: Per Statistica's website: "The gain value is computed by dividing the cross-amplitude value by the spectrum density estimates for one of the two series in the analysis. Consequently, two gain values are computed, which can be interpreted as the standard least squares regression coefficients for the respective frequencies." But I'm unclear on how to find the cross-amplitude value.


Song Out Of Range

Question: What does it mean when someone says a song is not in their range? Does it simply mean they can't hit the highest or lowest notes of a song or is it something that I'm missing? Look at the link to the article I posted below and read the first 2 paragraphs. What exactly does she mean?
If a song isn't in your range what can you do to put it in your range? I thought you just transpose it to a different key and sing it whatever octave the tessiture of your vocal range is.
http://blog.smule.com/tuesday-tips-how-to-know-what-song-is-suited-to-your-voice
Comment: Tessitura relates not to one's vocal range, but the notes in a song itself. When there are a lot of higher notes, the song is said to have a high tessitura.
Answer:
What does it mean when someone says a song is not in their range? Does it simply mean they can't hit the highest or lowest notes of a song...?

That's exactly what it means.

If a song isn't in your range what can you do to put it in your range? I thought you just transpose it to a different key and sing it whatever octave the tessiture of your vocal range is.

Yes, this is a very popular way to make a song that is not normally in a singer's range fit the singer. At the same time, transposing a song often changes the sound and feel of it in subtle ways. Many singers and musicians prefer not to transpose music and would rather pick a different song to sing that fits their range.
Answer: As someone who sings a lot of music (nowadays mainly in the shower), I end up singing a lot of music that's outside my range for at least a few notes (or outside my most comfortable range in several notes). By "outside my range", I mean I cannot hear myself sing the note at all, and by "outside my most comfortable range", I mean it takes me more effort to sing the notes (such as the C that's 2 octaves above Middle C).
Whenever the song gets out of my (most comfortable) range, I transpose the section an octave (up or down as necessary). In general, I do not prefer transposing what I sing into different keys--it's more difficult to remember that way, and in classical music, the key of the piece is often in the title (such as Mozart's "Symphony No. 40 in G Minor") and therefore looks bad in transposed versions.
Comment: So - you now need to work on being able to transpose on the fly. There is no reason with songs that they *have* to be in a certain key, for the most part. The original key can't be called the *proper* key - although some of the people I play with believe it to be so. Wouldn't it be good to think of a song in Eb, but then be able to sing it in F#? All to gain, nowt to lose! And of all people, those with absolute pitch are very capable of recogising their own range...
Comment: @Tim, I've found that I'm significantly less accurate at singing transposed versions the moment the music modulates. I'm only a bit less accurate on average if the music doesn't switch keys, but I cannot transpose atonal music on the fly at all. (If I have heard the song in more than one key, I can sing versions in those keys accurately.) I do think of several songs as having no native key (and therefore I am OK with singing them in whatever key I want), but they tend to be folk songs, children's songs, or Christmas carols like "Lightly Row" or "O Christmas Tree".
Comment: If you're singing in isolation, or even in the shower, how do you know you're singing in a particular key?  Absolute pitch? In which case, what's wrong with knowing you can't sing in the written key, and transpose the tune? Not that Mozart 40 was written to be sung in any case.
Comment: @Tim, you guessed right--I have absolute pitch. My memory of music is good enough that I can remember specific recordings, so I often rely on them as the originals I base my sung versions on. I find it harder to remember a transposed version, especially since I can no longer base it on the recording. I normally shift sections an octave on the fly.

Song Out Of Range


Running sockets.io in node without sudo access

Question: I have a socket.io node file that starts like this...
//sockets/server
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80); //the 5th line that the error refers to

When I run from the console with "node myFile.js" I get the following error...
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: listen EACCES
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1112:19)
    at listen (net.js:1155:10)
    at Server.listen (net.js:1240:5)
    at Object.<anonymous> (/home/myUser/node/myFile.js:5:5)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)

I can easily get around the error on my local machine (MAMP) by adding 'sudo' to the start of the command, but my hosting provider won't let me do that on the production environment.
Does anyone have any idea of a way to fix the error (or even know what it means) as opposed to sudoing it out of the way?
Comment: Possible duplicate of [Node.js EACCES error when listening on most ports](http://stackoverflow.com/questions/9164915/node-js-eacces-error-when-listening-on-most-ports)
Comment: Thanks Ben - you're right - don't know how I didn't find that post but it does describe the correct approach which just worked perfectly for me (as does the answer posted below by Tatsuyuki which I'll accept shortly).
Comment: You can also run your server on a higher number port that does not require those higher privileges (which keeps you from having to give your server root privileges) and then use iptable configuration to redirect port 80 to your higher port number.  I do this on my Raspberry Pi to keep from having to give my server process higher privileges, but it does successfully serve port 80.
Answer: Port 80 is a privileged port, and you need root or CAP_NET_ADMIN to bind to it.
The solutions are:

Do not bind to port 80 for development.
Configure your system to allow the port to be used as a normal user. See: https://superuser.com/questions/710253/allow-non-root-process-to-bind-to-port-80-and-443
Comment: Yeah, well you got my upvote anyway - thanks for the answer - I chose 8080 and it works perfectly - will accept answer shortly...


Como descobrir as coordenadas de um click na scene do Babylon.js?

Question: Boa tarde, pessoal
Estou iniciando em Babylon há pouco tempo, estou buscando algum jeito de descobrir a posição do mouse, quando houver algum click no canvas.
Consegui facilmente descobrir isto para um dado objeto, porém não para a scene em si (!?)
Não sei o que pode estar errado, parece bobo, mas estou há horas sem descobrir... Quem puder ajudar, agradeço!

 window.addEventListener('DOMContentLoaded', function () {
            var canvas = document.getElementById('canvas');
            var engine = new BABYLON.Engine(canvas, true);

            var createScene = function () {
                   var scene = new BABYLON.Scene(engine);
                   scene.clearColor = new BABYLON.Color3.White();

                   var box = BABYLON.Mesh.CreateBox("Box",4.0,scene);
                   var camera = new BABYLON.ArcRotateCamera("arcCam",
                    BABYLON.Tools.ToRadians(45),
                    BABYLON.Tools.ToRadians(45),
                    10.0,box.position,scene);
                   camera.attachControl(canvas,true);

    var light = new BABYLON.PointLight("pointLight",new BABYLON.Vector3(
            0,10,0),scene);
    light.diffuse = new BABYLON.Color3(1,1,1);

    var onpickAction = new BABYLON.ExecuteCodeAction(
    BABYLON.ActionManager.OnPickTrigger,
    function(evt) {

        console.log("(",evt.pointerX,",",evt.pointerY,")");

    });

    //não funciona
    scene.actionManager = new BABYLON.ActionManager(scene);
    scene.actionManager.registerAction(onpickAction);

    //funciona normalmente
    box.actionManager = new BABYLON.ActionManager(scene);
    box.actionManager.registerAction(onpickAction);

    return scene;
}

           var scene = createScene();
            engine.runRenderLoop(function () {
                scene.render();
            });
        });
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <canvas id="canvas"></canvas>

Answer: Olá,
Existe o evento onPointerDown no babylon onde você consegue pegar os eventos segue a documentação e um exemplo.
Espero que ajude.


Entropy of random variable which denotes the number of heads landed after 3 coin flips

Question: I am not sure how to work this out but I split the outcomes of 3 coin flips into the 8 possible outcomes: HHH, HHT, HTH, HTT | TTT, TTH, THT, THH
And have gotten a probability mass function for the random variable out of the 3 flips(only 1 head is 1/4, only 2 heads is 3/8, only 3 heads is 1/8) -
I have calculated the entropy as $H(x) = -sum(P(xi)*logP(xi)) =-1/4*log(1/4)-3/8*log(3/8)-1/8*log(1/8)$ - is that method correct?
Comment: The probability of only 1 head is wrong. You should also consider the probability of the event of zero heads.
Comment: true. hadn't thought of that
Answer: Your method is right, except that you did not compute the correct mass function reflecting the random variable of interest. For more on entropy, this is a lecture were i explain the intuition behind it.
Let $X$ be the random variable denoting the number of heads in your experiment
\begin{align}
 p_0  \triangleq \Pr(X = 0) &= \Pr(TTT) = \frac{1}{8}\\
 p_1  \triangleq\Pr(X = 1) &= \Pr(HTT) +\Pr(THT)+\Pr(TTH)  = \frac{3}{8}\\
 p_2  \triangleq\Pr(X = 2) &= \Pr(HHT) +\Pr(HTH)+\Pr(THH)  = \frac{3}{8}\\
 p_3  \triangleq\Pr(X = 3) &= \Pr(HHH)   = \frac{1}{8}
\end{align}
This is a mass function because $\sum p_i = 1$, in contrast to yours which is not. Now, we can easily compute the entropy
$$H(X) = - \sum p_i \log p_i$$


Irrationals vs rationals

Question: In real number system, given a number"n" whats the number immediately after"n"
lets say the number after "n" is "y". Is "y" rational or irrational???
By the completeness property of real number system "y" can be both rational and irrational..
So "y" does not exist?
Comment: Tom, I prefer to say, there is no such thing as the next real number.
Comment: @Tom for something to not exist, this something must still be defined first. You haven't defined the number immediately after $n$.
Comment: @Gerry's point seems to be that if something doesn't exist, then it is better not to refer to it by a naming convention that suggests it does (unless using a contradiction argument such as the above, in which case there is only briefly a name assigned). I may be off base, here, though.
Comment: @Dan: Ah! That makes more sense. Precision is good.
Comment: Right---there is no such thing as the "next" real number.
Comment: So "y" doesn't exist?
Comment: Do you know that the order is dense? Right? So there is no number  immediatly after a real number. Given $x, y \in \mathbb{R}$ there exists infinite (non - countable) numbers $z$ such that $x < z < y$
Comment: yeah, so it implies that such a number does not exist..
Comment: @Dan: That seems completely nonsensical to me. Being mathematically (well-)defined *entails* existence. There are certainly no non-existent mathematical entities that are (well-)definable. A viable argument (if you buy excluded middle arguments) proceeds as follows: "Suppose that there is some least real greater than $n,$ say $y.$ But since the reals are densely ordered, then we can find a real $z$ with $n<z<y.$ Contradiction. Thus, there is no least real greater than $n$."
Comment: @CameronBuie You see, your argument is talking about "some least real greater than $n$". That's your definition of "the number immediately after $n$". So before proving non-existence, you fashioned a definition. That is all I meant: you need something more concrete than a vague intuitive adjective like "next" or "immediate" to prove non-existence.
Comment: @CameronBuie Sorry for being too pedantic. It's just that I've participated more than once in conversations with non-mathematicians who talked about things like "adjacent numbers" without stopping to think what it is that they mean.
Answer: In the real number system, there is no number immediately after $n$. Such a number would be the least number greater than $n$--that is, the least element of $(n,+\infty),$ which has no least element.
The standard ordering of the reals is a dense linear order, meaning that between any two distinct elements, there is another element. Thus, there can be no least number greater than $n$, since if $y$ is a number greater than $n,$ there is some $n<z<y$.

Irrationals vs rationals


Define permissions for Actions?

Question: function custom_mod_action_info() {
  return array(
    'custom_mod_delete_user_cats' => array(
      'label' => t('Delete a users cats'),
      'type' => 'user',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}

This action is later used as VBO in a View.
I've defined an action like above in a custom module. How can I set some permissions so only users with a specific role can run this action?
Comment: I think the idea is that you secure permissions for the entities themselves, not the action. So if you have access to an entity, you can implicitly perform the action on it. I might be wrong though
Answer: For D7, I can see two answer depending on what behaviour you prefer:

VBO has a sub-module action permissions.  Enable this and it creates a permission for each action - see module page.  If the user lacks permission then the action is not even available for them.
If you need more granular permission that depends on the entity, then the "function which performs the action" can enforce it.  For example see views_bulk_operations_user_roles_action.  If the user lacks permission for some of the entities then the action won't take effect for those entities.  However there is typically not really any feedback to tell the user.

For D8, there is ActionInterface::access, see docs.

Define permissions for Actions?


Projective varieties of dimension $m$

Question: Let $X \subset \mathbb{CP}^n$ be a projective variety of dimension $m$. Is it true that $X$ can be realized as the image of a holomorphic map $f: \mathbb{CP}^m \to \mathbb{CP}^n$?
To this end, if there is a non-constant map $f: \mathbb{CP}^m \to X$ then it must be a surjection. This follows by the open mapping theorem together with compactness of $\mathbb{CP}^m$ and connectedness of the target. The thing that is unclear to me is whether or not one can always construct a non-constant holomorphic function from $\mathbb{CP}^m$ to an arbitrary projective variety.
Comment: You asked this a few days ago, no? I had added a comment asking you what happens in the case of curves, in particular the simplest case, that of elliptic curves. Did you think about that?
Comment: @MarianoSuárez-Álvarez Yes I did see your comment! Unfortunately I got stuck trying to write down specific maps by hand rather than thinking about things like Riemann-Hurwitz. Of course now I understand that there can be no non-constant meromorphic maps from a curve of lower genus to a curve of higher genus.

The source of my confusion was this: Say I take a degree 3 map from CP^1 to CP^2 and look at its image. I had previously assumed that the use of the word "degree" here would indicate the image would be some projective curve of degree 3 (genus 1), but this is evidently not the case.
Comment: I suppose the deeper cause of my confusion is forgetting that degree is not an intrinsic concept. Take a rational normal curve in P^d, which can be written as the image of a map P^1 -> P^d. The degree of this curve is certainly d, but its genus is not given by the usual formula 2g = (d-1)(d-2) because the curve is not being realized in P^2.
Answer: If $X$ is smooth and not the projective space itself, then this is impossible by the following:
Theorem [Lazarsfeld, Thm. 4.1]. Let $X$ be a smooth complex projective variety of dimension $m$. Assume that there is a surjective morphism $\mathbf{P}^m \to X$. Then, $X \cong \mathbf{P}^m$.
There is also a version in positive characteristic, when the morphism is assumed to also be separable; see [Kollár, Cor. V.3.5].
On the other hand, you can have singular $X$ that admit surjective morphisms from $\mathbf{P}^m$ by taking the quotient of $\mathbf{P}^m$ by a finite group.
Answer: One situation where this is impossible is when $X \subset \mathbb{CP}^2$ is a elliptic curve (i.e. a smooth complex projective curve of genus 1, realisable as a cubic hypersurface in $\mathbb{CP}^2$).
If there exists a surjective map $f : \mathbb{CP}^1 \to X$, then by the Riemann-Hurwitz formula, we would have
$$ 2g(\mathbb{CP}^1) - 2 = N (2g(X) - 2) + \sum_{P \in \mathbb{CP}^1} (e_P-1),$$
where $N$ is the degree of the covering map $f : \mathbb{CP}^1 \to X$, and for each $P \in \mathbb {CP}^1$, $e_P$ is the ramification index of $f$ at $P$ (which is greater than one at only finitely many $P \in \mathbb{CP}^1$).
Now, $g(\mathbb {CP}^1) = 0$, and $g(X) = 1$, so the left-hand side is negative, while the right-hand side is non-negative. This is a contradiction.

Projective varieties of dimension $m$


References for Higgs bundles

Question: I would like to ask if someone knows good references for the construction of the moduli space of Higgs bundles from the G.I.T point of view, and the study of this moduli space from the stacky point of view.
Thank you for your time.
Answer: The first GIT construction of the moduli space of semistable Higgs bundles on a curve is due to Nitsure, and is described in detail in his paper "Moduli space of semistable pairs on a curve" (https://londmathsoc.onlinelibrary.wiley.com/doi/abs/10.1112/plms/s3-62.2.275).
As for the moduli stack of Higgs bundles, its construction is given in the lectures notes "An introduction to moduli stacks, with a view towards Higgs bundles" by Casalaina-Martin and Wise (https://arxiv.org/pdf/1708.08124.pdf). There is also a comparison of the moduli stack and moduli space of semistable Higgs bundles in Section 7.7 of these notes.
Comment: AN INTRODUCTION TO MODULI STACKS, WITH A VIEW
TOWARDS HIGGS BUNDLES ON ALGEBRAIC CURVES looks good... I was looking for something similar https://mathoverflow.net/questions/337533/road-map-for-moduli-space-moduli-problem-moduli-stack

References for Higgs bundles


Understanding sets of polynomials as subspaces

Question: I have a homework assignment, that I can't quite wrap my head around, let me state the question, and show my progress.
Let $n$ be a natural number, and let $\alpha \in \mathbb{R}$ be a real scalar. Consider the subset
\begin{equation*}
  V=\{p\in P_n(\mathbb{R}):p(\alpha)=0\},
\end{equation*}
of the real vector space $P_n(\mathbb{R})$.
First I need to show, that $V$ is a subspace of $P_n(\mathbb{R})$, and as far as I figure, $V$ is the set containing all polynomials of degree $\leq n$ where no matter the variable $\alpha$ the polynomial equals $0$.
I've then showed that since all elements are $0$ it's closed under addition, scalar multiplication and it ofcourse contains $0$ itself. I assume what I have done so far is correct, but am unsure.
Next up I need to decide the dimension of $V$ and I have been hinted that I need to use the formular $\text{dim}(v)=\text{dim}(\text{ker}(L))+\text{dim}(L(V))$ on the imaging $L:P_n(\mathbb{R})\rightarrow\mathbb{R}$ defined as $L(p)=p(\alpha)$.
I assume $\ker(L)=0$ since all coefficients in the polynomial has to be $0$, and therefore $\dim(\ker(L))=0$ as well. Same goes for $L(V)=0$ and $\dim(L(V))=0$, so is the answer to this question just $0$?
The reason why I'm unsure of myself is because I feel it's almost too easy with all these zeroes.
Sorry if some of the terminology is wrong, english is not my first language.
Comment: I don't think you are interpreting the problem correctly.  I believe that $\alpha$ is a fixed real number, so that $V$ is the set of polynomials of degree $\le n$ with a root at $\alpha.$
Answer: By Bézout's Theorem we have $$p\in V\iff p(x)=(x-\alpha)q(x),$$ where $q\in P_{n-1}(\Bbb R).$ Then $\dim V=n$ (the same as the dimension of $P_{n-1}(\Bbb R)).$ Why $V$ is a subspace? Because it is easy to see that $ap+bq\in V$ whenever $p,q\in V$ and $a,b\in\Bbb R.$


How to get fields from taxonomy terms?

Question: I am able to retrieve taxonomy terms programmatically, (as long as I only want to reference the default fields, 'tid' and 'name'). But how do I access custom taxonomy fields?
$vid = 'MACHINE_NAME';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
    $tid = $term->tid;
    $term_name = $term->name;

    // REFERENCE CUSTOM FIELD VALUES HERE...

}

I have tried all manor of ways I have seen, but can't get any of them working, eg:
$value = $term->FIELD_NAME->value;
$value = $term->get('FIELD_NAME')->getValue();

How do I reference custom taxonomy term fields by their machine name, from what is returned by getStorage('taxonomy_term')->loadTree($vid)?
Comment: Either should be correct, but only assuming the field type has a column named `value`. What type of field is it?
Comment: Correct, it depends on the field type. Look here for info about how to get the value from an entity reference field, https://drupal.stackexchange.com/a/284658/72672.
Comment: @Clive It's a text field, but I couldn't get either to work earlier. I'm AFK now, so will experiment with getValue() when I get back. Jdrupal, thanks for that useful link!
Comment: Just realised this happened to me before, the answer should help :)
Answer: The entities aren't loaded by default (for performance reasons), but TermStorage::loadTree takes a $load_entities parameter:

If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy_term_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.

That will give you access to the fields. E.g.
$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadTree($vid, 0, NULL, TRUE);

Comment: Brilliant, thanks @Clive. getValue() returned an array, so I swapped it for getString(), but it's all working now fine!
Comment: Thank you!  That got me much closer to the solution. In my case, I have a known taxonomy id... i just want the machine_name.
Your code above returns an array with every child of the vocabulary - not the paraent.

`   An array of term objects that are the children of the vocabulary $vid.`

How to get fields from taxonomy terms?


Outlook add-in with Visual Studio 2013 not works

Question: I created a small add-in outlook project with visual studio 2013. When I run the add-in for the 1st time, it works. But if I start outlook and that I remove this add-in, when I want to launch it again from visual studio to debug for example, the add-in is no more taken into account by outlook. What does do to solve this problem?
Comment: If the answer was useful to you or solved your problem, please mark it as correct. Otherwise, give us more detail if the solution did not work and we can attempt to help you further.
Answer: If you created a VSTO based add-in you just need to build it to get it registered anew.
Typically the windows registry keys allow to detect what add-ins are registered and then load them. Read more about the required windows registry keys in the Registry Entries for Application-Level Add-Ins article.
Comment: Thanks for you answer. I don't no why, but only do a build or re-build the add-in is not enough. But with you information about registry, if I delete the entry for the add-in, then build it then it works anew.
Answer: You must rebuild the project within Visual Studio. Once you do a Rebuild it will load into Outlook the next time that you run the debugger.


Interpolation and Extrapolation of Randomly Scattered data to Uniform Grid in 3D

Question: I have a 256 x 256 x 32 grid of regularly spaced points ranging over x, y, and z and with an associated variable "a". I also have a group of randomly scattered points in a more confined x, y, z space, with an associated variable "b". What I essentially want to do is interpolate and extrapolate my random data to a regularly spaced grid that matches the "a" cube, as shown below:

I have used scipy's griddata so far to achieve the interpolation, which seems to work fine, but it cannot handle the extrapolation (as far as I know) and the output sharply truncates to 'nan' values. Whilst researching this problem I came across a couple of people using griddata a second time with 'nearest' as the interpolation method to fill in the 'nan' values. I tried this but the results don't seem reliable. More appropriate looking results are obtained if I use a fill_Value with 'linear' mode, but at the moment it's more a fudge because fill_Value has to be a constant.
I noticed that MATLAB has a ScatteredInterpolant class which seems to do what I want, but I am unable to find an equivalent class in Python, nor figure out how to implement such a routine efficiently in 3D. Any help is greatly appreciated.
The code I am using for the interpolation is below:
x, y, z, b = np.loadtxt(scatteredfile, unpack = True)

# Create cube to match aCube dimensions
xi = np.linspace(-xmax_aCube, xmax_aCube, 256)
yi = np.linspace(-ymax_aCube, ymax_aCube, 256)
zi = np.linspace(zmin_aCube, zmax_aCube, 32)

# Interpolate scattered points
X, Y, Z = np.meshgrid(xi, yi, zi)
bCube = griddata((x, y, z), b, (X, Y, Z), method = 'linear')

Comment: Are the points in space count data or are they coordinates with a corresponding measurement `f(x,y,z)`?  Are you sure this is interpolation and extrapolation?  It looks like you may be wanting to bin the points into the 3-d bins you have constructed.
Comment: in case your ``b`` data are somewhat well-behaved, you could add some evenly spaced synthetic data points to your scattered cloud to force the behavior you want - but that totally depends upon your use-case (might be justified for simply displaying the data)...
Answer: This discussion applies in any dimensionality. For your 3D case lets talk about computational geometry first, to understand why part of the region gives NaN from griddata.
The scattered points in your volume make up a convex hull; a geometric shape with the following properties:

The surface is always convex (as the name suggests)
The volume of the shape is the lowest possible without violating convexity
The surface (in 3d) is triangulated and closed

Less formally, the convex hull (which you can compute easily with scipy) is like stretching a balloon over a frame, where the frame corners are the outermost points of your scattered cluster.
At the regular grid location inside the balloon you're surrounded by known points. You can interpolate to these locations. Outside it, you have to extrapolate.
Extrapolation is hard. There's no general rule for how to do it... it's problem-specific. In that region, algorithms like griddata choose to return NaN - this is the safest way of informing the scientist that s/he must choose a sensible way of extrapolating.
Let's go through some ways of doing that.
1. [WORST] Botch it
Assign some scalar value outside the hull. In the numpy docs you'll see this is done with:
    s = mean(b)
    bCube = griddata((x, y, z), b, (X, Y, Z), method = 'linear', fill_value=s)
Cons: This produces a sharp discontinuity in the interpolated field at the hull boundary, heavily biases the mean scalar field value and doesn't respect the functional form of the data.
2. [NEXT WORST] "Blended botching it"
Assume that at the corners of your domain, you apply some value. This might be the average value of the scalar field associated with your scattered points.
Sorry, this is pseudocode as I don't use numpy at all, but it'll probably be fairly clear
# With a unit cube, and selected scalar value
x, y, z, b = np.loadtxt(scatteredfile, unpack = True)
s = mean(b)
x.append([0 0 0 0 1 1 1 1])
y.append([0 0 1 1 0 0 1 1])
z.append([0 1 0 1 0 1 0 1])
b.append([s s s s s s s s])
# drop in the rest of your code

Cons: This produces a sharp discontinuity in gradient of the interpolated field at the hull boundary, fairly heavily biases the mean scalar field value and doesn't respect the functional form of the data.
3. [STILL PRETTY BAD] Nearest neighbour
For each of the regular NaN points, find the nearest non-NaN and assign that value. This is effective and stable, but crude because your field can end up with patterned features (like stripes or beams radiating out from the hull), often visually unappealing or, worse, unacceptable in terms of data smoothness
Depending on the density of data, you could use the nearest scattered datapoint instead of the nearest non-NaN regular point. This can be done simply by (again, pseudocode):
bCube = griddata((x, y, z), b, (X, Y, Z), method = 'linear', fill_value=nan)
bCubeNearest = griddata((x, y, z), b, (X, Y, Z), method = 'nearest')
indicesMask = isNan(bCube)
# Use nearest interpolation outside the hull, keeping linear interpolation inside.
bCube(indicesMask) = bCubeNearest(indicesMask)

Using MATLAB's delaunay based approaches will reveal more powerful methods for achieving similar in a one-liner, but numpy looks a bit limited here.
4. [NOT ALWAYS TERRIBLE] Naturally weighted
apologies for poor explanation in this section, I've never written the algorithm but I'm sure some research on the natural neighbour technique will get you far
Use a distance weighting function with some parameter D, which might be similar to, or twice (say) the length of your box. You can adjust. For each NaN location, figure out the distance to each of the scattered points.
# Don't do it this way for anything but small matrices - this is O(NM)
# and it can be done much more effectively (e.g. MATLAB has a quick
# natural weighting option), but for illustrative purposes:
for each NaN point 1:N
    for each scattered point 1:M
        calculate a basis function using inverse distance from NaN to point, normalised on D, and store in a [1 x M] vector of weights
Multiply weights by the b value, summate and divide by M

You basically want to end up with a function that smoothly goes to the average intensity of B at a distance D away from the hull, but coincides with the hull at the boundary. Away from the boundary it is weighted most strongly on its nearest points.
Pros: nicely stable and reasonably continuous. Because of the weighting, is more resilient to noise at single data points than nearest neighbour.
5. [HEROIC ROCKSTAR] Functional form assumption
What do you know about the physics? Assume a functional form that represents what you expect the physics to do, then do a least squares (or some equivalent) fit of that form to the scattered data. Use the function to stabilise the extrapolation.
Some good ideas which can help you construct a function:

Do you expect symmetry or periodicity?
Is b a component of a vector field which has some property like zero divergence?
Directionality: do you expect all corners to be the same? Or maybe a linear variation in one direction?
is field b at a point in time - perhaps a smoothed timeseries of measurements can be used to come up with a basic function?
Is there already a known form like a gaussian or quadratic?

Some examples:

b represents intensity of a laser beam passing thru a volume. You expect the entry side to be nominally identical to the outlet, with the other four boundaries of zero intensity. The intensity will have a concentric gaussian profile.
b is one component of a velocity field in an incompressible fluid. The fluid must be divergence free, so any field produced in the NaN zone must also be divergence free so you apply this condition.
b represents temperature in a room. You expect higher temperature at the top, because hot air rises.
b represents lift on an aerofoil, tested over three independent variables. You can look up the lift at stall easily, so know exactly what it'll be in some parts of the space.

Pros/Cons: Get this right and it'll be awesome. Get it wrong, especially with nonlinear functional forms, and it will go very wrong and can lead to very unstable results.
Health warning you can't assume a functional form, get pretty results, then use them to prove that the functional form is correct. That's just bad science. The form needs to be something well behaved and known independent of your data analysis.
Answer: If your scatter of points conforms fairly well to a cube shape, one approach could be to use griddata to interpolate onto a regular grid of data that fits within your point cloud (therefore avoiding nans) and then use this regular grid of values as the input to interpn which does facilitate linear extrapolation (but requires a regular grid as input).
This way you can use griddata as before for all the points within the convex hull of your scatter of points and you can use interpn to estimate the points that are returned as nans.
This is far from perfect, but I think it comes closer to achieving what you are looking for.
Pros:

Avoids sharp discontinuities.
Captures the basic linear trends at the edge of your dataset without having to know the functional form.
Respects asymmetries in your data (e.g. doesn't tend to the population mean at large distances, so one side of your dataset can have larger values than the other at large distances.)

Cons:

The effectiveness of this approach will depend a lot on how large a cube you can fit within the convex hull of your initial scatter of points. If your data is spikey/patchy and irregular then even points on the edge of the convex hull may have been extrapolated significant distances from the edge of the nested cube, incurring errors as the extrapolation won't be taking into account nearer data points that lie outside the cube.
The linear extrapolation will be heavily influenced by noise in the data
at the edges of the point cloud.
Computational cost of doing two sets of interpolations.


What's the preferred method of creating different page templates

Question: Basically, I want to give my articles and blog entries a different class on the body so I can style them independently.
I am given to understand that the best way to do this is with creating custom tpl files
I'm working in a custom built theme that is pretty much running just on a page.tpl.php and a stylesheet.
How would I do this easily in Drupal 7? I tried this method for drupal 6 but it didn't seem to work.
Answer: This should by there by default.
For example, the body classes on my test site look like this for a simplenews node:
<code><body class="html not-front logged-in one-sidebar sidebar-first page-node page-node- page-node-90 node-type-simplenews toolbar toolbar-drawer i18n-en" >
</code>
As you can see, there is node-type-simplenews, among many other things.
Those classes are defined in template_preprocess_html() and are using in html.tpl.php (not page.tpl.php, unless you've overriden that. If so, you need to duplicate the logic in that function for your page.tpl.php.
Comment: Wow you're right. I thought I had checked that, but I had not realized that chrome developer tools summarizes the inheritence list at the bottom.. i thought it was showing me everything.


Question regarding generalized Egoroff's Theorem

Question: I'm looking at this problem, which asks one to prove a generalized version of Egoroff's Theorem. While I understand the OP's approach to divide $X$ into a countable number of subsets (and apply Egoroff's Theorem to those with finite measure), I don't understand his final claim, that $f_n \to f$ uniformly on $E^{c}$. Roughly speaking, the OP's argument is "if $f_n \to f$ uniformly on a countable  collection of sets $\{A_k\}_{k_1}^{\infty}$, then $f_n \to f$ uniformly on $\bigcup_{k=1}^{\infty} A_k$". However, this is not necessarily true. I can't find a good justification for his last step.
Comment: You are right, this is a big issue in the question you linked.  Notice that the author's solution does not really use the fact that $g$ is integrable --- I suspect that exploiting this more fully will lead to a proof.
Answer: David Giraudo in this posting gives a nice solution to the problem. I present the outline and some details
Define $g_n=\sup_{k\geq n}|f_k-f|$.
Notice that

$g_n$ is monotone nonincreasing,
$0\leq g_n\leq 2g$,
and $g_n\xrightarrow{n\rightarrow\infty}0$ $\mu$-a.s. since $f_n\xrightarrow{n\rightarrow\infty}f$ $\mu$-a.s.
By Markov-Chebyshev's inequality, for all $n,m\in\mathbb{N}$
$$\mu(g_n> 1/m)\leq m\int_Xg_n\,d\mu\leq 2\int_X g\,d\mu<\infty$$
Dominated converges implies that
$$\lim_n\int_X|g_n|\,d\mu=0$$

Hence, given $\varepsilon>0$, one can choose a subsequence $n_m$ along which
$$\mu(g_{n_m}>1/m)\leq \varepsilon 2^{-m}$$
Define $A_m=\{g_{n_m}>1/m\}$ and $B:=\bigcap_m(X\setminus A_m)$.

For all $x\in B$,  $0\leq g_{n_m}(x)\leq \tfrac1m$ for all $m$. This means that $f_n$ converges uniformly on $B$. Indeed, for any $\varepsilon'>0$ choose $M$ large enough so that $1/M <\varepsilon'$. Then for all $n\geq n_M$,
$$\sup_{x\in B}|f_n(x)-f(x)|\leq\sup_{x\in B}g_{n_M}(x)\leq \tfrac1M<\varepsilon'$$

$\mu(X\setminus B)=\mu\Big(\bigcup_mA_m\Big)\leq\sum_m\varepsilon 2^{-m}=\varepsilon$.


Synthetic control method when every unit is affected, but at different times

Question: The synthetic control method can be used to calculate the effect of an event when some units are affected by the event but others are not.
What method can I use if all units are affected by the same event, but at different times? For example, I have data on the productivity of different teams in a workplace, and also the number of people joining and leaving in each period (mostly 0 people leave each period, but sometimes someone leaves. The case is similar for joining.). I want to study the effect of someone leaving on team productivity.
Answer: You need some untreated units to form the counterfactual. To the extent that there are none, or just a few, left to form the control, your ability to reweight them will be nonexistent or severely compromised.
Unfortunately there are no other methods that would work well in this setting that are also credible.


Querying across multiple elasticsearch types

Question: I want to fetch documents present in multiple types (type1 AND type2 AND type3...) in Elastic Search 5.0 . I know searching across multiple types is possible by using multiple types like type1,type2 in URL and by also filtering the _type field. But all these conditions are OR (type1 OR type2). How do I achieve the AND condition?
Here are two documents in my ES,
{
   "_index":"cust_58e8700034fa4e368590fb1396e2641c",
   "_type":"unique-fp-domains",
   "_id":"n_d4dbba7309a94503b25eca735078f17c_258b3ad1a11aba282f35908662bdc5432d68fd96bf3ca90013dcdd5764331399",
   "_version":2,
   "_score":1,
   "_source":{
      "mg_timestamp":1579866709096,
      "violated-directive":"connect-src",
      "fp-hash":"258b3ad1a11aba282f35908662bdc5432d68fd96bf3ca90013dcdd5764331399",
      "time":1579866709096,
      "scan-id":"n_d4dbba7309a94503b25eca735078f17c",
      "blocked-uri":"play.sundaysky.com"
   }
}

{
   "_index":"cust_58e8700034fa4e368590fb1396e2641c",
   "_type":"tag-alexa-top1k-using-csp-tld-domain",
   "_id":"AW_XY4P4kmprPQ28bTUb",
   "_version":1,
   "_score":1,
   "_source":{
      "tagged-domain":"sundaysky.com",
      "tag-guidance":"FP",
      "additional-tag-metadata-isbase64-encoded":"eyJ0b3RhbC1hbGV4YS1tYXRjaGVzIjoyMzh9",
      "project-id":2,
      "fp-hash":"258b3ad1a11aba282f35908662bdc5432d68fd96bf3ca90013dcdd5764331399",
      "scan-id":"n_d4dbba7309a94503b25eca735078f17c",
   }
}

I want to fetch the documents from the same index from the given 2 types with "scan-id":"n_d4dbba7309a94503b25eca735078f17c"
I tried this,
{
  "size": 100,
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_type": {
                    "value": "tag-alexa-top1k-using-csp-tld-domain"
                  }
                }
              },
              {
                "term": {
                  "scan-id": {
                    "value": "n_d4dbba7309a94503b25eca735078f17c"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_type": {
                    "value": "unique-fp-domains"
                  }
                }
              },
              {
                "term": {
                  "scan-id": {
                    "value": "n_d4dbba7309a94503b25eca735078f17c"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

But it doesn't work.
Comment: can you share some samples(query, documents, expected and actual result).
Comment: Hi, thanks for getting back, I have added sample documents and requirement in the question.
Answer: Elasticsearch is not good in joining different collections of documents, but in your case you might be able to solve your issue with parent-child relationship.
How to query many index types together in an AND fashion?
In case when you have a one-to-many relationship you can model it with parent-child. Let's suppose that type unique-fp-domains is "parent" type and scan-id field is a unique identifier. Let's also suppose that tag-alexa-top1k-using-csp-tld-domain is a "child" and every document of type tag-alexa-top1k-using-csp-tld-domain refers to exactly 1 document in unique-fp-domains.
Then we should create the Elasticsearch mapping in the following way:
PUT /cust_58
{
  "mappings": {
    "unique-fp-domains": {},
    "tag-alexa-top1k-using-csp-tld-domain": {
      "_parent": {
        "type": "unique-fp-domains"
      }
    }
  }
}

And insert the documents like this:
# "parent"
PUT /cust_58/unique-fp-domains/n_d4dbba7309a94503b25eca735078f17c
{
    "mg_timestamp": 1579866709096,
    "violated-directive": "connect-src",
    "fp-hash": "258b3ad1a11aba282f35908662bdc5432d68fd96bf3ca90013dcdd5764331399",
    "time": 1579866709096,
    "scan-id": "n_d4dbba7309a94503b25eca735078f17c",
    "blocked-uri": "play.sundaysky.com"
}

# "child"
POST /cust_58/tag-alexa-top1k-using-csp-tld-domain?parent=n_d4dbba7309a94503b25eca735078f17c
{
    "tagged-domain": "sundaysky.com",
    "tag-guidance": "FP",
    "additional-tag-metadata-isbase64-encoded": "eyJ0b3RhbC1hbGV4YS1tYXRjaGVzIjoyMzh9",
    "project-id": 2,
    "fp-hash": "258b3ad1a11aba282f35908662bdc5432d68fd96bf3ca90013dcdd5764331399",
    "scan-id": "n_d4dbba7309a94503b25eca735078f17c"
}

Now we will be able to query for parent objects having any child associated with it == join on parent ID, which is we forced to be scan-id by providing the _id of the document manually.
The query will use has_child and will look like this:
POST /cust_58/unique-fp-domains/_search
{
    "query": {
        "has_child": {
            "type": "tag-alexa-top1k-using-csp-tld-domain",
            "query": {
                "match_all": {}
            },
            "inner_hits": {}
        }
    }
}

Note that we use inner_hits to tell Elasticsearch to retrieve the matched "child" documents.
The output would look like:
    "hits": [
      {
        "_index": "cust_58",
        "_type": "unique-fp-domains",
        "_id": "n_d4dbba7309a94503b25eca735078f17c",
        "_score": 1.0,
        "_source": {
          "mg_timestamp": 1579866709096,
          "violated-directive": "connect-src",
...
        },
        "inner_hits": {
          "tag-alexa-top1k-using-csp-tld-domain": {
            "hits": {
              "total": 1,
              "max_score": 1.0,
              "hits": [
                {
                  "_type": "tag-alexa-top1k-using-csp-tld-domain",
                  "_id": "AW_xhfnnIzWDkoWd1czA",
                  "_score": 1.0,
                  "_routing": "n_d4dbba7309a94503b25eca735078f17c",
                  "_parent": "n_d4dbba7309a94503b25eca735078f17c",
                  "_source": {
                    "tagged-domain": "sundaysky.com",
...
                  }

What are the downsides of using parent-child?

the parent ID should be unique
join is only on parent ID
some performance overhead:

If you care about query performance you should not use this query.

to enable parent-child one will have to change the mappings and reindex the existing data

Other important things to consider
In Elasticsearch 6, types have been removed. The good news are that already starting from Elasticsearch 5 one can use join datatype.
In general, Elasticsearch is not very good to manage relations between objects, but there are few ways to deal with them.
Hope that helps!
Comment: @z3r0 Glad I could help. I think that a good starting point is the [Modeling your data](https://www.elastic.co/guide/en/elasticsearch/guide/master/modeling-your-data.html) chapter of the ES Definitive Guide, it's a bit outdated (based on ES 2) but covers core concepts pretty well. Subsection "Handling relationships" talks about how to model relations in ES (~= the same as I [linked above](https://www.elastic.co/blog/managing-relations-inside-elasticsearch)).
Comment: Thanks for the detailed answer Nikolay. Apologies for replying so late. I agree with your answer. One thing though, the above parent-child data modelling doesn't work for me. But I agree there should have been some different data model for elastic search for my data. Are there any references for data modelling in elastic search. I am used to thinking in relational database terms. Any guidelines will be quite helpful.
Answer: I think this query will figure out your problem;
"query": {
  "bool": {
    "must": [
      {
        "terms": {
          "_type": "tag-alexa-top1k-using-csp-tld-domain"
        }
      },
      {
        "terms": {
          "_type": "unique-fp-domains"
        }
      }
    ],
    "filter": [
      {
        "scan-id": {
          "_type": "n_d4dbba7309a94503b25eca735078f17c"
        }
      }
    ]
  }
}

Answer: "query": {
        "query_string" : {
            "query" : "(_type : unique-fp-domains OR tag-alexa-top1k-using-csp-tld-domain) AND (scan-id : n_d4dbba7309a94503b25eca735078f17c)
            }
    }
Answer: you could use a msearch. This can combine multiple searches. You can find more information about this at their documentation. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html
Comment: Please consider adding an example to your answer.
Comment: How do I perform and condition between the independent results of the requests?


UITableViewCell + standard disclosure indicator + secondary UIButton + HIG violation

Question: I've a simple question but I cannot find a clear answer around the web.
Suppose I have a custom
<code>UITableViewCell
</code>
With the default disclosure detail button that take to a detail view controller.
Is it good to have secondary, custom button that, when tapped, fires another action rather than presenting the detail view controller?
Or it could be an HIG violation?
any suggestion very appreciated.
Answer: Where would you like to put another button? Maybe the simplest thing to do is put the other action in
<code>-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>
Answer: I probably mis-explained.
Here is a raw image. It may help claryfing the question:
Comment: After googling and watching hundreds of iOS common patterns, I come to a conclusion: having an UIButton on a selectable UITableViewCell may not violate any Apple HIG, but it's a very very bad experience for the user.


golang nil pointer assignment with ignored output - (*)(nil)

Question: while going through this tutorial on writing FUSE filesystems in go, I came across this cryptic assignment:
var _ fs.Node = (*Dir)(nil)

Can someone explain the mechanics of this syntax, and how does it fit in the context in which it is declared? As I understand the outcome of the assignment is actually ignored (and what does the right hand expression even result in? a nil Dir pointer?)
Answer: This makes the compiler check if type *Dir fulfills fs.Node interface.
Take a nil pointer, make it a *Dir pointer and assign it to an unnamed variable of interface type fs.Node. Since we never use this variable, we have to make it unnamed.


How to retrieve more than 3000 user details from an Active Directory group using C#?

Question: I have an Active Directory group with more than 3000 members in it. I want to retrieve all those members from that group using the LDAP connection. I tried using the below snippet but it is providing one 1-1499 members from the group. Is there is any other way to achieve the same
<code>LdapConnection connection = new LdapConnection(********);
NetworkCredential cred = new NetworkCredential(********, ********, ********);
connection.Credential = cred;

List<SearchResponse> results = new List<SearchResponse>();
SearchRequest request = new SearchRequest("***********", "(objectClass=group)", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] {"member" });

PageResultRequestControl prc = new PageResultRequestControl(1000);
SearchOptionsControl soc = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);
request.Controls.Add(prc);
request.Controls.Add(soc);

while (true)
{
       SearchResponse response = connection.SendRequest(request) as SearchResponse;

       foreach (DirectoryControl control in response.Controls)
       {
           if (control is PageResultResponseControl)
           {
                prc.Cookie = ((PageResultResponseControl)control).Cookie;
                break;
           }
       }

       foreach (var item in response.Entries[0].Attributes["member"].GetValues(typeof(String)))
       {
            var t = item;
       }

       results.Add(response);
}
</code>
Answer: Appears that you are hitting the MaxValRange limits.
MaxValRange value controls the number of values that are returned for an attribute of an object, independent of how many attributes that object has, or of how many objects were in the search result.
I do not do C# but We have a sample in Java code that may be helpful.


Image border issue

Question: HTML

MMH

Miami Max Hydro

                About
                Contact

                                    <img src=data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMVExIVGBYYFRcVFhcVFxUVFxUYFxUVFRUYHSggGB0lGxUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGBAQFysdHR0rLS0rKy0tLSstKysrKy0tLSsrLS0tLS0tNy0tLS0tNystNysrLS03KystKy0tKysrK//AABEIAJABAAMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAAFAgMEBgcBAAj/xABBEAABAwIDBQUFBgQEBwEAAAABAAIDESEEBTESQVFhcQYTIoGhMpGxwdEHFEJS4fBTYnKSFiOCshckM2PC0vEV/8QAGQEAAwEBAQAAAAAAAAAAAAAAAQIDAAQF/8QAJREAAwEAAQMEAgMBAAAAAAAAAAECESEDEjEEE0FRIjJCYXEF/9oADAMBAAIRAxEAPwDSyEy5t1Ik1TUiuzmXkYJTdUp+qSEg6OtYvPdYrxKTKFgkZjUpwXmrsjqKNlJIGKfuTMh8DuiTiH1KTM6jD0UWW3gB97dO/eNOf1UDaulk12U5MtfZLFATedB51RHtRiSJyK0o0H0VTyWYh4INDttoTuNUX7VzO7522AHBgrS4JpqOqp/EVL8hzCZi/ZF61v7yArblspdG08QqFBUUFq0aPmrzlX/TaOS55/Y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NBod/wAFNxOX92CJNoVFW7FHV3Gt0HMLrihtfTcrTwsEfPkLRTbYLqAX3aJpxuuZXgJXMkka0ujjFZDoAD80l7hu0WVCtFryWEiFtN9TREGTlp4K1NyaJuGhsQ7YZcbyWgkrmNwDHNFdRbqOa565ZTwf/9k= />

Cell2

Cell3

CSS:
body {
    background-image: url(http://weknowyourdreamz.com/images/sea/sea-08.jpg);
    background-size: cover;
    font-family: 'Century Gothic', CenturyGothic, AppleGothic, sans-serif;
    back
}
.header {
    text-align: center;
    padding: 10px;
    background: #D2F0C6;
    overflow: auto;
    position: fixed;
    top: 1px;
    right: 1px;
    left: 1px;
    border: 6px solid #80bc80;
}
.header-inner {
    Margin-top: 10px;

}
.images {
    padding: 20px;
}
.header-inner a {
    text-decoration: none;
    color: #000000;
    font-size: 24px;
    font-weight: bold;
    line-height: 20px;
}
.header-logo {
    font-size: 32px;
    Font-weight: bold;
    line-height: 28px;
}
.header-logo a {
    text-decoration: none;
    color: #000000;
}
.header-nav a {
    text-decoration: none;
    color: #295f6f;
    margin-right: 5px;
    margin-left: 5px;
    line-height: 25px;
    font-weight: bold;
}
.header-nav {
    margin-right: 5px;
    margin-left: 5px;
}
..images {
    padding: 20px 0;
}
.column {
    width: 33%;
    height: 33%;
    font-weight: bold;
    line-height: 30;
    float: left;
    text-align: center;
}
.profile-overlay {
    float: left;
    border: 6px solid #80bc80;
    width: 255px;
    height: 245px;
}

My Issue:
Basically, No matter what I do to get a border around my image, I get
Basically the top border extends behind the header.
I've tried margin-top with no success, it just keeps the picture in the same spot relative to the border while pushing the top of the border down.
line-height won't work either. Even line-height 1 will instantly make the picture match the top border but go away from the bottom and hide under the header.
I do have an idea in mind, doing line-height 1 then doing some command to move the whole border/picture down relative to the body, but I don't know any code that does that.
Comment: You do realize that fixed positioning is used on the header and that the header will always stay fixed and on top, rest of the content will go behind right? The margin needs to be added to the sibling of the header but even then it will go behind once you start scrolling the page.
Comment: `box-model:border-box`
Comment: No no no, I know that, but I can't figure out how to make the top of the border fit tight on top of the image.
Comment: @BOTIrwin: Can't you give your header a fixed height value in pixels?
Comment: @Harry No I tried that. If I do something like height: 200px, it will always have the top of the border start way above the top of the image.
Answer: JSFiddle.
Remove border: 6px solid #80bc80; for .profile-overlay and add it to .column1 img.
.column1 img {
  border: 6px solid #80bc80;
}

Comment: YES THANK OMG =DDD

Image border issue


Sistema de login

Question: Eu fiz um site no qual eu tenho implementado este ficheiro que pertence ao login mas nao me funciona

<? php  include('backoffice/db-config.php') ?>
<? php

$nome = $_POST['nome'];
$password = $_POST['password'];
$db = mysql_query("SELECT * FROM 'users' WHERE nome = '$nome' and password = '$password' ") or die(mysql_error());
$num_row = mysql_num_rows($row);

if($num_row < 1){
    session_start();
    $_Session['nome']=$_POST['nome'];
    $_Session['password']=$_POST['password'];
    echo"tas dentro";
    echo" ";

} else{
    echo"Login falhoe";
    echo" ";

}
?>

nao me da erros simplesmente executa o ultimo echo
Comment: O último `echo`... hmm... você se refere à "*Login falhoe*"?
Comment: o que me aparece no browser é isto

loginsuccessufully()";

} else{
    echo"Login falhoe";
    echo" ";

}
?>
Comment: Para começar, mysql_* não funciona nas versões mais recentes do PHP, você pode usar Mysqli ou PDO
Comment: @braulio_holtz Você sabe qual versão de PHP ele usa? Você sabe se o erro está no driver do banco?
Comment: nao nao sei onde ta  erro, ele nao me executa o codigo
Comment: @coiso Cria um arquivo php com o código <?php phpinfo(); e execute e mande o resultado, php version, algo assim
Answer: 1. Alterar o adaptador do banco de dados (recomendado)
Você deveria usar PDO ou MySQLi ao invés de mysql.
2. Tratamento do conteúdo provido pelo $_POST (recomendado)
Nunca passe variáveis mágicas de requisição ($_POST, $_GET, etc) sem uma higienização adequada. Você está fazendo isso:
[...]

$nome = $_POST['nome'];
$password = $_POST['password'];

[...]

Quando falo de higienização, me refiro ao seu literal significado:

s.f. Ação ou efeito de higienizar.
(Etm. higienizar + ção)

E higienizar, por sua vez:

v.t.d. Fazer com que fique limpo; ficar asseado: higienizar os
  sanitários. Deixar de estar doente; ficar saudável ou higiênico.
(Etm. higiene + izar)

As suas variáveis mágicas de requisição não estão saudáveis porque podem armazenar diversas malícias que podem prejudicar o seu aplicativo num todo; partimos desde injeção SQL até caracteres maliciosos que a sua aplicação não está preparada para lidar, podendo ser espaços ou até alguns mais exóticos.
3. Problema na query
O seguinte fragmento de código não está correto:
[...]

$db = mysql_query("SELECT * FROM 'users' WHERE nome = '$nome' and password = '$password' ") or die(mysql_error());

[...]

O uso de aspas simples em variáveis de banco é incorreto. Ao invés disso, você pode usar os totalmente opcionais "`", ficando dessa forma:
[...]

$db = mysql_query("SELECT * FROM `users` WHERE nome = '$nome' and password = '$password' ") or die(mysql_error());

[...]

4. Problema na condição de registro de sessão
Você tem o seguinte fragmento:
[...]

if($num_row < 1){

[...]

O problema aí está na sua condição. Quer dizer então que se os resultados da sua consulta no banco forem menor que um, ou seja, retornar "0" login válido, você vai registrar uma sessão?
Substituimos, então, pelo seguinte:
[...]

if($num_row == 1) {

[...]

Por que == 1?
Se a quantidade de linhas retornadas for maior que um, significa que temos mais de um resultado – o que não pode ser verdade, porque aí ou temos um problema de query ou dois registros iguais (ou quase) no banco de dados.
Se a quantidade de linhas for igual a um, a margem de erro é quase zero. Portanto, fique com essa opção que é a mais adequada para o seu caso.
Answer: Erros Encontrados:
$db = mysql_query("SELECT * FROM 'users' WHERE nome = '$nome' and password = '$password' ") or die(mysql_error());
$num_row = mysql_num_rows($row);

Você colocou $db na mysql_query e no mysql_num_rows($row), seria então, mysql_num_rows($db).
Código melhorado:

<?php
    include('backoffice/db-config.php')
    $nome      = $_POST['nome'];
    $password  = $_POST['password'];
    $query     = mysql_query("SELECT * FROM 'users' WHERE nome = '{$nome}' and password = '{$password}' limit 1") or die(mysql_error());

    if(mysql_num_rows($query) == 1){
        session_start();
        $_Session['nome']=$_POST['nome'];
        $_Session['password']=$_POST['password'];
        echo "tas dentro";
        echo" ";
    } else{
        echo"Login falhoe";
        echo" ";
    }
?>

Obs: Não é o código ideal para a solução, porque, contem mysql_* que é depreciado( utilize PDO ou Mysqli), a utilização de $_POST que deveria ser utilizado filter_input.
Comment: esse codigo ajudou mas agora aparece me este erro

Parse error: syntax error, unexpected T_VARIABLE in C:\wamp\www\pap_site\backoffice\loginmanage.php on line 12
Comment: E qual seria o código da linha 12?
Comment: Qual a linha 12? eu fiz outra edição ...
Comment: ja me aparece outro erro, agora o erro é este Warning: include(backoffice/db-config.php) [function.include]: failed to open stream: No such file or directory in C:\wamp\www\pap_site\backoffice\loginmanage.php on line 11

e a linha 11 é esta     include('backoffice/db-config.php') ;
Comment: @coiso, ele não ta achando o db-config.php na pasta backoffice !!!
Comment: Esse erro indica que o arquivo backoffice/db-config.php não existe, cheque sua existência acessando isso: localhost/backoffice/db-config.php.
Comment: @perdeu mas ele adicionou, tanto que ao perguntado o código da linha 11 ele respondeu: include('backoffice/db-config.php');
Answer: Não use aspas simples em nomes de tabelas, apenas em valores.
$db = mysql_query("SELECT * FROM 'users' WHERE nome = '$nome' and password = '$password' ") or die(mysql_error());
$num_row = mysql_num_rows($row);

Passe a variavel $db para mysql_num_rows() no lugar de $row
$db = mysql_query("SELECT * FROM users WHERE nome = '$nome' and password = '$password' ") or die(mysql_error());
$num_row = mysql_num_rows($db);

Sistema de login


Help proving that two topologies generated by two different metrics are the same

Question: Let $d_2$ and $d_{\infty}$ be metrics on $\mathbb{R^3}$.
Hence:
$$d_2((x_1,y_1,z_1),(x_2,y_2,z_2))=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2+(z_1-z_2)^2}$$
$$d_{\infty}((x_1,y_1,z_1),(x_2,y_2,z_2))=max(|x_1-x_2|,|y_1-y_2)|,|z_1-z_2|)$$
So i need to prove that the toplogies: $\mathcal{T}_2 ,\mathcal{T}_{\infty}$ are the same(both are generated by the obvious metric).
So since i have to prove they are the same, it means that  they have the same base.
They are generated by metric so their base is an open ball.
So if they are the same, both metrices have to have identical open balls.
AM i on the right track, or am i wrong?
Comment: No, they don't have to have the same open balls. Rather, show that for each metric, an open ball in that metric is still an open _set_ in the other.
Comment: Generally saying, these metrics are generated by norms $\|\cdot\|_2$ and $\|\cdot\|_{\infty}$. In finite dimensional space all the norms are equivalent, which means they generate the same topology.
Comment: They don't have the same open balls. They have the same open $sets$........ Show that every open $d_2$-ball is a union of open $d_{\infty}$ balls and vice-versa.......   It suffices to show that when  $p\in \Bbb R^3$ and $r>0$   there exists $s>0$ such that $B_{d_{\infty}}(p,s)\subset B_{d_2}(p,r)$, and vice-versa.......  An open $d_2$-ball $B$ about $p$ is spherical, and contains  an open cubical region   $C$ centered at $p,$ which is an open $d_{\infty}$-ball. And $C$ contains an open spherical region $D$ centered at $p$, which is an open $d_2$-ball.
Answer: Let $U$ be open in $d_2$. Let $(x_1,x_2,x_3):=x \in U$, then there exists some open ball $(B,r)$ that contains $x$ and is properly contained in $U$. But as soon as this happens, we also have that there is a neighborhood $B_\infty$ given by $max(|x_1-y_1|,|x_2-y_2|,|x_3-y_3|)<r$.
This can be seen since $|(x_i-y_i)| <r$, since the sum of their squares is less than $r^2$. But then $B_\infty) \subset (B,r) \subset U$. Hence, $U$ is open in $d_\infty$ as well, and the other direction is similar


Path (URL) to call custom module function

Question: I am developing a custom module and I need an URL that would trigger an action when called.
The purpose is for an external server to call this address passing some variables through $_REQUEST['message'], and then return a STRING with the success/error string. So the URL in question is only supposed to be called by a machine.
I now have a PHP file in the root that does the job, but I'd like to integrate it to the Drupal way through this custom module.... Is there a way to do this?
Thank you
Answer: The best way to do this is to build a custom module and implement the hook hook_menu().
You'll need to implement:

a .info file with metadata about your
module
a .module file containing
hook_menu() and your callback

foo.module should look like this:
function foo_menu() {
  $items = array();
  $items['foo/myurl'] = array( // change 'foo/myurl' to the url you want
    'title' => 'Callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  return $items;
}

function custom_callback () {
  // Parse $_REQUEST parameters
  return 'success';
}

Comment: how can I make the `custom_callback()` function to `echo` some when visited from the browser? It should return a string (or an XML)...
Comment: Using echo() :)
Comment: maybe you can guide me on this one? http://drupal.stackexchange.com/q/6667/1146 (continuation of this one, but I'd rather make it a Question than a comment). Thanks


Show that $f$ is measurable on $(a,b)$

Question: Let $f,F : (a,b)\to \mathbb{R}$ such that $F$ is differentiable on $(a,b)$ and $F'(x) =f(x)$ for each $x \in (a,b)$. Show that $f$ is measurable on $(a,b)$.
Hint : Show first that $\forall x \in (a,b) : f(x) = \lim\limits_{n \to \infty} n[F(x+\frac{1}{n}) - F(x)]$.
I have already proved the hint ... How to proceed please?
Answer: Note that each function $x\mapsto n(F(x + 1/n) - F(x))$ is measurable and that the limit of a sequence of measurable functions is measurable.
Comment: That is correct.
Comment: We can say this because :
Since F is differentiable then it is continuous and so it is measurable. Isn't it?

Show that $f$ is measurable on $(a,b)$