Como passar parâmetro para Index de outro Controller

Question: Tenho que passar um parâmetro (ID) para o index de um controler,
Tentei usar o ActionLink mas não funcionou.
View:

                @Html.DisplayNameFor(model => model.Tag)

                @Html.DisplayNameFor(model => model.Fluido)

                @Html.DisplayNameFor(model => model.Vedacao)

                @Html.DisplayNameFor(model => model.Criticidade)

                @Html.DisplayNameFor(model => model.Mtbf)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Tag)

            @Html.DisplayFor(modelItem => item.Fluido)

            @Html.DisplayFor(modelItem => item.Vedacao)

            @Html.DisplayFor(modelItem => item.Criticidade)

            @Html.DisplayFor(modelItem => item.Mtbf)

            @Html.ActionLink("Detalhes", "Index", "RelatorioRa", new { tagId = item.TagID })

}

Controler RelatorioRa que ira receber o ID:
 public async Task<ActionResult> Index(int? tagId)
    {
        var relatorioRaModels = db.RelatorioRaModels.Include(r => r.RelatorioTag);

        if (tagId.HasValue)
        {
            //realiza o filtro para a tag selecionada
            relatorioRaModels = relatorioRaModels.Where(a => a.TagID == tagId);
        }

        return View(await relatorioRaModels.ToListAsync());
    }

Comment: Amigo, o exemplo que lhe respondi na outra pergunta mostra como fazer isso é o `@Html.ActionLink(linkText: item.Tag, actionName: "Index", controllerName: "RelatoriosRas", routeValues: new { tagId = item.TagID }, htmlAttributes: new { })`
Answer: Nessa sua situação, bastaria você acrescentar mais um parâmetro no seu ActionLink que seria referente ao htmlAttributes
@Html.ActionLink("Detalhes", "Index", "RelatorioRa", new { tagId = item.TagID }, null)

Se você passar somente três parâmetros, ele entende que o seu new { tagId = item.TagID } é o htmlAttributes e que o RelatorioRa é o routeValues.
Comment: Amigo pode me explicar porque usar assim: `@Html.ActionLink("Detalhes", "Index", "RelatorioRa", new { tagId = item.TagID })` não funciona? e do jeito que vc passou funciona?
Comment: É por causa da assinatura do `ActionLink` https://msdn.microsoft.com/pt-br/library/system.web.mvc.html.linkextensions.actionlink(v=vs.118).aspx
Comment: Cara, to te devendo uma cerveja, rs obrigado em valeu
Comment: bora beber então


Regarding expansion of MACROS during preprocessing

Question: I have an existing MACRO which takes two entities.
ROOT_MACRO(x,y)
I want to define 2 new macros like this :- MACRO_1(x,y)= ROOT_MACRO(z,x__y)
Here I want z to be evaluated in preprocessing using MACRO_2
For ex. my cpp file would look something like this :-
MACRO_2(z)
MACRO_1(x,y)==> Should expand to ROOT_MACRO(z,x__y)
//Later on in the .cpp file,
MACRO_2(p)
MACRO_1(x,y)==> Should expand here to ROOT_MACRO(p,x__y)
Is there a way to achieve this ? I hope the question is clear.
Comment: I am almost sure that there is a way to achieve what you want to do without using macros.
Comment: Macros are evaluated by the preprocessor, not the compiler. So they cannot be evaluated at "compile-time". And if you use C++, other constructs than macros might be more suitable. Pick a language.
Comment: I **have to** use macros since `ROOT_MACRO` isn't mine. Its a third party framework. I want a slight modification on top of it.
@Olaf :- True !! i've edited the question appropriately.
Answer: If I understand correctly, you want something like the following:
#define MACRO_2(p) #define MACRO_2_DEFINED p
#define MACRO_1(x,y) ROOT_MACRO(MACRO_2_DEFINED,x__y)

But cpp (c pre-processor) works in one-pass, and you can't define a define. What you could do if you are able to change the build system is use m4 before sending the code to cpp. Here is an example using m4:
#define ROOT_MACRO(x,y) This is the root macro with arguments x and y
define(`MACRO_2',`#undef MACRO_2_DEFINED
#define MACRO_2_DEFINED $1')
define(`MACRO_1', `ROOT_MACRO(MACRO_2_DEFINED, $1__$2)')

MACRO_2(z)
MACRO_1(x,y)

MACRO_2(p)
MACRO_1(x,y)

Then running m4 on the file above (e.g. $m4 foo.c) yields:
#define ROOT_MACRO(x,y) This is the root macro with arguments x and y

#undef MACRO_2_DEFINED
#define MACRO_2_DEFINED z
ROOT_MACRO(MACRO_2_DEFINED, x__y)

#undef MACRO_2_DEFINED
#define MACRO_2_DEFINED p
ROOT_MACRO(MACRO_2_DEFINED, x__y)

And running cpp on the code above (e.g. $m4 foo.c | cpp -) yields:
# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "<stdin>"

This is the root macro with arguments z and x__y

This is the root macro with arguments p and x__y

Answer: @davir is right, you can't #define a define. The best you can get with the standard preprocesor is something like this:
#define  M1(x,y) MACRO_BASE(M2, x##__##y)

...
#define M2 z
M1(x,y) //# expands to MACRO_BASE(z,x__y)

...//later
#define M2 p
M1(x,y) //# expands to MACRO_BASE(p,x__y)

If z and p are values of a fixed type, you could get away with something awful like:
#define M2(v) thetype_t current_m2__ = v
#define M1(x,y) MACRO_BASE(current_m2__, x##__##y)

Which could work as long as  you always have one and only one call to M2 in the same scope as M1.
But why not just combine the M2 and M1 calls like #define M(v,x,y) MACRO_BASE(v,x##__##y)?


Can non-voice instruments produce the sounds of vocal lyrics?

Question: How can an instrument like the guitar or the piano be made to sound as though it's speaking real words, without any use of a human voice?
Comment: What has your research shown you so far? Why wasn't it satisfactory?
Comment: Probably, reading about the vocoder might give you some ideas!
Comment: Would talkbox count? It doesn't use the actual voice and only half of vocal tract.
Comment: Will recording parrots do?
Comment: I took "object instrument" to mean "not a person".  Editing that out makes talkbox a valid answer, but I don't think that was the asker's intention.
Comment: @toporeinstatemonica I've never read or heard the phrase before and also have always interpreted the word "instrument" on its own to not include voice unless specifically included. "Are there any instruments that can produce speech or singing sounds?" Would be clear to me as not including the voice.
Comment: The examples in the second sentence seem to make it clear that "object instrument" means an instrument that isn't the human voice. What else needs clarifying here?
Comment: @ToddWilcox My guess is that OP's first language isn't English. FWIW I also generally interpret 'instrument' as not including the human voice, but then it's also common to read/hear phrases like "the human voice is the most beautiful/flexible instrument", so maybe OP felt they needed to clarify...
Answer: Speaking piano
The idea behind synthesizing speech from a mechanical instrument is that since speech sounds are (highly complex) combinations of sine waves, and each sine wave represents a pitch, combining instrumental pitches can mimic those same sounds.
This was demonstrated with a piano by Peter Ablinger in 2009 and can be seen in the below video.

There is a very nice video by Andreas Raduege explaining in more detail how this process works. It relates human speech to computer generated speech to piano-generated speech by using Fourier transforms to analyze sound patterns.

(See also: What modern innovations have been/are being made for the piano?
In theory, this technique could be applied to any instrument, except for two factors:

comparatively limited pitch range on many instruments;
limited- or inability to produce sufficient multiple, simultaneous pitches (this could be overcome, perhaps, by multitracking).
Answer: There's a distinction between vocal-like and actual words, and it's tough to get to the latter state.
I played a recording of Clara Rockmore, the first virtuoso of the theremin, and my wife asked me "the woman singing, why is she so sad?" Similarly, in the intro to David Lee Roth's "Yankee Rose", Steve Vai uses a guitar and wah pedal to "converse" with Dave. But there wasn't the articulation to sound like actual words.
There is a way to get closer. There's a device called the Talk Box, which is a small amplifier and a tube. The tube goes in your mouth, and you articulate the sounds. The classic uses I can think of are from steel guitarist Pete Drake's "Forever", Peter Frampton's "Do You Feel Like I Do?" from Frampton Comes Alive, and Roger Troutman on many tracks, including Tupac's "California Love". Listen to them and see if that's close enough.
Answer:
How to emit actual lyrics without any human voice, only using an object instrument ?

A tool that can create speech sounds without any human voice input is called a speech synthesizer. An example of a speech synthesizer oriented towards musical performance is Yamaha's Vocaloid software. An online search will find many examples of vocal 'performances' rendered with this software (you'll quickly meet Hatsune Miku...)

Like make the guitar or the piano speaking real words, without any use of a human voice ?

A piano and guitar aren't optimal tools to generate realistic human voice - what we can do is to use the piano or guitar as part of a process that creates a sound that has some of the characteristics of the human voice. Typically, some kind of filtering is used to shape the sound's frequency response into formants that simulate the resonances of the human vocal tract.
It is possible to use a formant filter without involving any actual human performance - e.g. it's possible to buy a pedal dedicated to the purpose:

Other techniques for projecting formants onto instrumental sounds include the talkbox, and vocoder - but in these cases, a real human is involved.


Why is my dynamically-generated oval becoming a square?

Question: Thought i had everything looking ok.
https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html

function doit() {
 drawOval(100, 150, 90, 90);
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.left = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }
<input type="button" onClick="doit()" value="Do it">

Any ideas?
Comment: That Oracle link is for Java which is different from JavaScript.
Comment: What part of your code do think think makes it oval? By default DIVs are rectangles.
Answer: I don't see anything in your styles that would result in an oval. You need border-radius, probably different for opposing corners:

function doit() {
 drawOval(10, 65, 90, 90);
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.left = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.style.borderRadius = '50px 80px';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }
<input type="button" onClick="doit()" value="Do it">
Comment: Is there a relationship between the height/width input values and the values you selected for `borderRadius`?  I'm unfamiliar with how this property works.  I guess I'm asking, why `50px 80px`?
Comment: Really I've created an ellipse instead of an oval. I just needed values greater than half the respective dimensions. An oval out of a square with 50% radius becomes a circle, so 45px would've yielded that.
Answer: Just apply border-radius at 50%, so all borders will be the same.

function doit() {
 drawOval(100, 150, 90, 90);
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.left = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   // This will do the trick
   newdiv.style.borderRadius = '50%';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }
<input type="button" onClick="doit()" value="Do it">
Answer: First of all,  you are mixing java and javascript. both are different programming languages. if you want to draw oval you can just update your code following way:

function doit() {
 drawOval(160,80,50);
 myOval = document.getElementById("newdiv");
}

function drawOval(width, height, radius) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.style.borderRadius = radius+"%"
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }
<input type="button" onClick="doit()" value="Do it">
Comment: Thank you for identifying the mixing of java language types and for suggesting the correct code
Answer: You have to have your width twice the size of height for a better result (horizontal one).
Then, the oval shape is created with the CSS border-radius property. So to apply that in JavaScript you have to use it as,
newdiv.style.borderRadius = "50%";
You can try the same thing as width/height
Try the code snippet below. Adjust the values and get your own oval shape.

function doit() {
 drawOval("90", "100", "100", "50");
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.borderRadius = "50%";
   newdiv.style.left  = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }
<input type="button" onClick="doit()" value="Do it">


UC Node Checkout for pay to publish user content?

Question: Is there a way to use this module for a pay to publish set up, like in classifieds where user adds content and then pays to publish it in D7?
Generally speaking that is....I like many others having been paying for a module but the person who created it has disappeared now and it is first time ever I've paid for something re drupal. Normally I study up on anything open source- which just goes to show there are no shortcuts in this world.
Answer: Try Pay-per-node
This module allows creation of a number of nodes of chosen type for some users. It temporarily overrides the node creation permissions and keeps track of the number of nodes the user can create.
It can be used as standalone module or as an e-commerce plug-in. In the second case paypernode can be integrated with Ubercart, providing a new "product feature" which will allow, upon product purchase, to create a number of nodes.
Answer: I did this:
eventually didn't need pay per node and managed to get uc_node_checkout to work
for allowing anon to publish a node of type Job Advert which lands in the cart, requires checkout and is only published on payment complete by a rule using exec custom php
using the code from #19 here https://drupal.org/node/376384
and
http://drupaleasy.com/blogs/ultimike/2009/03/event-registration-ubercart
set Create Job Advert to authenticated user role (not anon) to force login before purchase


What is this type of notehead called?

Question: I was looking through some sheet music when I came across a notehead that looked very odd. It looks like a whole note with two lines on both its sides. Here is an image of the notehead:

What is this type of notehead called, and what is its duration?
Comment: Xilpex,  I thoroughly applaud your interest in learning everything music, but please: go to https://www.dolmetsch.com/musicalsymbols.htm .  Read it. Study it.  Download it.   don't subject this site to another couple hundred "what is this symbol" question!
Comment: @CarlWitthoft Seriously.. and the argument that SO wants to get its own answers to the top of Google results is ridiculous in this case. The site you linked is a *far* better resource for learning these symbols than this site could ever hope to be. There's simply nothing to discuss—the symbols mean what they mean. A simple reference is all a person ought to need.
Answer: This is called a double whole note or breve.
Whereas a whole note is equivalent in duration to four quarter notes, a double whole note is equivalent to eight quarter notes.
We see it often in transcriptions of older music, where the half note is used as the beat value instead of the quarter note. Consider, for instance, this example from Palestrina; also make sure to check out the breve rest!

Note that some modern notation systems only write one bar on either side of the note, but it's still a double whole note.
Answer: Called a breve, it's twice as long as a semibreve - no surprise there! The semibreve is the usual full bar note these days, worth four crotchets.
The surprise is that the word 'breve' actually means short, which makes one wonder what long notes were like in the days of yore.
Comment: The breve was a half or a third (depending on the rhythmic mode) of a longa; see https://en.wikipedia.org/wiki/Longa_(music).  There has been a sort of 'inflation' over the centuries, as note values came to represent longer and longer notes, and so composers had to use shorter and shorter note values to achieve the same effect.  See https://music.stackexchange.com/questions/40487/
Answer: It's a double whole note, aka breve, and lasts twice as long as a whole note. Eg. in 4/4 it'd count for 2 measures - 8 quarter notes.

What is this type of notehead called?


Nginx to serve last page proxied when no backend available

Question: Imagine we have a site made of nginx as a frontend, and apache (with php or whatever) as a backend. The idea is that nginx will serve static while proxy requests to *.php files to backend. Easy to implement and no-brain-needed config, isn't it?
Now imagine we have bad-behaviour backend. It uses some unstable modules, it used to produce pages for seconds and we're not sure if the page be rendered at all. Weird, but still possible, right? Legacy code and so on. By the way, the backend may be on different machine (yes, legacy: old OS, old software, "don't even touch it!" etc.)
Now we'd like to "protect" ourself in a case the backend won't answer. It would be great to serve page as we served it last successful time when we got no page or get 5xx error. To say in other words, if backend returned 200 code and the page content, then we serve it. If we got timeout or we got 5xx code from backend, we serve the page for the same URI but cached one. This will give us some time to fix backend while users will see at least something.
Nginx is a nice piece of software. I found proxy_cache_use_stale directive and also some others but I'm afraid what will be the version that will be served if backend fails.
I can also imagine some http balancer (nginx as an example) that will check the backend status and stop use it whatever happens. The second backend then maybe server full of static pages that mimics the original site (maybe even without some element, like 'login' link). If so, how should I wisely update the 'mimics' server over time?
What approach may be better? What would you choose?
Comment: have you considered cloudflare?
Comment: I considered Cloudflare but their datacenters are not geo well placed. And they add their note (page is cached) into the stale page content, not something i'd like to see.
Answer: CloudFlare have 100+ data centers all over the world, they're very well placed and very well peered, and you can't beat the price of their free tier. Yes CloudFlare does show a warning if the main site is offline, but maybe their paid business plans can suppress that warning - you'd have to ask them. If you don't want the warning your only option is Nginx or similar caching.
They key parts of the nginx configuration would be these, in your location block. There's a lot more about them in this excellent article. Basically it says only cache 200 (success) responses and only for 1s (increase that if you can), use the stale page while you're updating, and don't queue requests for pages already requested.
<code>proxy_cache_lock on;
proxy_cache_valid 200 1s;
proxy_cache_use_stale updating;
</code>
If you have anonymous users page caching will reduce the load on your server, even if you only cache pages for 1 second, though longer is better. This reduced load may make the application more reliable.
Of course you should fix the badly behaved application.


Is Hilbert space a Normed Space or a Inner Product Space? Or it have to be both at the same time?

Question: This can sound like something trivial, but I keep seeing both of these being used towards the Hilbert Space, to the point that I am confused and not sure anymore. Even Wikipedia says that it's
"a real or complex inner product space that is also a complete metric space with respect to the distance function induced by the inner product",
So, we don't need a norm, we just use an inner product to induce a metric, right? Or we do need the norm?  Can we have an inner product that gives us a metric, without inducing a norm?
In some other place in the very same article, Hilbert Space is called a Normed Space, even though it's not clear from its definition.

My problem is, that Normed Vector Spaces with an Inner Product are, in fact, quite rare. In general, you often have Normed Spaces, where inner product doesn't induce the norm.
So, how is this with Hilbert Space?
Do an Inner Product Space with a metric must to be a Normed Space? If yes, then I can understand why it's called a Normed Space, but if there can be a Inner Product Space, with a metric coming from inner product, that doesn't induce a norm somewhere in between (is it possible?), then why people call Hilbert Space a Normed Space?

I would be glad, if someone could explain this and bring insight onto my confusion :-)
Comment: The inner product naturally induces a norm, given by $\Vert v \Vert=\sqrt{\langle v, v \rangle }$. That this is in fact a norm can be seen via the Cauchy-Schwarz inequality. So whenever one says "Hilbert space", we usually carry the whole bundle of information: the vector space structure, the inner product, the natural norm (as above), the metric from the norm, the topology from said metric etc (unless explicitly said that we are considering another topology/metric/norm etc on the underlying set).
Comment: the norm is $\|v\|:= \langle v, v \rangle ^{1/2}$
Comment: Thank you. Now I see that I also confused myself, to the point that I even formulated question in a different way that for what I wanted to ask. I started from "Normed Space" and concluded that it doesn't have to be an Inner Product Space, while it's an other way around. Thank you for clarification!
Answer: An Hilbert spaces is a Complete Inner Product Space and it is also a Banach Space because from the Inner product we can canonically defines the norm:
$||x||=\sqrt{\langle x,x\rangle}$.
But note that a vector space can be normed but not equipped with an inner product ( as you  can see here). So  we can have a complete normed space ( a Banach space) that is not an Hilbert space.
Intuitively: a normed space is a vector space in which the vectors have a length, in an inner product space  we have also ''angle'' between vectors, and if any Cauchy sequence of vectors converge, than this space is complete and is called an Hilbert space.
Comment: A Hilbert space is normed, with a "natural" norm induced by the inner product.
Comment: So is the Hilbert space must be normed vector space?


How to migrate D6 node reference to D7 organic group membership?

Question: I have created migrations for most of my D6 site to a new D7 site.  In the D6 site I have users with profile nodes.  Those profile nodes are linked to another type of node via node reference.  In D7 the other node will be an organic group.
I would like to be able to transfer the node reference relationship in D6 to organic group membership in D7.  Has anyone done this?
Thanks in advance for any help given.
Answer: I ended up using the advanced method as described in the semi-official documentation (https://drupal.org/node/2023273).  It all came down to modifying the query to get the nid and new group nid.
<code>class MemberCompanyMembershipMigration extends DrupalMigration {
    /**
     * Construct a migration.
     *
     * @param array $args
     *   Constructor arguments passed at migration-registration time.
     */
    public function __construct($args) {

        parent::__construct($args);

        // Set the fields we want; document in the UI.

        $this->sourceFields += array(
                'nid' => t('Group node ID.'),
                'is_active' => t('User status in the group.'),
                'is_admin' => t('Group admin or not.'),
                'uid' => t('User ID.'),
        );
        $this->sourceOptions['map_joinable'] = FALSE;
        // Set the query as the migration source.
        $this->source = new MigrateSourceSQL(
                $this->query(), $this->sourceFields, NULL, $this->sourceOptions
        );
        // Map source rows to destination rows with uid+gid.
        $this->map = new MigrateSQLMap($this->machineName,
                array(
                        'field_contact_member_company_nid' => array(
                                'type' => 'int',
                                'not null' => TRUE,
                                'description' => 'ID of the group.',
                        ),
                        'uid' => array(
                                'type' => 'int',
                                'not null' => TRUE,
                                'description' => 'ID of the user.',
                        ),
                ),
                MigrateDestinationOGMembership::getKeySchema()
        );
        // Destination is group membership.
        $this->destination = new MigrateDestinationOGMembership();
        // Field mappings.
        $this->addFieldMapping('group_type')
        ->defaultValue('node');
        $this->addFieldMapping('entity_type')
        ->defaultValue('user');
        // Let the user migration map the uids.
        $this->addFieldMapping('etid', 'uid')
        ->sourceMigration('ClickUser');
        $this->addFieldMapping('state', 'is_active');
        $this->addFieldMapping('is_admin', 'is_admin');
        // Group migration maps the gid via the OG Node migration.
        $this->addFieldMapping('gid', 'field_contact_member_company_nid')
        ->sourceMigration('MemberCompany');
        // Minimal source config means we just set a default
        // instead of looking for roles to map.
        $this->addFieldMapping('group_roles')
        ->defaultValue(array(OG_ADMINISTRATOR_ROLE));
        // Accept defaults for these destination fields.
        $no_input = array(
                'created',
        );
        $this->addUnmigratedDestinations($no_input, t('Do Not Migrate'));
    }
    /**
     * Query for the source group data.
     *
     * @return QueryConditionInterface
     *   Provides a connection and query for getting OGMembership records.
     */
    protected function query() {
        $query = Database::getConnection('click2', $this->sourceConnection)
        ->select('content_type_contact_content','p')
        ->fields('p', array('field_contact_member_company_nid'));
        $query->join('node','n','n.vid = p.vid');
        $query->addField('n', 'uid');
        $query->isNotNull('field_contact_member_company_nid');
        return $query;
    }
    public function prepareRow($row) {
        if (parent::prepareRow($row) === FALSE) {
            return FALSE;
        }
    }
}
</code>


Pandas Merge two tables with the second tables' one column transposed

Question: Table 1
df1 = pd.DataFrame({'df1_id':['1','2','3'],'col1':["a","b","c"],'col2':["d","e","f"]})

Table 2
df2 = pd.DataFrame({'df1_id':['1','2','1','1'],'date':['01-05-2021','03-05-2021','05-05-2021','03-05-2021'],'data':[12,13,16,9],'test':['g','h','j','i'],'test2':['k','l','m','n']})

Result Table

Brief Explanation on how the Result table needs to be created:

I have two data frames and I want to merge them based on a df_id. But the date column from second table should be transposed into the resultant table.

The date columns for the result table will be a range between the min date and max date from the second table

The column values for the dates in the result table will be from the data column of the second table.

Also the test column from the second table will only take its value of the latest date for the result table

I hope this is clear. Any suggestion or help regarding this will be greatly appreciated.
I have tried using pivot on the second table and then trying to merge the pivoted second table df1 but its not working. I do not know how to get only one row for the latest value of test.
Note: I am trying to solve this problem using vectorization and do not want to serially parse through each row
Answer: Here is the solution for the question:

I first sort df2 based of df1_id and date to ensure that table entries are in order.

Then I drop duplicates based on df_id and select the last row to ensure I have the latest values for test and test2

Then I pivot df2 to get the corresponding date as column and data as its value

Then I merge the table with df2_pivoted to combine the latest values of test and test2

Then I merge with df1 to get the resultant table

df1 = pd.DataFrame({'df1_id':['1','2','3'],'col1':["a","b","c"],'col2':["d","e","f"]})
df2 = pd.DataFrame({'df1_id':['1','2','1','1'],'date':['01-05-2021','03-05-2021','05-05-2021','03-05-2021'],'data':[12,13,16,9],'test':['g','h','j','i'],'test2':['k','l','m','n']})

df2=df2.sort_values(by=['df1_id','date'])
df2_latest_vals = df2.drop_duplicates(subset=['df1_id'],keep='last')

df2_pivoted = df2.pivot_table(index=['df1_id'],columns=['date'],values=['data'])
df2_pivoted = df2_pivoted.droplevel(0,axis=1).reset_index()
df2_pivoted = pd.merge(df2_pivoted,df2_latest_vals,on='df1_id')
df2_pivoted = df2_pivoted.drop(columns=['date','data'])

result = pd.merge(df1,df2_pivoted,on='df1_id',how='left')
result

Note: I have not been able to figure out how to get the entire date range between 01-05-2021 and 05-05-2021 and show the empty values as NaN. If anyone can help please edit the answer
Answer: You need to pivot your df2 into two separate table as we need data and test values and then merge both resulting pivot table with df1
df1 = pd.DataFrame({'df1_id':['1','2','3'],'col1':["a","b","c"],'col2':["d","e","f"]})
df2 = pd.DataFrame({'df1_id':['1','2','1','1'],'date':['01-05-2021','03-05-2021','03-05-2021','05-05-2021'],'data':[12,13,9,16],'test':['g','h','i','j']})

test_piv = df2.pivot(index=['df1_id'],columns=['date'],values=['test'])
data_piv = df2.pivot(index=['df1_id'],columns=['date'],values=['data'])

max_test = test_piv['test'].ffill(axis=1).iloc[:,-1].rename('test')
final = df1.merge(data_piv['data'],left_on=df1.df1_id, right_index=True, how='left')
final = final.merge(max_test,left_on=df1.df1_id, right_index=True, how='left')

and hence your resulting final dataframe as below
|    |   df1_id | col1   | col2   |   01-05-2021 |   03-05-2021 |   05-05-2021 | test   |
|---:|---------:|:-------|:-------|-------------:|-------------:|-------------:|:-------|
|  0 |        1 | a      | d      |           12 |            9 |           16 | j      |
|  1 |        2 | b      | e      |          nan |           13 |          nan | h      |
|  2 |        3 | c      | f      |          nan |          nan |          nan | nan    |

Comment: Thanks, but how to get the dates between 01-05-2921, 05-05-2021 and show the values as NaN.
Comment: Also if you have multiple columns in table2 - ```test1```,```test2```,```test3```..... It would get very cumbersome do do pivots for each column. I have edited the question to incorporate this complexity
Comment: I have posted an answer myself. I have still not able to figure out how to get the entire date range. Lets discuss if yours or my answer is better suited to the question. Then I will mark that one as the answer


How to put an image for the bottom of the page

Question: I'm trying to put an image for the bottom of my page. i tried to put it by using android:gravity="bottom" but, my image did not align to the bottom of the page.
Here is my XML,
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/login_land_layout_margin"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/logo"
                android:src="@drawable/ic_logo" />

            <EditText
                android:id="@+id/codeEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:ems="10"
                android:hint="@string/code"
                android:textColorHint="#FFFFFF"
                android:inputType="textPassword" >

                <requestFocus />
            </EditText>

            <EditText
                android:id="@+id/nameEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:ems="10"
                android:hint="@string/name"
                android:textColorHint="#FFFFFF"
                android:inputType="textPersonName" />

            <EditText
                android:id="@+id/emailEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:ems="10"
                android:hint="@string/email"
                android:textColorHint="#FFFFFF"
                android:inputType="textEmailAddress" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/login_land_margin_both"
                android:layout_marginRight="@dimen/login_land_margin_both"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/loginBtn"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="@dimen/login_Land_margin_top"
                    android:background="#0f4b9b"
                    android:text="@string/login"
                    android:textColor="@color/LoginButtonColor" />

            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <ImageView
            android:id="@+id/poweredBy"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/poweredby"
            android:gravity="bottom"
            android:scaleType="fitXY"

            />
    </LinearLayout>

</RelativeLayout>

Here is the view of my image.

I need to add the powered by image for the bottom of the page.
Comment: On your ScrollView change height to fill parent android:layout_height="fill_parent"
Comment: simple use align parent bottom in your layout in which u have placed the imageview...u can use it directly in imageview too..by removing the linear layout
Comment: yup like Neha said you can use align parent bottom, i think it is more easy to you use RelativeLayout if you just make a layout with login page inside
Comment: Neha , Removed the linear layout.and used android:layout_alignParentBottom="true" nothing changed.
Answer: your code is right so dont worry about it.
Just add one line to your scrollView.
android:fillViewport="true"

thats it, you will get result you want
Comment: Wow! What a quick answer . Thank you so much. Working perfectly.
Answer: You have placed the imageview widget inside the Linearlayout. Please remove the Linearlayout and only use the ImageView Widget. Use the following code for placing the imageview at the bottom of the screen.
<ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/poweredby"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:scaleType="fitXY" />

Comment: Added android:fillViewport="true" for scroll view. Now working as expected.
Answer: Use Relative layout that fills the whole screen you should be able to use android:layout_alignParentBottom to move the Image to the bottom of the screen.
Answer: No need to use that linear layout remove that
<ImageView
            android:id="@+id/poweredBy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/poweredby"
            android:layout_alignParentBottom="true"
            android:scaleType="center"

            />

To your scrollview add this android:fillViewport="true"
Comment: removed the linear layout. Problem is still there.
Comment: Added android:fillViewport="true" for scroll view. Now working as expected.
Answer: You can do 2 things.
1.) Make a Linear Layout and set on of the properties of your ImageView as
 android:layout_below="@+id/LogInButton"

and set some padding on top in this LinearLayout which is holding this image.
2.) Use footer

See this tutorial on how to set footer
http://www.javacodegeeks.com/2013/10/android-fixed-header-and-footer-with-scrollable-content-layout-example.html
Comment: Added android:fillViewport="true" for scroll view. Now working as expected.


I need a new and improved DFT

Question: The traditional Discrete Fourier Transform (DFT) and its cousin, the FFT, produce bins that are spaced equally. In other words, you get something like the first 10 hertz in the first bin, 10.1 through 20 in the second, etc. However, I need something a little different. I want the range of frequency covered by each bin to increase geometrically. Suppose I select a multiplier of 1.5. Then we have 0 through 10 in the first bin, I want 11 through 25 in the second bin, 26 through 48 in the third, etc. Is it possible to modify the DFT algorithm to behave in this fashion?
Comment: You are looking for the [Constant Q Transform (CQT)](http://www.elec.qmul.ac.uk/people/anssik/cqt/).
Comment: You can always calculate DFT at the points of interest. Also, [Discrete Wavelet Transform](http://en.wikipedia.org/wiki/Discrete_wavelet_transform) and [Filter Banks](http://en.wikipedia.org/wiki/Filter_bank) come to my mind. Might be worth looking at them.
Comment: Also asked here: http://dsp.stackexchange.com/questions/129/how-can-i-compute-a-log-spaced-power-spectrum
Comment: Poorly worded.  What you want is neither new, nor an improvement in many cases.
Comment: I've learned something new today!
Answer: To quote my dissertation:

A collection of transforms are given the name constant Q and are
  similar to the Fourier transform.
Computation of the discrete Fourier transform can be very efficient
  when employing the use of the fast Fourier transform. However we
  notice that energy of a signal is divided into uniformly sized
  frequency buckets across the spectrum. While in many cases this is
  useful, we notice situations where this uniform distribution is
  sub-optimal. An important example of such a case is observed with the
  analysis of musical frequencies. In Western music, the frequencies
  that make up the musical scales are geometrically spaced. We therefore
  see that the map between frequency bins of the discrete Fourier
  transform and the frequencies of musical scales is insufficient in the
  sense that the bins match poorly. The constant Q transform addresses
  this issue.
The aim of the constant Q is to produce a set of logarithmically
  spaced frequency bins in which the width of the frequency bin is a
  product of the previous. As a result we may produce an identical
  number of bins per musical note across the audible spectrum, thus
  maintaining a constant level of accuracy for each musical note. The
  frequency bins become wider towards the higher frequencies and
  narrower towards the lower frequencies. This spread in the accuracy of
  frequency detection closely imitates the manner in which the
  human-auditory system responds to frequencies.
Additionally, the close matching of notes in western scales renders
  the constant-Q particularly useful in note detection; identifying a
  musical note value rather than an explicit frequency value.
  Furthermore the constant Q simplifies the process of timbre analysis.
  The frequencies of a musical note played by an instrument are often
  comprised of harmonically related partials. The timbre of the
  instrument can be characterised by the ratios of the harmonics. With
  the constant Q transform, the harmonics are equally spaced across the
  bins regardless of the fundamental frequency. This greatly simplifies
  the process of identifying an instrument playing a note anywhere in
  the scale simply by shifting the characterisation across the bins. A
  potential downside to using the constant Q transform is that it
  demands more computation than the Fourier transform.
An efficient algorithm for transforming a discrete Fourier transform
  (which may be computed with the FFT) into a Constant Q transform is
  detailed in [Brown and Puckette (1992).][1]
[1]:
  http://www.wellesley.edu/Physics/brown/pubs/effalgV92P2698-P2701.pdf

I need a new and improved DFT


Alguém poderia me ajudar a alinhar?

Question:

function Somar() {
  var somaN1 = window.document.querySelector('input#somaN1')
  var somaN2 = window.document.querySelector('input#somaN2')
  var somaRes = window.document.querySelector('span#somaRes')
  var somaN1 = Number.parseInt(somaN1.value)
  var somaN2 = Number.parseInt(somaN2.value)
  var soma = somaN1 + somaN2
  somaRes.innerHTML = `<strong>${soma}</strong>`
}

function Subtrair() {
  var subtracaoN1 = window.document.querySelector('input#subtracaoN1')
  var subtracaoN2 = window.document.querySelector('input#subtracaoN2')
  var subtracaoRes = window.document.querySelector('span#subtracaoRes')
  var subtracaoN1 = Number.parseInt(subtracaoN1.value)
  var subtracaoN2 = Number.parseInt(subtracaoN2.value)
  var subtracao = subtracaoN1 + subtracaoN2
  subtracaoRes.innerHTML = `<strong>${subtracao}</strong>`
}

function Multiplicar() {
  var multiplicacaoN1 = window.document.querySelector('input#multiplicacaoN1')
  var multiplicacaoN2 = window.document.querySelector('input#multiplicacaoN2')
  var multiplicacaoRes = window.document.querySelector('span#multiplicacaoRes')
  var multiplicacaoN1 = Number.parseInt(multiplicacaoN1.value)
  var multiplicacaoN2 = Number.parseInt(multiplicacaoN2.value)
  var multiplicacao = multiplicacaoN1 + multiplicacaoN2
  multiplicacaoRes.innerHTML = `<strong>${multiplicacao}</strong>`
}

function Dividir() {
  var divisaoN1 = window.document.querySelector('input#divisaoN1')
  var divisaoN2 = window.document.querySelector("input#divisaoN2")
  var divisaoRes = window.document.querySelector('span#divisaoRes')
  var divisaoN1 = Number.parseInt(divisaoN1.value)
  var divisaoN2 = Number.parseInt(divisaoN2.value)
  var divisao = divisaoN1 + divisaoN2
  divisaoRes.innerHTML = `<strong>${divisao}</strong>`
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Fazendo cálculos.</title>

Cálculos a seguir:

    <input type="number" class="number" id="somaN1">
    +
    <input type="number" class="number" id="somaN2">
    <input type="button" value="=" onclick="Somar()">

    <input type="number" class="number" id="subtracaoN1">
    -
    <input type="number" class="number" id="subtracaoN2">
    <input type="button" value="=" onclick="Subtrair()">

    <input type="number" class="number" id="multiplicacaoN1">
    ×
    <input type="number" class="number" id="multiplicacaoN2">
    <input type="button" value="=" onclick="Multiplicar()">

    <input type="number" class="number" id="divisaoN1">
    ÷
    <input type="number" class="number" id="divisaoN2">
    <input type="button" value="=" onclick="Dividir()">

Eu estou tentando a algum tempo alinhar os inputs da direita com apenas uma declaração CSS. Alguém poderia me ajudar?
Answer: Uma boa forma de garantir largura e alinhamento dos item é a utilização do inline-grid, no seu caso, a utilização deve ser junto a definição da largura do elemento, ou seja width:20px e a definição do alinhamento dos elementos da classe aritmetico com a definição do text-align:center.
Seu código ficaria assim:

function Somar() {
  var somaN1 = window.document.querySelector('input#somaN1')
  var somaN2 = window.document.querySelector('input#somaN2')
  var somaRes = window.document.querySelector('span#somaRes')
  var somaN1 = Number.parseInt(somaN1.value)
  var somaN2 = Number.parseInt(somaN2.value)
  var soma = somaN1 + somaN2
  somaRes.innerHTML = `<strong>${soma}</strong>`
}

function Subtrair() {
  var subtracaoN1 = window.document.querySelector('input#subtracaoN1')
  var subtracaoN2 = window.document.querySelector('input#subtracaoN2')
  var subtracaoRes = window.document.querySelector('span#subtracaoRes')
  var subtracaoN1 = Number.parseInt(subtracaoN1.value)
  var subtracaoN2 = Number.parseInt(subtracaoN2.value)
  var subtracao = subtracaoN1 - subtracaoN2
  subtracaoRes.innerHTML = `<strong>${subtracao}</strong>`
}

function Multiplicar() {
  var multiplicacaoN1 = window.document.querySelector('input#multiplicacaoN1')
  var multiplicacaoN2 = window.document.querySelector('input#multiplicacaoN2')
  var multiplicacaoRes = window.document.querySelector('span#multiplicacaoRes')
  var multiplicacaoN1 = Number.parseInt(multiplicacaoN1.value)
  var multiplicacaoN2 = Number.parseInt(multiplicacaoN2.value)
  var multiplicacao = multiplicacaoN1 * multiplicacaoN2
  multiplicacaoRes.innerHTML = `<strong>${multiplicacao}</strong>`
}

function Dividir() {
  var divisaoN1 = window.document.querySelector('input#divisaoN1')
  var divisaoN2 = window.document.querySelector("input#divisaoN2")
  var divisaoRes = window.document.querySelector('span#divisaoRes')
  var divisaoN1 = Number.parseInt(divisaoN1.value)
  var divisaoN2 = Number.parseInt(divisaoN2.value)
  var divisao = divisaoN1 / divisaoN2
  divisaoRes.innerHTML = `<strong>${divisao}</strong>`
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Fazendo cálculos.</title>

Cálculos a seguir:

    <input type="number" class="number" id="somaN1">
    +
    <input type="number" class="number" id="somaN2">
    <input type="button" value="=" onclick="Somar()">

    <input type="number" class="number" id="subtracaoN1">
    -
    <input type="number" class="number" id="subtracaoN2">
    <input type="button" value="=" onclick="Subtrair()">

    <input type="number" class="number" id="multiplicacaoN1">
    ×
    <input type="number" class="number" id="multiplicacaoN2">
    <input type="button" value="=" onclick="Multiplicar()">

    <input type="number" class="number" id="divisaoN1">
    ÷
    <input type="number" class="number" id="divisaoN2">
    <input type="button" value="=" onclick="Dividir()">

Além disso, corrigi as funções executadas no seu código, todas as operações estavam apenas somando.

Alguém poderia me ajudar a alinhar?


Porque a DIV quebra de linha ao ser redimensionada?

Question: Tenho três DIV´s uma ao lado da outra, porém defini que a DIV do meio (espaco-contato) tenha uma largura mínima definida, porém, que as DIV´s laterais continuem responsivas.
O que está acontecendo é que ao chegar na largura mínima definida na DIV do meio (espaco-contato), a da lateral direita (espaco-interacao) quebra de linha e depois a DIV (espaco-contato) também quabra de linha. Preciso que as três DIV´s continuem reduzindo suas larguras sem quebrar de linha.
Segue o link para verificação: https://jsfiddle.net/gladisonperosini/3bohLt7r/4/
Como resolver?
Segue o CSS:
header{
    width: 100%;
    max-width: 1550px;
    margin: auto;
    background-color: #eee;
    padding: 5px;
    box-sizing: border-box;
    overflow: auto;
}
header div.espaco-logo{
    float: left;
    width: calc(100% / 3);
    height: 130px;
    background-color: #222;
}
header div.espaco-contato{
    float: left;
    width: calc(100% / 3);
    min-width: 450px;
    height: 130px;
    background-color: #ccc;
}
header div.espaco-interacao{
    float: left;
    width: calc(100% / 3);
    height: 130px;
    background-color: #222;
}

HTML

Comment: coloque um exemplo funcionando com o problema, só observar o código estático fica mais difícil ajudar
Comment: Coloca display: Flex, no header que deve resolver
Comment: @RicardoPontual Olá, segue o link https://jsfiddle.net/gladisonperosini/3bohLt7r/4/
Comment: @hugocsl Não resolveu!
Comment: Gladison, como o @hugocsl comentou colocar um `display:flex;` resolve. (Também removi os floats, que não tem mais necessidade) Veja o exemplo: https://jsfiddle.net/0boad2kt/
Answer: Se a div do meio possui uma largura mínima de 450px, quando a largura da tela divida por 3 for menor que 450px (desconsiderando o padding que você colocou no header), a div do meio irá continuar com os mesmos 450px (que é o mínimo definido), e irá ocupar mais espaço do que foi definido na função calc(100% / 3), fazendo com que as outras divs laterais (a última primeiramente, ou as duas) fiquem sem espaço para ficarem ao lado, causando a quebra de linha.
O que você deve fazer mesmo é utilizar flexbox no header, como dito nas outras respostas, mas há uma outra forma que aproveita melhor o recurso do flexbox:
Além de dispensar o uso do float: left (que não é o melhor recurso nesses casos) pode dispensar também o uso do calc(100% / 3). Já que vai usar flexbox, use em vez do calc(), a propriedade flex: 1 em cada div (que seria o mesmo que flex-grow: 1). Essa propriedade irá distribuir as 3 divs de forma igual dentro da largura do header (mantendo a largura mínima da div do meio definida em 450px). Se a largura da tela for igual ou maior que 450px * 3, ou seja, 1350px, as 3 divs terão exatamente a mesma largura.
O código ficará assim:

body{
   margin: 0;
}
header{
    width: 100%;
    max-width: 1550px;
    margin: auto;
    background-color: #eee;
    padding: 5px;
    box-sizing: border-box;
    overflow: auto;
    display: flex;
}
header div.espaco-logo{
    height: 130px;
    background-color: #222;
    flex: 1;
}
header div.espaco-contato{
    min-width: 450px;
    height: 130px;
    background-color: #ccc;
    flex: 1;
}
header div.espaco-interacao{
    height: 130px;
    background-color: #bbb;
    flex: 1;
}

Repare que com o uso da propriedade flex o código fica mais enxuto e melhor aproveitado os recursos do flexbox.
Comment: Passo quase 1hr para escrever a resposta, abro manuais, leio, analiso tudo, faço vários testes, reviso tudo antes de clicar em "Postar" pra ver se há alguma coisa errada ou se escrevi alguma besteira ou algo muito subjetivo, aí vem um usuário e negativa. Tudo bem que ele pode não concordar com alguma coisa, mas no mínimo deveria reconhecer o esforço que foi feito e se for negativar (que é um direito), pelo menos dizer o que achou de errado. É isso que faço com respostas elaboradas. Com respostas pobres eu tb negativo sem falar nada, mas com elaboradas, se eu voto -1, eu sempre deixo um recado.
Comment: Posto uma resposta bem explicada e sugerindo uma solução melhor e vem um usuário e negativa sem falar nada. Esse tipo de usuário deveria rever seus conceitos se está realmente ajudando a comunidade. Lamentável! Esse é o mal do StackOverflow.
Answer: Olá, você pode resolver utilizando o flex-box desta forma:
header{
    width: 100%;
    max-width: 1550px;
    margin: auto;
    background-color: #eee;
    padding: 5px;
    box-sizing: border-box;
    overflow: auto;
    display: flex;
    flex-wrap: nowrap;
}
header div.espaco-logo{
    width: calc(100% / 3);
    height: 130px;
    background-color: #222;
}
header div.espaco-contato{
    width: calc(100% / 3);
    min-width: 450px;
    height: 130px;
    background-color: #ccc;
}
header div.espaco-interacao{

    width: calc(100% / 3);
    height: 130px;
    background-color: #bbb;
}

Answer: porque essa div  ela tem um tamanho quando esse tamanho da tela não suporta tamanho da div ela faz essa quebra de linha  vc pode mudar tamanho dela usando @media screen and (max-width 480px) so um exemplo ou mudar tamanho.  se voce prestar atenção tamanho da div não muda voce teria que mudar tamanho width para aquela screen.
@media screen and (min-width: 600px) {
  header div.espaco-logo{
    float: left;
    width:150px ;
    height: 130px;
    background-color: #222;
}

recomendo usar bootstrap 4


How to configure depend.el in emacs org-mode?

Question: http://orgmode.org/worg/org-contrib/org-depend.html
In the bottom of the webpage,"Advanced Triggerring Example"--
{(defun mm/org-insert-trigger ()
"Automatically insert chain-find-next trigger when entry becomes NEXT"
(cond ((equal org-state "NEXT")
     (unless org-depend-doing-chain-find-next
       (org-set-property "TRIGGER" "chain-find-next(NEXT,from-current,priority-up,effort-down)")))
    ((not (member org-state org-done-keywords))
     (org-delete-property "TRIGGER"))))

(add-hook 'org-after-todo-state-change-hook 'mm/org-insert-trigger)`}

I want to configure the org-mode like styled above, but I don't know how.
mm/org-insert-trigger What about mm? I put the code in .emacs. When I changed the status to 'NEXT', it appears symbol's value as variable is void.
Comment: put `(require 'org-depend)` in your `.emacs` (also called init file).
Comment: the `mm` is most likely the authors name. To help you solve your problem, please provide backtrace. `(setq debug-on-error t)`
Comment: `unless: Symbol's value as variable is void: org-depend-doing-chain-find-next`
Comment: @kindahero You should add that as an answer to have it accepted/upvoted.
Answer: put (require 'org-depend) in your .emacs


How to add user info along with address info in a single form using 2 content types?

Question: I have a content type 'Person', one field of which has a entity reference to a content type 'Address'.
I would like an anonymous user to add their information along with their address in a single form using these two content types. What should I use to do that?  Do I have to code it or does a module or a combination of modules help me?
Also similarly, for a logged-in user, I would like them to be able to edit their information which was previously saved. How do I do that?
Notes:

I would like the anonymous users to register and also provide a few more pieces of profile information. Of course, I do limit what else they can do till they get approved by the administrator.
I could capture the address information in the same content type but the reason I am thinking of separate content type is because two people can have the same address and I don't want to have redundant information. It would also provide me a way to figure out people who live in the same household. Also, I don't want to lose the address if someone moves and decides to update their address. It looks like I can add/edit two different nodes in the same page. If not reference, how? Do I have to code for it or there are modules that can do it?
My choice of 'address' as an example was a bad one. My broader question is: Given two tables with one of the fields as a foreign key into the other, in Drupal, how can I create, update, delete corresponding rows in the two tables at the same time. The interface being user friendly UI for end user. Does I have to do this in code, or is there a single module or a set of modules that can be used to accomplish this? I am not looking for a full solution as much as pointers in the right direction.
Comment: Your question was somehow unclear , are you going to allow anonymous users to add some data to an specific content type?
Comment: although you can add/edit two different nodes on one page, I don't know that you can do it with a reference, since the referenced node needs to exist before hand in order for the reference field to work. Why not include address information in the same content type?
Comment: In order to get around that duplicate information, you would have to expose the address content type, so that a new user would 'select' an address from an existing list if possible - that is a HUGE privacy issue, and  would constitute a breach of privacy (illegal) in many countries - even if it's auto-complete, to find out if someone had created an account you just start typing their address. It's a bad idea. duplicate addresses should be irrelevant (my opinion), given the miniscule space they would require
Comment: @AjayR : I integrated various of your comments (to your own question) IN your question (within "Notes"), which should help others to digest your question and your related comments. Please review what I added within those 'notes', and correct/rework where appropriate, ok?
Answer: You probably should have a look to Profile2 module. If you really want to use content types, you should have a look to Inline Entity Form and then configure permissions to be sure users can only edit their own content.
Hope that helps ;-)
Comment: Thanks, vbouchet.  I am using profile2 already. but like @Geoff mentioned above, I am running into 'referenced node need to exist already' issue.
Answer: It sounds to me that you should have a look at the Entity connect module. Here are some details about it (from its project page):

Entity Connect now expands both

Entity reference
References (node_reference and user_reference)

fields by adding "add new content" and "edit current content" buttons.
It will work with all default widgets provided by Entity reference and References.
The Drupal module will allow you to dynamically create and edit entities (see bellow for the list of currently working entity types)
  which should be referenced into an Entity reference field.
It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.
The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.
The "edit" button will take the user to the edit form of the referenced entity. Once the user is done editing, he is sent back to the previous form.

Refer to Creating related records on the master for a first impression/intro about this module. This article is part of the illuminating Relativity Model for Drupal, for which this is an introduction to it (quoted from this linked page):

The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:

Data architecture and data modeling merging as a single step through a documentation procedure.
Customized user interfaces that cater to individual workflows throughout permission roles.
Multi-level relational data structures that relate to other multi-level relational structures.
Mimicking the concept of database joins within Drupal's UI's.
Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The small handfull of modules (cfr. the last bullet) is detailed on Interface elegance and experience and is like so (apart from Drupal core):

https://www.drupal.org/project/ctools
https://www.drupal.org/project/date
https://www.drupal.org/project/entity
https://www.drupal.org/project/entityreference
https://www.drupal.org/project/entityconnect
https://www.drupal.org/project/field_group
https://www.drupal.org/project/token
https://www.drupal.org/project/pathauto
https://www.drupal.org/project/views


Nginx as reverse proxy to Hudson-Logout issue

Question: I have configured nginx as a reverse proxy to our hudson build server as follows:
server {
    listen       80;
    server_name  koala.proxy.internal;

location /hudson/ {
    proxy_pass         http://build.example.com/hudson/;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header Host $http_host;
    proxy_redirect     off;
    }

The backend hudson server is configured to authenticate users with Active Directory using
the hudson active directory plugin.
Everything works fine, except that when I click the logout button, nothing happens, and
I am still logged in, wheras the expected behaviour is, I should be logged out and taken
back to the login page.
The request and response headers in firebug show these:
Response:
HTTP/1.1 302 Moved Temporarily
Server: nginx
Date: Wed, 01 Sep 2010 02:40:57 GMT
Connection: keep-alive
Set-Cookie: ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE=""; Path=/hudson
Location: http://koala.proxy.internal/hudson/
Content-Length: 0
Expires: Thu, 02 Sep 2010 02:40:57 GMT
Cache-Control: max-age=86400

Request:
GET /hudson/logout HTTP/1.1
Host: koala.proxy.internal
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:126.96.36.199) Gecko/20100722     Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://koala.proxy.internal/hudson/people/
Cookie: screenResolution=1280x720; JSESSIONID=8957FA425BC89DE784266DAACAD45135

Below are the headers from the hudson server, when I access it directly and click the logout button:
Response:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Expires: 0
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 01 Sep 2010 05:00:33 GMT

Request:
GET /hudson/login?from=%2Fhudson%2F HTTP/1.1
Host: build.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:18.104.22.168) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://build.example.com/hudson/
Cookie: screenResolution=1280x720; JSESSIONID=105C0A7031B817E0321336310FC8D6E1

As I understand from the headers,when I click logout, the GET request should be for "/hudson/login?from=%2Fhudson%2F" and not for "/hudson/logout" , as is happening through the reverse proxy.
I have tried many things to get it working but to no avail.Would really appreciate if someone could guide me here.
Thanks,
Mogaroy
Answer: For anyone who may be facing similar issues, I solved my problem by adding 'add_header Pragma "no-cache"' to my configuration.
http://agiletesting.blogspot.com/2010/06/commong-nginx-configuration-options.html
Thanks,
Mogaroy


Matlab permutation

Question: I have written a function to perform permutations of n obejects.
I have the variables a=[1],[2],[3];k=1 and n=4;a contains the objects which are 1,2 and 3 respectively.The following is the function code that i have written:
function [res]=perm(a,k,n,jj)

if k==n
    res{jj}=a;
    jj=jj+1;

else
    for i=k:n
        t=a{k};
        a{k}=a{i};
        a{i}=t;
    perm(a,k+1,n,jj)
    t=a{k};
    a{k}=a{i};
    a{i}=t;
    end
end
end

However, when i call the function as:
jj=1;

    [res]=perm(a,k,n,jj)

I am getting the following error displayed:
Error in ==> perm at 3
if k==n

??? Output argument "res" (and maybe others) not assigned during call to "J:\main
project\perm.m>perm".

Error in ==> mainp at 254
    [res]=perm(a,k,n,jj)

The following is the code in the main program with regard to the permutation:
mr=4
    for i=1:mr
        a{i}=i;
    end
    n=mr;
    %This assignment is for the ease to work with.
    %just stored the indices till mr for the purpose of permutation
    k=1;
    %this is the k that the function perm has

  jj=1;

    [res]=perm(a,k,n,jj)

Can somebody please help me resolve this?Thanks in advance.
Comment: is it possible `perm` is a nested function inside `perm.m`? is it possible you have a variable `res` in the scope outside `perm`?
Comment: Can you share your entire code? It looks like you're not calling the function correctly. `Error in ==> mainp at 254
    [res]=perm(a,k,n,jj)`
Comment: The error message looks right, even if the location is not.  Make sure that `res` is assigned on every path through `perm`.  Right now it is only assigned if `k == n`.
Comment: @MylesBaker   The following is the code in the main program with regard to the permutation:
mr=4
    for i=1:mr
        a{i}=i;
    end
    n=mr;
    %This assignment is for the ease to work with.
    %just stored the indices till mr for the purpose of permutation
    k=1;
    %this is the k that the function perm has

  jj=1;

    [res]=perm(a,k,n,jj)
Comment: @shai, i am calling perm recursively. And variable res is used first inside perm,after which its value is returned to the main program
Comment: @BenVoigt I am getting this error message only when res is a cell array and it has to be returned. Otherwise if i make the assignment as res=a instead of res{jj}=a, i am getting the outputs printed. But I cant follow this since I need each permutation for future processing.
Answer: Your else block leaves res undefined.
I think you're assuming that res is a global variable and all invocations of perm will write into different parts of a single cell array.  That isn't true.  It is an output variable, local to the current call.  There's no sharing during recursion, they all have independent cell arrays named res.  The parameter jj is also not shared, so adding one is useless as well.
If you want to use this technique of building up the output, you'll need to make sure it is defined at a wider scope than the recursion.  For example, use a local helper function:
function [res]=perm(a,k,n,jj)
    res = {};
    perm_impl(a,k);

    function [] = perm_impl(a,k) // doesn't get its own local res, n, or jj
        if k==n
            res{jj}=a;
            jj=jj+1;
        else
            for i=k:n
                t=a{k};
                a{k}=a{i};
                a{i}=t;
                perm_impl(a,k+1)
                t=a{k};
                a{k}=a{i};
                a{i}=t;
            end
        end
    end
end

Now all runs of perm_impl work on the same cell array res, because Matlab documentation says:

Variables within nested functions are accessible to more than just their immediate function. A variable, x, to which you assign a value or use within a nested function resides in the workspace of the outermost function that both contains the nested function and accesses x.
If you intentionally use a variable in this manner, it is not a problem. For examples, see the MATLAB Programming Demo on Nested Functions.
However, if you unintentionally use a variable in this manner, it can result in unexpected behavior. If the highlighting indicates that the scope of a variable spans multiple functions, and that was not your intent, consider:

Renaming the nested function variable so it does not match the outer function variable name.
Passing the variable into the function as an input argument instead of using the variable directly within the nested function

I can't tell whether a was supposed to be shared or not...
Comment: So in reality, I should have said "Every instance of the local function has a separate copy of its input and output parameters".  Variables belong to the outer function and are shared between every invocation of the local helper function.
Comment: So then how can i make it global so that I get all the permutations stored for future processing?
Comment: Thank you so much. It worked. But I have one more doubt. Eventhough the local function is employed,it is being called recursively.So how exactly building up the output works here. I mean every instance of the local helper function should have its own local variables I suppose?
Comment: Every instance of the local function has a separate copy of its own local variables, yes.  But res does not belong to the local function...  Only `a` and `k` are local to the helper function.
Comment: @Geethu: Ack!  My previous explanation was wrong.  Matlab help says "Variables within nested functions are accessible to more than just their immediate function. A variable, x, to which you assign a value or use within a nested function resides in the workspace of the outermost function that both contains the nested function and accesses x."

Matlab permutation


prove change in total probability of success in binomial distribution

Question: A binomial distribution of $n$ samples and probability of success $p$ is defined as
$ P(k) =  \binom{n}{k} \cdot p^kq^{n-k} $.
For a given value of $r$ where $r \in \mathbb{N} \quad \text{and } r \gt 1$, if we decrease the probability of success by  $\hat{p} = \frac{p}{r}$ and increase the samples $\hat{n} = nr$, I want to prove
$P(k\ge 1) - P(\hat{k}\ge 1) \gt 0 $
$\Rightarrow \left(1-P(k= 0)\right) - \left(1-P(\hat{k}= 0)\right) \gt 0$
$\Rightarrow P(\hat{k}= 0) - P(k= 0) \gt 0$
$\Rightarrow  \binom{nr}{0} \cdot \hat{p}^0\hat{q}^{nr} - \binom{n}{0} \cdot p^0q^{n} \gt 0$
$\Rightarrow \left(1-\hat{p}\right)^{nr} - \left(1-p\right)^{n} \gt 0$
$\Rightarrow \left(1-\frac{p}{r}\right)^{nr} - \left(1-p\right)^{n} \gt 0$
I'm able to show it for specific examples but unfortunately unable to prove the last inequality in generic form.
Answer: First, by expanding $(1-p/r)^r$ to the power series, we have
$(1-p/r)^r=1-p + [(r-1)p^2/(2! r)-(r-1)(r-2)p^3/(3!r^2)+…+(-p/r)^r]$
that is,
$(1-p/r)^r = 1-p + A$
where $A > 0$ is the term in the square brackets. Thus, we have
$(1-p/r)^r > 1-p$,   (for r > 1). Then we have
$\left(1-\frac{p}{r}\right)^{nr} \gt \left(1-p\right)^{n}$


Why my hook_menu does not work?

Question: I have this code in the module cleanetica_advanced.
function cleanetica_advanced_menu() {

    $items['ajax/content/%'] = array(
      'page callback' => 'cleanetica_advanced_ajax_load',
      'page arguments' => array(2),
      'title' => 'Ajax content load',
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );

    $items['ajax/validate/form/%'] = array(
      'page callback' => 'cleanetica_advanced_ajax_validate_form',
      'page arguments' => array(3),
      'title' => 'Ajax validate form',
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );

    $items['user'] = array(
       'title' => 'blogs',
       'description' => 'Listing of blogs.',
       #'page callback' => 'blog_page',
       'access arguments' => array('access content'),
       'type' => MENU_DEFAULT_LOCAL_TASK
     );

    return $items;
}
For some reason the item "blogs" (which I created for testing only, there are no blogs in our site) does not show in the tabs of the page /users. I need to show it in the /users tabs. What is my error?
I checked that cleanetica_advanced module is loaded by inserting some nonsense in the .module file and seeing that the site ceases to work with an error message. (Then I removed the nonsense.)
By the way, does user in $items['user'] refer to the page where the menu should be shown or to the ID of the menu item itself?
Comment: There's a number of question on the general topic of implementing hook_menu. Please check some of those first.
Answer: "user" is a path already used by the User module; if your module is not executed after the User module (i.e. you are not altering the order hooks are executed), the menu item of the User module takes the precedence. (That is also the wrong way to alter the menu item defined from another module, but your purpose is not that.)
  // Registration and login pages.
  $items['user'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'page callback' => 'user_page',
    'access callback' => TRUE,
    'file' => 'user.pages.inc',
    'weight' => -10,
    'menu_name' => 'user-menu',
  );

If you want to define a menu tab for each user account, as I think, the definition of your menu item should be similar to this, used from the User module.
  $items['user/%user/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_profile_form', 1),
    'access callback' => 'user_edit_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'file' => 'user.pages.inc',
  );

For example, something similar to the following would work.
  $items['user/%user/edit'] = array(
    'title' => 'Blogs',
    'description' => 'Listing of blogs.',
    'page callback' => 'cleanetica_advanced_blog_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_LOCAL_TASK,
  );

The page callback receives an argument: the user object for the user account. It will be called from Drupal as cleanetica_advanced_blog_page($account).
Every function implemented by a module needs to be prefixed by its short name.
The menu type is MENU_LOCAL_TASK since there is already a MENU_DEFAULT_LOCAL_TASK menu item, and there cannot be two MENU_DEFAULT_LOCAL_TASK; the other tab is also the tab showing the details for the user account, and it is better to keep that as default tab.

If you want to show a list of blog posts global for all the users, then you need to change the path from user, or user/%user/edit, to (for example) blogs. Adding it as tab of the user tab doesn't make any sense, since the page would list content, not a list of users; it would be also shown together user/login, user/register, and it doesn't make sense to show a list of blog posts to who is registering/logging in.
Answer: user path is defined by core user.module so you cannot overwrite it from hook_menu().
If you want to alter default /user page, you need to implement hook_form_alter.
However, note that /user page is the only page that works in maintenance mode and it's a little bit complicated that this page shows login page or redirects to the user's profile depending on whether the user is logged in or or not.
If you want to add a new tab in user's profile(or add a new tab and set it the default), you can
(for Drupal 7):
$items['user/%user/blogs'] = array(
  'title' => 'Blogs',
  'page callback' => 'blog_page', // enter your own page callback here
  'page arguments' => array(1), // first argument to your page callback would be $user
  'access arguments' => array('access content'),
  'type' => MENU_LOCAL_TASK,
  'file' => 'cleanetica_advanced.pages.inc', // whatever. If your pagecallback is in the .module file, omit this line.
);

If you want to set this tab as the default, change MENU_LOCAL_TASK above to MENU_DEFAULT_LOCAL_TASK and implement a hook_menu_alter().
function cleanetica_advanced_menu_alter(&$items) {
  $items['user/%user/view']['type'] = MENU_LOCAL_TASK;
}

Why my hook_menu does not work?


allocating and deleting a pointer of an observer base class in a derived class

Question: i'm learning how to manage pointers in c++, since i need to do some numerical work.
Is it okay to have an observer pointer in a base class, and then taking ownership in a derived class?
#include <iostream>
#include <vector>
#include <memory>

class TensorExpression {
    public:
    using scalar = float;
    using pointer = scalar *;

    virtual ~TensorExpression() = default;

    TensorExpression(pointer data, std::vector<std::size_t> shape)
    :   data_ptr(data)
    ,   shape_(shape)
    {}

    protected:
    pointer data_ptr;

    private:
    std::vector<std::size_t> shape_;
};

class Tensor : public TensorExpression {
    public:

    Tensor(std::vector<std::size_t> shape)
    :   TensorExpression(new scalar[memory_size(shape)], shape)
    {}

    ~Tensor() override {
        delete[] data_ptr;
    }

    private:

    std::size_t memory_size(std::vector<std::size_t> shape) {
        std::size_t size = 1;
        for(auto s : shape) size *= s;
        return size;
    }
};

Also, if I want to change to an a smart pointer aproach after i understand this, will it be harmful if i'm planning to do gpu programming?
Comment: Not sure, but it sounds you should wrap those tensor allocated pointers into appropriate `std::unique_ptr` to make current ownership clear.
Comment: Since you are dealing with a raw owning pointer (`float*`), you can do what you like to it anywhere. Just be sure who's the current owner so you don't delete it twice.
Comment: in my case, only Tensor is able to delete the pointer, all other derived class will just be observers as the base class. But since i'm planing to delete Tensor from it's base class pointer, I'm worried i will be producing issues in the future.
Comment: It's an unusual setup, but as long as you remember who's owning it (and do a proper implementation of [_"the rule of five_"](https://en.cppreference.com/w/cpp/language/rule_of_three)) you could do it like this.
Comment: Yes, what @πάνταῥεῖ mentions is probably a better approach. Implement `unique_ptr` yourself and then use that home made wrapper.
Comment: @πάνταῥεῖ Does that also work for inplace new?
Answer: I would make the following changes to your code (code stripped down to the basics for clarity):
#include <iostream>
#include <vector>
#include <memory>

class TensorExpression {
    public:
    using scalar = float;
    using pointer = scalar *;

    virtual ~TensorExpression() {
        delete [] data_ptr;
    }

    TensorExpression(pointer data)
    :   data_ptr(data)
    {}

    protected:
    pointer data_ptr = nullptr;
};

class Tensor : public TensorExpression {
    public:

    Tensor()
    :   TensorExpression(new scalar[memory_size(shape)])
    {}
};

The point is, that if the base class declares data_ptr, it should also be responsible for destroying it (no matter who created it).  It also needs to initialise it (I always do that, regardless).
This puts you in a position to do the following, down the line, if you ever need to / want to:

data_ptr can be made a smart pointer (recommended) - that would be a simple drop-in change

you can add other classes that derive from TensorExpression

Also (for production code), read up on the rule of 3 / 5, else you have written yourself a time bomb here.
And of course, std::vector is the method of choice for allocating storage like this as it manages that automatically.
Comment: This all sounds awfully complicated (and error prone).  I think you should add an example of how you want to _use_ your class to your question.  We can probably suggest a way to make it all nice and simple.
Comment: I know about 3/5 rule, is just a prototipe, the problem with that is that i need to work with Eigen library or CUDA, and if a i put a destructor in the base class, and i decide to pass a pointer of a block of memory wrapped in a tensor expression, i will get double free violation.
Comment: @EricCardozo So, the API says that it takes over the overship of the raw owning pointer? If so, not a problem, remove `delete[] data_ptr;`
Comment: Yeah, but sometimes i need to initialize my data with some custom distribution. The issue I'm trying to solve is something like optional ownership. Sometimes creating a Tensor that owns a pointer and is responsible for deletion, but also passing lighweight views of that tensor and making operations with some extenal libraries. Anyways thanks for the help.
Comment: @Ted Lyngmo I think I'm solving it refactoring my code with a third class, a TensorBuffer, with optional ownership. A destructor that deletes the data given a bool member is_owner. So a Tensor can be just a view or allocate a block of memory.
Comment: @Ted Lyngmo was right, I could just remove the destructor ad rely in another entity to manage the memory. I don't know why I was complicating my self to much.