Preference graph?

Question: What is the name of a directed weighted graph in which an arc can have one of 3 weights: +, -, and x (for, e.g., 'like', 'dislike', and 'acquainted, but indifferent')? Note that the latter is not equivalent to the case of no arc.
Are there any results available for such graphs? I presume that they can be used in voting systems, maybe recommender systems, but I could not find any references.
Answer: There are definitely results concerning signed graphs. I am not so sure about the option with indifferent, but I guess somebody has looked into it.
Comment: Thank you! This brings me closer to the goal.

Preference graph?


How do I change the rate modules output to "# of users like this"?

Question: I am using the Rate module.
The current display for my thumbs up widget is:
(thumbs up image) 2 users have voted, including you.

I would like to change it to:
(thumbs up image) 2 users like this

How do I change the default tpl to accomplish this?
print $up_button;

if ($info) {
  print '
' . $info . '
';
}

if ($display_options['description']) {
  print '
' . $display_options['description'] . '
';
}

Answer: I haven't used the module. But looking at the code, you essentially need to override the preprocess function in the module which is used to generate the string.
Open rate.module in an editor and search for the text string that you are looking to change. In this case, this string would be something like "have voted", which should lead you to the function named rate_preprocess_rate_template_thumbs_up(). This is the function that you should look to override. You can see that the strings are added as part of two format_plural calls and should be straightforward to amend in the override function.
You can perform the override either from a custom module or from your theme's template.php file. Since the module is using a preprocess function to make its changes, I recommend using a process function (note the difference in name) when you override it. There should be plenty of documentation and examples available on drupal.org and drupalSE to aid you if you are unfamiliar with overriding.
Answer: Use the String Overrides module and add the following to the config:
original: @count users have voted, including you.

replacement: @count users like this.


(ASP.NET) Project file must include 'WindowsBase, PresentationCore, PresentationFramework'

Question: I'm seeing an inscrutable compile error in my ASP.NET application.

Project file must include the .NET Framework assembly 'WindowsBase, PresentationCore, PresentationFramework' in the reference list

That's the WPF assembly.  My project is ASP.NET.  Has anyone ever encountered this before?
Even stranger, the project was compiling before I started messing around with my .resx files due to a different issue.  Then suddenly this nonsensical error appeared.
Answer: This happens if you have a file in your project with its Build Action set to Resource. (which is used for WPF embedding)
Find the offending file and change its Build Action.
Comment: Ah yeah, thanks I think that's is.  I had set some of my .aspx files to "Page".  Changing them back to "Content" seems to have fixed the problem.  (That's what I get for monkeying around with stuff I don't understand.)
Comment: Do you have anything other than `None`, `Compile`, or `Content`?
Comment: I did set the .resx files to Build Action = *Resource* while I was experimenting.  But currently nothing is set to that (confirmed by searching for "Resource" in the project file), and I'm still seeing the error.
Answer: I had the following in the csproj file:
<Page Include="BuildProcessTemplates\DefaultTemplate.11.1.xaml">
  <Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="BuildProcessTemplates\LabDefaultTemplate.11.xaml">
  <Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="BuildProcessTemplates\UpgradeTemplate.xaml">
  <Generator>MSBuild:Compile</Generator>
</Page>

Changing it to below fixed the problem:
<Content Include="BuildProcessTemplates\DefaultTemplate.11.1.xaml" />
<Content Include="BuildProcessTemplates\LabDefaultTemplate.11.xaml" />
<Content Include="BuildProcessTemplates\UpgradeTemplate.xaml" />


Consistent, non-parametric, robust (to fat tails) estimation of expected value of an asymmetric distribution

Question: Question: Is anyone aware of a consistent, non-parametric estimator of the expected value of an asymmetric distribution that is robust to fat tails? What if we constrain ourselves to the class of continuous (on the real number line) uni-modal distributions?
Note: There are several parametric estimators in the literature; I am specifically interested in non-parametric estimators.
Comment: If we talk about fat tailed distributions, then the existence of expected value is a very strong assumption.
Comment: @user603 It's not robust :-)   The data I'm working with is (very) fat-tailed, so the sample mean is very noisy, even with lots of observations. The sample median or sample trimmed mean are examples of robust estimators, but given an asymmetric distribution, they do not (necessarily) converge to the expected value.
Comment: what's the problem with the sample mean?
Comment: @MichaelMayer Very true and to be honest I'm not completely convinced it does exist for the type of data I'm working with. Nonetheless, for the current paper I'm working on I am assuming it exists so as to fit in with the extant literature :-)  I might look at other location parameters in a future paper...
Answer: In the univariate setting I would do like so:

Compute the adjusted whiskers from the adjusted boxplot.
Compute a weighted mean by assigning weight 1 to the observations inside the adjusted whiskers and 0 (for those observations outside the whiskers). This is a form a trimmed mean, but the trimming takes the asymmetry of the good part of the data into account.
Comment: "I wonder if *any* estimator would work at all" -I agree with this sentiment. This is why I said in an earlier comment that it is plausible the question has no answer. After all, to obtain consistency for the first moment, we need to say something about the tails of the distribution, but without making a parametric assumption, it is difficult to see how to do this without using the observations from the tails. I was hoping that I was overlooking something clever, but perhaps what I am trying to do is simply impossible without a parametric assumption.
Comment: +1 I hadn't come across Hubert and Vandervieren's paper in my literature search. It was an interesting read, thanks for the reference. However, the estimator you propose is not (necessarily) consistent, so I'll hold off on awarding the answer tick for now. It is plausible that the question has no answer, so if there are no other responses over the next few weeks I'll come back and give the tick. Thanks again.
Comment: I'm interested by your comment. It's not clear to me how  an estimate of centrality can by inconsistent.
Comment: I understand the use of consistency factor to correct the systematic bias resulting from trimming on the second moments. I've never encountered the concept of consistency correction factor for the first moment. Under the conditions of your comment, I wonder if *any* estimator would work at all. On the one hand, you don't know the distribution of the good data, so, if you want to exclude the outliers, you will to do some form of trimming. But by your comment above, this will cause the trimmed mean to be the inconsistent.
Comment: The parameter I am specifically interested in is expected value (ie first moment), and by "consistency" I mean convergence in probability to the first moment. My reading of the Hubert/Vandervieren paper indicates that their method is ad hoc, ie it is a good approximation across a wide variety of distributions, but nonetheless the resulting asymmetric trimmed mean is not guaranteed to converge in probability to the first moment. Thus by my definition it is inconsistent. Unfortunately, for the paper I am writing, the parameter of interest *must* be the first moment (for several reasons).
Comment: @ColinTBowers: thanks for having taken the time to respond to my comment. Indeed, it may be that we are overlooking some more clever approach.


How to programmatically set the front page?

Question: I want to set the Drupal front page programmatically at run time.
How can I do this? Is this possible?
Answer: You can use variable_set() for that.
variable_set('site_frontpage', $value);

Comment: This is correct, but it's not something that should be done too frequently or based on a use action. A variable_set() call always results in "cache_clear_all('variables', 'cache_bootstrap');" so the next request will need to re-fetch the variables and the bootstrap information from the database.
Comment: Yes, it will affect performance, cache_bootstrap contains multiple caches that will only be rebuilt over time, for example hook implementations. Alternative solutions would be using Views, Panels or a custom module to dynamically display content on the front page. For example, you could build a view to show the most recent node of a content type and then point site_frontpage to that.
Comment: @Berdir - this affect somehow the site performance?
Comment: Using this in a `hook_install` or `hook_update_N` then should be fine.
Answer: There is a module (Frontpage, which is one I maintained) that allows to set a different front page for anonymous users, and authenticated users. The module allows third-party modules to alter the page to which the users are instead redirected, or to alter the structure array used to render the page. Third-party modules are allowed to change the redirection URL only when the front page for anonymous or authenticated has not been set within the Frontpage module, or when there has been an error during the node loading; the module will probably be changed in the future to allow third-party modules to redirect the users to a specific page they select.
As alternative, you can create a custom module that, using code similar to the one used by Frontpage, redirect users to a specific page, basing on specific criteria.
The module should implement hook_menu() and associate a menu callback to, for example, http://example.com/frontpage; the page callback of that menu item should simply verify a condition is verified, and then redirect the users to a specific URL.
The code skeleton could be something similar to the following:
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['frontpage'] = array(
    'page callback' => 'mymodule_frontpage_view',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function mymodule_frontpage_view() {
  // These variables can be useful to redirect the users
  // to specific pages, basing on the language currently set for
  // the content, or on the fact the user is logged in.
  $langcode = $GLOBALS['language_content']->language;
  $logged_in = user_is_logged_in();

  if ($condition) {
    drupal_goto($redirect);
  }
}

Answer: A very flexible solution would be to use Panels. Different displays can be presented based on any criteria, and is controlled through a UI.
Answer: I fixed like this:
/**
 * Implements hook_page_alter.
 * @param type $page
 */
function my_module_page_alter(&$page){
  global $user;

  $is_fron_page = drupal_is_front_page();
  if($is_fron_page && $user->uid){
    $redirect = 'users/'.$user->name.'/my-argument';
    drupal_goto($redirect);
  }
}

Comment: Hello. Nice of you to share your code. Would be even nicer if you could tell us how exactly your code fixes it. You know, reasoning others can follow if for some reason copy-pasted code will not work for them.
Comment: @molot - this method, that should be added to your custom module, implements `hook_page_alter`, and uses `drupal_is_front_page` to redirect users, using `drupal_goto`, based on some condition (in this case $user->uid should not be 0)
Comment: @commonpike it's not that I don't understand it. My comment was about answer's quality overall, and specifically to it's usability for new, inexperienced users.
Answer: The Rules module can be used also to set the frontpage "programatically".
The actually rule to be created, would be a variation of the answer at Redirect logged in (authenticated) users to a different frontpage using rules or php code.
And optionally combining it with the Flag module, might possibly further enhance the user experience. Eg for logged in users to indicate which of the possible frontpages they consider as their "favorite".
Answer: If you're looking to programmatically set this globally, you can set the variable in settings.php:
$conf['site_frontpage'] = 'some/custom/path';

Answer: I've altered the homepage node (on subdomains) by settings the variable in a hook_url_outbound_alter()
variable_set('site_frontpage', $value);

And then redirecting:
$_GET['q'] = 'node/' . $domain_homepage_node_id;

Answer: From command line or in a shell's script, you can use this Drush command
drush variable-set site_frontpage /path/to/page

or, using alias vset
drush vset site_frontpage /path/to/page

This should comply with Drupal 7 (then Drush 8), as per question.
If you use more a modern system instead, e.g. Drupal 10/Drush 12, then try
drush config:set system.site page.front /path/to/page

or, using alias cset
drush cset system.site page.front /path/to/page

or alias config-set
drush config-set system.site page.front /path/to/page


field_info_field API to get human readable name

Question: We want get human readable name from field info API.
For e.g. in below API call
field_info_field('field_image')

From UI for Drupal to add Article as below:

Can we get this human readable names i.e. Title, Alternate Text etc from API.
Answer: You can't, no - the labels are set statically in code (in image.field.inc), they don't come from the API:
<code>// Add the additional alt and title fields.
$element['alt'] = array(
  '#title' => t('Alternate text'),
  '#type' => 'textfield',
  '#default_value' => isset($item['alt']) ? $item['alt'] : '',
  '#description' => t('This text will be used by screen readers, search engines, or when the image cannot be loaded.'),
  // @see http://www.gawds.org/show.php?contentid=28
  '#maxlength' => 512,
  '#weight' => -2,
  '#access' => (bool) $item['fid'] && $settings['alt_field'],
);
$element['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#default_value' => isset($item['title']) ? $item['title'] : '',
  '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
  '#maxlength' => 1024,
  '#weight' => -1,
  '#access' => (bool) $item['fid'] && $settings['title_field'],
);
</code>


Each input="file" Jquery não valida

Question: Possuo o seguinte código no formulário:

            Máximo de 7 fotos

            <input type="file" name="files[]" class="form-control"
            multiple="multiple" placeholder="" id="picture">

Quando realizo a seleção dos arquivos eu tenho a validação de quantidade( que funciona normalmente ):

    $("#picture").on("change", function () {
        if ($("#picture")[0].files.length > 7) {
            $(this).css('boder', '3px solid red');
            $('#small-alert-pic').css('color', 'red')
            $('#small-alert-pic').text('ATENÇÃO! SÃO PERMITIDOS APENAS 7 FOTOS PARA UPLOAD');
        }
    });

porem quando faço a validação do tamanho do arquivo ocorre que apenas valida o primeiro. Se eu seleciono um arquivo de 1kb e um de 19MB( nessa ordem) ele não valida o segundo, porem se seleciono o de 19MB e o de 1KB ele valida normalmente. Segue o código:
 $('#picture').change(function(){
        var isOk = true;
        var maxSize = parseInt(2048, 10)
        $('input[type=file]').each(function () {
            if (typeof this.files[0] !== 'undefined') {
                var size = this.files[0].size;
                console.log(size / 1000 + ' -- ' + maxSize);
                isOk = maxSize > (size / 1000);
                if (!isOk) {
                    $('#picture-size').prev().css({
                        "color": " red"
                    }).text('ATENÇÃO SÃO PERMITIDOS CADA ARQUIVO DEVE POSSUIR APENAS 2MB');
                } else {
                    $(this).prev().css({
                        "border": "none"
                    });
                }
                return isOk;
            }
        });
        return isOk;
    });

Alguém tem ideia do que pode estar ocorrendo?
Answer:
Note que eu inteirei sobre o array de arquivos.

O problema, aparentemente, está aqui: var size = this.files[0].size;.
Veja: com isso, você pega somente o primeiro arquivo. E você deve validar em todos os arquivos, não somente para o primeiro.
Tenta o seguinte:

$("#picture").on("change", function() {
  if ($("#picture")[0].files.length > 7) {
    $(this).css('boder', '3px solid red');
    $('#small-alert-pic').css('color', 'red')
    $('#small-alert-pic').text('ATENÇÃO! SÃO PERMITIDOS APENAS 7 FOTOS PARA UPLOAD');
  }
});

$('#picture').change(function() {

  //console.clear();

  var isOk = true;

  var maxSize = parseInt(2048, 10);

  $('input[type=file]').each(function() {

    var files = this.files;

    for (let i = 0; i < files.length; i++) {

      if (typeof this.files[i] !== 'undefined') {

        var size = parseInt(this.files[i].size);

        console.log(size);

        console.log(size / 1000 + ' -- ' + maxSize);

        isOk = maxSize > (size / 1000);

        if (!isOk) {
          $('#picture-size').prev().css({
            "color": " red"
          }).text('ATENÇÃO SÃO PERMITIDOS CADA ARQUIVO DEVE POSSUIR APENAS 2MB');
        } else {
          $(this).prev().css({
            "border": "none"
          });
        }
      }

      return isOk;

    }
  });
  return isOk;
});

  Máximo de 7 fotos

  <input type="file" name="files[]" class="form-control" multiple="multiple" placeholder="" id="picture">

Comment: O looping funcionou agora, eu tive que realizar umas modificações pois quando é colocado o return dentro do each ele só executa o primeiro. Obrigado.
Comment: Na hora, meu amigo.

Each input="file" Jquery não valida


(How much) should I focus on sight reading if my end goal is being able to play by ear on piano?

Question: So my technical ability is ahead of my sight reading ability. And I haven't practiced my ear at all. My end goal is to eventually be able to play any song by ear and put my own variation on it. I'm not good at sight reading at all. I can read the notes but it does take me a while to get them all in my head. I don't care much for sight reading either, although I feel like I should at least master the basics.
Now my question is, should I continue practicing sight reading first before I practice ear training? Are there any big benefits in sight reading and does it help me improve in other aspects of playing the piano as well? Should I practice both simultaneously? Or should I just neglect sight reading alltogether and just focus on ear training and relative pitch if that's my end goal?
I always fiddled around with the piano as a child and would watch tutorials for songs online. That's why my technical ability is far ahead of everything else. I only recently started learning about the music theory behind it and how to read notes etc.
Comment: Do you mean you want to improvise piano _arrangements_ of songs, where the vocal part of the song will be played instrumentally on the piano? That contrasted with playing the _piano part_ of song.
Comment: @MichaelCurtis Yes that's what I mean!
Comment: @Tipsi - Usually the term _sight reading_ means performing having never seen the sheet music before. After that first play-through it's not _sight reading_ any more, it's just plain _reading_. In your question do you mean _reading_ or _sight reading_? Proper _sight reading_ is a hugely useful skill in its own right, but it's predicated on the skill of _reading_.
Answer: If you want to be able to pick up on a song by ear, sight reading won't be a lot of help. (Downvoters - please say why you did!).
Since your aim is to play by ear, and hit whatever notes and chords instinctively, then being able to read charts won't help at all.
As long as you are aware of what each chord comprises, and how they work with each other, and can play a bass line that flows, and use your ears for instant accuracy, carry on playing the way you do, as sight reading is a very different and diverse skill from playing by ear. Generally speaking, I find that players fall into one of the camps  - great sight readers, or great 'play by earers'. There are very few players that I've worked with who are very good at both. I guess if one is better at one, then that gets favoured over the other, and strengthens more to the detriment of the other.
Looking at and considering the comments and answers - it would be worth a foray into sight reading. It might just be that, as you already have a way round the notes, that looking at how it's portrayed on the lines and spaces, it suddenly becomes pretty obvious how it all works. And you start thinking - actually, it's easier than I thought, I'll have a go. Certainly worth consideration. 'Cos then you have that extra bow to your fiddle, or whatever the phrase may be today...
EDIT: something that will help you playing by ear is to know several scales, in many keys. Reason for this is that when you've found/decided on a key for a piece, and are aware of whether it's using say, blues scale, pent. scale, minor scale notes, it usually automatically means certain notes won't be played. So you will save time and effort not even trying those notes. Simple example, in key C, chances are you won't be needing D♭.
Comment: I definitely do want to get the basics down for reading sheet music. But another big reason why I still use sheet music is because my ear isn't trained well enough to play very technically demanding pieces of music. And isn't it important to still play music that matches with my technical ability?

I either continue reading sheet music on the side in order to play more technically demanding songs, or I only practice playing by ear and start with easier songs. Another option is to watch youtube tutorials like I used to do, but I doubt that's a good idea.
Comment: If today's requirement is to play a particular song, don't be ashamed to use any resources you can find!  For the broader requirement of developing your personal skills, do anything that broadens your musical horizons.  (Why are you restricting your ambitions to being a 'busker' anyway?)
Comment: @Laurence I'm not planning on competing or becoming an actual performer. I'm learning to play the piano because I love how it feels when I am playing. I barely like classical music, only modern classical music really. Most songs I do like don't have sheet music availabe and aren't as hard as classical music. That's why playing by ear is my goal. I'd rather be really good at 1 method than decent at all methods.
Comment: Far be it from me to question your goal... but I'm going to anyway!   No, your goal is playing the music.  Playing by ear is merely a method, one route to that goal.
Comment: @LaurencePayne Sure but my goal can still be to play music by ear. I want to eventually be able to hear a song and instantly play it without having to read sheet music. I'm aware that there is plenty of music that I won't be able to do this with. For example with alot of classical music. And I might not get it right 100%, but that IS my goal. Another reason for this is because alot of music I often want to play, doesn't have any sheet music available for it. Playing by ear will help with this as well.
Comment: @Tipsi classical music can also be played by ear. Classical musicians like Bach were improvisers first and foremost, sheet music was just a way to "record" what they did but they didn't actually learn their craft with sheet music, they learned it from partimento improvisation.
Answer: You can only play 'by ear' using musical elements that you're familiar with.  So you need to get familiar with LOTS of music, in LOTS of styles - what it sounds like, and what your fingers have to do to get that sound.
Sorry, @Tim, but by far the most efficient way to do this is by reading lots of music. Not necessarily by perfecting a small number of difficult pieces (though you need technique too.)
Develop your 'by ear' playing skills AND your sightreading skills.  They will nurture each other.  Remember, the aim is to play the piece.  If the printed music is available, it's foolish to reject that route!
Comment: I've played with many people who couldn't read, but were able to play hundreds of tunes that were in their minds - and could also play along with something never heard before, because they could play by ear. A lot of the stuff I do, and always have done, has been by ear, and I don't think knowing how to sight-read - which I can - helped that side much. Agree to disagree. But it is good to be able to do both. OP wants to know which direction to go, and he's given both sides of the coin with answers here! Probably hasn't time to do all though. And since play by ear is more natural, go that way.
Comment: "the most efficient way to do this is by reading lots of music" - true if you already have those sight reading skills. But if you are someone who enjoys trying to figure things out by ear more than reading scores, acquiring those skills might come at a relatively high opportunity cost.
Comment: Given the actual question details - 'haven't practiced my ear at all' and 'not good at sight reading at all' - and the OP sort of supposing them to be mutually exclusive, this really is the best answer. Being able to read a songbook will help immensely. It can also _confirm_ what they do by ear. Don't overlook that fact that  'by ear efforts' can actually lead to _mistakes about what the actual notes are_! (How many garbage guitar tabs online where made by ear?)
Comment: Yeah.  All these barriers people set up about the methods they DON'T want to use to develop and learn.    Get in a situation where a paying gig depends on being able to play 10 new songs by Saturday.  You'll soon stop being picky about the learning method!
Comment: @LaurencePayne - been there, done it, never been desperate enough to want to rely on readily available 'tabs', as unlearning something learned wrongly is even more time-costly.
Comment: Yes, all sources must be checked, criticised and corrected.  Sometimes it's interesting to see what the composer wanted before a performer tore it to bits (yes, I'm looking at you, Ms. Streisand). Sometimes a published song copy can be a very poor transcription. Sometimes a tab can reveal something beyond the scope of chord symbols.  Often notation will show a chord that was outside your experience, therefore it would have been hard to 'busk'. But it's no big deal to put something right, even if you've been playing it wrong for years. Have a bit more confidence in your skill!
Answer: Before I start, I will mention that I can really only play (guitar, sing and drums) by ear. If I learn from something written down, I'm much slower and can't read music so it has to be tab or chord notation. In honesty, I've never needed to go further than this in order to get a LOT of enjoyment from music.
Learning a piece by ear is ace fun, and you'll get probably 90% of popular tunes easily. However when you get to something that's hard to hear (!) in detail, you probably need to see it written down.
The difference is that 'by ear' gives you a feel for it, and a good hint at a piece. Seeing it written down tells you THE CORRRECT THING TO PLAY.
However this doesn't necessarily mean sight-reading. It could be just reading the notes of a tricky part and getting them sorted at your own pace, then getting the rest right by ear.
Perhaps it depends on the kind of music you're playing. If you're playing popular tunes, or something jazzy etc then by-ear is usually enough detail to get them learnt. If you're playing tricky classical pieces with intricate arpeggias etc, then maybe getting the right detail becomes more important.
Incidentally, I'm in awe of people who can sight-read. It's not something I aspire to myself because I enjoy the freedom of playing things how I hear them rather than being too dictated-to. But watching someone sight read a piece is to me quite astonishing.
I've had the same thing said by sight-readers about those who can play by ear, which underlines Tim's answer.
Answer: There is a common misconception on what "playing by ear" is.  Many people think it is knowing what a melody is then hunting and pecking on your instrument for the correct notes.  One wouldn't walk through a mine field like that so why would we attempt to perform like that? Because you probably know how to read and sound out words, I can say "cat" and you will be able to guess KAT or CAT or maybe even QHUAT. That is because you have mastered the alphabet and sounding out with your mind's ear.
True playing by ear is more cerebral than you think.  It involves knowing all your scales, some degree of music theory and the ability to see the notes in your mind's eye when you hear them.  Here is what I mean.
I can hear the tune ODE TO JOY in my head.  Because I sing a lot but sing by visualizing sheet music (usually by the pool)  in my head, I just know that the melody starts on the third.  I can hear it start on the third.  From there, as I hear each pitch, I just know what the numeric values are:
33455432 1123322 33455432 1123211
As I hum, I simply know those corresponding numbers because I only think in numbers. An added benefit to reading by numbers and not letters is that I can then transpose that into any key.  Just start on the third of any scale and play those numbers.  Poof, you're a genius.  If I am improvising and I wish to quote this melody, I only have to aim for the third. There is no hunt and peck, there is no guessing, there is no "playing by ear." It is all brain conversion from inner ear.
The good news is that you can practice this anywhere without the need for a piano.  Lying in bed, driving a car, lounging by the pool, hiking through the woods, listening to the homily . . . Also, whenever you hear music, don't just hum along, listen or ignore it, use it to practice.  What is the starting pitch?  Is it on the 1, 3, 5?  Does the bridge change keys a fourth higher?  What is the chord progression? You can hear all these things and translate them to numbers on the fly. WITH PRACTICE.
Some teachers teach the solfege method but I find numbers easier and if I am jamming with other musicians I can just hold up a finger. I can't hold up a SOL.
Try it with something simple such as MARY HAD A LITTLE LAMB.  It starts on the third.  Don't use just your ear, employ the brain. Don't guess, know. I'll wait.  My brain tells me the pitches are 3212333 222 355 3212333322321.  Did you get those too? Go test them on the piano in any key.
Now, someone is going to chime in saying "That is fine and dandy for melody but you can't do that with larger works, fugues or etudes." What they are really saying is THEY can't do it.  Because I only read by numbers I can see all the numbers.  If they read by letters, they see letters. I can't fly an airplane so therefore nobody can. All you need to do is know your scales and intervals and what each interval sounds like - away from the piano.
As an added bonus, you will find memorization to come rather quickly.  Actually you are not "memorizing" notes.  Your ear will hear and you'll just know or read in your mind. I don't  have GOLDILOCKS AND THE THREE BEARS memorized but I can fake the story.
This will be offensive to many people but I consider letter readers to be musically illiterate.  Like, they can speak but not read. My folk group musicians are all excellent readers.  They can play anything I put before them. However, if I ask them to raise it a third, they can't.  Why?  They really don't know what they are doing. Matching dots to a key is so easy a parrot can do it.  In the following video, I doubt the bird knows what a square, circle or isosceles trapezium is.  This bird is not genius, it is just matching shapes like it was trained to do.  BTW, this is how Beethoven could compose while deaf. His ear may have been deaf but his brain wasn't. Go ahead, "hum" something in your brain.  What were the numbers?
Parrot matches shapes
A good way to practice is to go steal a hymnbook from your local Protestant church (God will forgive you) and away from the piano, number sing all four parts.  Start with just one line at a time (SAT or B).  Soon you will see all four parts by their numbers.  Hymns are great to start with because they rarely go beyond and octave, the notes are repetitive, the form is often AABA and all the notes are chord tones.  Study, study, study, study, study.  Then sit at the piano.  Oh, if you don't want to beg, borrow or steal, you can check out hymnary.org but taking a book with you means you can "practice" anywhere, anytime.
Comment: I agree with much of what you say (+1), but once someone is familiar enough with an instrument, I think it is often possible for then to just pick out the notes of a melody they've heard without analysing it first. Many people without the musical training to identify intervals can sing a melody back correctly, isn't doing the equivalent on the guitar a similar skill?
Comment: While there's a lot of interesting food for thought in this answer, I don't see how it answers the question. Instead, it's an essay about what comprises music literacy in your opinion. (I happen to agree with a lot of what's written here, but that's not the point.) It'd also be a much better answer if it were less confrontational ("offensive to many people") and more helpful (e.g., "this is a method that works well for me"). I hope this helps improve the answer!
Comment: Can you figure out the numbers for less tonal pieces? I guess you can for 12-tone serialist pieces, but I once transcribed a piece that had the F7/Eb - G7/F - Ab/Bb - G/A chord progression at one point, and I suspect passages like this raise difficulties when trying to assign note numbers to them.
Answer:
My end goal is to eventually be able to play any song by ear and put
  my own variation on it.

Same here that was my goal too, esp if you're into improvising and composing you need to play by ear mainly. Even the Beatles didn't know how to read music.
I played piano as a kid for years reading sheet music, played guitar for a few more years without knowing much theory, just jamming around to random tabs and improvising random patterns. It took me about 10 years to realize I had learned music all wrong.
I had an epiphany when I realized that music should be played just like we whistle, using muscle memory. Another epiphany came to me when I realized that all major scales are simply shifted in pitch but are essentially the same pattern "do re mi fa so etc", that and that 80% or so songs are in major. Then another epiphany when I realized I've always had a propensity for the minor scale, and more epiphanies along the way.
I then went back to a piano and took it upon myself to play by ear hundreds of songs that I always had in my mind throughout life and ask any question I had on this site. It took me about two years of about 3-4 hours a day but I was committed. Just knowing as many songs as you can, that you personally like and what makes them tick. So like what scales and chords they're using. But not focusing on chords names, more so focusing on their function and relative notation (I, ii, IV, V7, etc) so that you can play them in other keys.
My biggest suggestion is to take very easy songs and play them in all keys. It's like playing scales but practicing scales limits you to playing minor second and major second intervals. That's not enough. So take a tune, for example "Amazing Grace" and play it in all keys. That way you start developing your muscle memory to what different intervals sound like, and you start training yourself to know where
 the notes and chords are in all keys.
At first it can take days to figure out a song but with enough practice it then takes minutes, or even seconds.
Also the only thing you need is a piece of paper and write what songs you know on it. And constantly work and refine them and add more songs to that list. There are still old songs I know that I'm constantly fitting new harmonies in and polishing what they sound like, adding embellishments, etc.
But you need theory if you go by ear: so know how to create a scale, know how to get chords from a scale, play major/minor, etc. Once you have theory + ear then you have music. You'll hear ANY song on the radio and you'll know how to recreate it instantly when you have a keyboard next to you, and you'll be able to improvise your own music, it's very liberating. You'll begin to appreciate how every song around you follows the same basic rules.
Comment: @Tipsi absolutely always start with melody (that will indicate your scale) then to harmonize it try I IV or V chords of your scale. Keep in mind that there's many ways to harmonize a melody. The more harmonic vocabulary you build via theory the better. As far as the higher/lower that will go away with time after you build muscle memory. Meaning you will internalize how an interval sounds and you'll know what key to what key to play. With time it just gets better and better and that's when the real fun starts.
Comment: I tried to play a few songs by ear yesterday. It went well-ish. I got the chorus of 1 song in just 10 minutes. But I often pressed a note, thought to myself "Hmm.. It should be higher"  and just keep repeating until I had the right melody. This isn't really playing by ear imo. But hopefully it will help get me there. I'm also not sure whether I should get the chords or melody first. Melody seems quite easy and I often do guess the notes right. However chords for me is just playing all the chords available in that scale until it sounds right.
Answer: Playing by ear is only possible when you have the patterns you wish to identify already adapted. If not - you will lose much time to to find them out by trial and error. These patterns can be melodic, rhythmic and harmonic ones.
If you are able to identify the chords (and the chord progressions) you will easily be able to find out the tune or even improvise to these chords. (Understanding and following the rhythm will probably the lesser afford.)
That means: sight reading will always be a help! It is like reading, writing and speaking in general a feedback process that will always benefit.
Try to play along a tune or the chords to a record. It's a good practice.
So the most important would be to learn chord patterns as posted here:
Is there a set of closely related keys in modern popular music?
and by studying harmony (not on a professional level, but just by this examples above.)


Subprocess.check_output does nothing for node.js on windows?

Question: I've got a strange problem with my automated minify tool. I had to replace yuicompressor with csso, since yuicompressor hasn't updated since 2013 and has many bugs with newer css selectors.
This has increased the complexity (as in amount of involved "stuff") to the point where I have no idea how to debug an issue with the command executed. (Or even if it got executed).
I've basically got my problem narrowed down to the following python code snippet (currently with a lot of added debug statements to help diagnose the problem):
print("node " + os.path.join(getScriptPath(), "css", "csso", "bin", "csso")
    + " -i " + os.path.join(root, name) + " -o " + os.path.join(root, outname) + " --debug")
os.remove(os.path.join(root, outname))
try:
    result = subprocess.check_output(["node",
        os.path.join(getScriptPath(), "css", "csso", "bin", "csso"),
        "-i", os.path.join(root, name),
        "-o", os.path.join(root, outname),
        "--debug"
        ], stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as exc:
    print("ERROR: Failed to execute CSSO with error:", exc.returncode, exc.output)

Note here that getScriptPath() is a small helper function that returns the current path the script file is in. csso is installed by copying the files manually under css/csso/bin/csso. name is a string holding the relative path to the original css file (usually something like ../../domains\mydomain.com\templates\css\style.css), while outname is always the same as name, but with the extension changed to .min.css.
If I copy & paste the result of the first print() call directly in a cmd terminal, csso will run and minify my file. But, if I call a batch script that runs a python program that eventually runs the code above (as part of the things it does), nothing is done, with no output.
The subprocess.run call used to be a simple shell call, which would have no output. Yet, I still get no output. Here's some example output I'm getting by manually running it (in stderr):
## parsing done in 16 ms

Compress block #1
[0.000s] init
[0.000s] clean
[0.015s] replace
[0.000s] prepare
[0.000s] mergeAtrule
[0.000s] initialMergeRuleset
[0.000s] disjoinRuleset
[0.016s] restructShorthand
[0.000s] restructBlock
[0.000s] mergeRuleset
[0.016s] restructRuleset
## compress done in 47 ms

## generate done in 0 ms

(The current output from the python version appears empty. If it contains any data, all the bytes are printed as empty in the standard cmd tool).
One idea: is there a way to get subprocess.run (or shell) to echo back the exact command it executed, and from exactly which path, so I can replicate it manually and at least exclude any mistakes in constructing the command or diffrences in quotes, etc? Ideally probably as a binary file, as this looks like 'two things appear exactly the same but aren't' fun.
Other relevant tags:
batch, minify.
Answer: I've managed to diagnose the problem.
On windows, there are somehow multiple different PATH variables. The machine where the problem occurred had not rebooted after installing node.js, and the PATH was available for cmd directly, but not to python, which still used the old variable. Hence it got an error; node doesn't exist.
For some reason still unknown to me that error was silenced with the original code. But, adding these two lines in between (indicated by >>>) would cause the program to print the results of both commands (instead of neither):
 >>> result2 = subprocess.check_output("echo \"Hello World\"", stderr=subprocess.STDOUT, shell=True)
    except subprocess.CalledProcessError as exc:
        print("ERROR: Failed to execute CSSO with error:", exc.returncode, exc.output)
    print(result.decode())
    >>> print(result2.decode())


Views Filters: show published items from the last week or minimum number of items

Question: The homepage on our local newswebsite "Zee-Online" has a view that shows al published content from the last week. How can i change this, to show at least a fixed number of items?
I want a view that gives me all the nodes from the last week OR at least 12 items (if the first filter-criteria doesn't result in at least 12 items)
Comment: items per page could set a maximum. You might have to use php for the 'or' condition.
Comment: I don't want a maximum! If there are less then 12 items published in the last week, it should display older items to get the minimum of twelve.
Answer: Since you're trying to create a Views filter using an "OR" relationship, you might want to consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

... provides a views plugin which modify query to support OR conditions for contextual filters.

Does this help?
Comment: There's an OR relationship in the views module, but i can't configure a way to display the 12 most recent items. (and second clausule is OR published in the last week). Now i solved the problem using an Attachment in the view. We use the masonry views module on our page. It's almost what i want, but not perfect. The items in the attachment doesn't align with the masonry layout in the view.... (www.zee-online.be) (you can see where the attachment starts)
Comment: There's another problem: There are duplicate results in the page and attachment, but the query-settings => distinct doesn't solve the problem?


OLS vs IV estimates - Sign and Significance

Question: Assume I have an equation with 1 endogenous variable, and many other exogenous variables. Also assume I have 2 valid instruments for the endogenous variable for IV estimation.
If I were to estimate this equation by OLS estimation and IV estimation , would I expect the sign of the EXOGENOUS variables and statistical significance to remain the same?
For a particular exogenous variable, if the signs and statistical significance under OLS and IV are the same, then why is this the case?
Comment: Regarding the second question, this "particular variable" is again an exogenous variable?
Comment: Yes it is exogenous
Answer: My answer is caveated by the questions "Remain the same" as what exactly? and What precisely do you mean by "expect?"
Assuming you mean if you compare the results of an (uninstrumented, single stage) and an instrumental variables regression of the same outcome, and by "expect" you are asking about the possibility of sign and significance changes, then:
No. It is very possible that both sign and $p$-value changes. The possibility of changing sign underscores why directed acyclic graphs and the analytic methods accompanying counterfactual interpretations of causality are worth thinking hard about, and also underscores the usefulness of instrumental variables regression in helping to provide unbiased causal estimates if their assumptions are met. If I understand your question correctly, then the below signed DAG represents one possible scenario, where $O$ is the dependent variable, $X$ is an endogenous variable, $Z_{1}$ and $Z_{2}$ are exogenous variables, $U$ is unobserved, time flows from left to right, the arrows with pointed heads mean "causes an increase in (the probability of)", and the arrow with a round head means "causes a decrease in (the probability of)." Here both $Z_{2}$ and $U$ confound $E(O|X)$ as an unbiased estimator of the true causal effect of $X$ on $O$. Adjusting the regression by $Z_{2}$ removes the bias from $Z_{2}$, but that from $U$ remains. Given an exogenous predictor like $Z_{1}$, we could obtain an unbiased estimate of the true causal effect of $X$ on $O$ using $\hat{X}$ (as predicted by $Z_{1}$).
Sign change in the endogenous case:Because the effect of $U$ on $O$ is negative, $U$ specifically biases $E(O|X)$ downward; whether the bias takes $E(O|X)$ only towards 0, or past 0 and into negatives (sign-switch) depends on the relative magnitude on the effects of $X$ on $O$, $U$ on $X$ and $U$ on $O$.
Sign change in the exogenous case:Because $X$ is a causal "collider" for $Z_{1}$ and $Z_{2}$, instrumenting $X$ only on $Z_{1}$ produces biased estimates both for the effect of $X$ on $O$, and for the effect of $Z_{2}$ on $O$:
For OLS ($O \sim 1 + Z_{1} + Z_{2} + X$):

A larger causal effect of $Z_{1}$ on $X$ relative to the causal effect of $Z_{2}$ on $X$, biases $\beta_{Z_{1}}$ to increase, and biases $\beta_{Z_{2}}$ toward 0.
A smaller causal effect of $Z_{1}$ on $X$ relative to the causal effect of $Z_{2}$ on $X$, biases $\beta_{Z_{1}}$ downward (possibly into negatives/switching signs) and biases $\beta_{Z_{2}}$ downward (possibly into negatives/switching signs).

For IVR ($O\sim 1 + \hat{X} + Z_{2}$; $\hat{X} \sim 1 + Z_{1}$):

A larger causal effect of $Z_{1}$ on $X$ relative to the causal effect of $Z_{2}$ on $X$, $\beta_{Z_{2}}$ is biased to estimate above its true direct causal effect; $\beta_{\hat{X}}$ is a nearly unbiased causal estimate of the effect of $X$ on $O$ (slightly towards zero).
A smaller causal effect of $Z_{1}$ on $X$ relative to the causal effect of $Z_{2}$ on $X$, $\beta_{Z_{2}}$ is biased to estimate above its the true (direct) causal effect; $\beta_{\hat{X}}$ is biased towards zero.

For IVR ($O\sim 1 + \hat{X} + Z_{2}$; $\hat{X} \sim 1 + Z_{1} + Z_{2}$):

A larger causal effect of $Z_{1}$ on $X$ relative to the causal effect of $Z_{2}$ on $X$, $\beta_{Z_{2}}$ is a nearly unbiased estimate the true direct causal effect of $Z_{2}$ on $O$; $\beta_{\hat{X}}$ is a nearly unbiased estimate of the true causal effect of $X$ on $O$.
A smaller causal effect of $Z_{1}$ on $X$ relative to the causal effect of $Z_{2}$ on $X$, $\beta_{Z_{2}}$ is biased to estimate below its the true (direct) causal effect (possibly into negatives/switching signs); $\beta_{\hat{X}}$ is slightly biased to overestimate estimate of the true causal effect of $X$ on $O$.

In the first case for all three models, where the true causal effect of $Z_{1}$ on $X$ is larger than that of $Z_{2}$ on $X$, any biases of $\beta_{Z_{2}}$ do not switch the sign, and the magnitude of the estimate can be different or the same for each model depending on the difference in magnitudes of the true effects of $Z_{1}$ and $Z_{2}$ on $X$.
In the second case for all three models, where the true causal effect of $Z_{1}$ on $X$ is smaller than that of $Z_{2}$ on $X$, the biases of $\beta_{Z_{2}}$ are all capable of switching the sign but the downward bias is different for each model such that the term may be negative in OLS, but positive in one or both of the IVR models.

Even if the sign does not change, one would expect the $p$-value of the endogenous variable to change more often than not, as two-stage IV regression necessarily sacrifices variance and therefore statistical power in the instrumented variable (so in the provided example, specifically $s^{2}_{\hat{X}} < s^{2}_{X}$, because we dispense with the portion of the variance of $X$ that is not explained by $Z_{1}$). One could see the $p$-value of the exogenous effects (e.g., $\beta_{Z_{2}}$) to change between models because the effect itself changes, or not change because the effects are similar.
Of course the signs do not necessarily have to change (again, it will depend on the relative magnitudes), and the loss of variance in an instrumented predictor ($p$-values increase) may be offset by better model fit due to decrease in bias from that predictor ($p$-values decrease).
Comment: All of this seems a little superficial as it does not explain why and when an exogenous variable in an IV regression would change sign or significance. Endogeneity often causes a bias in all variables but it does not occur if an exogenous variable is uncorrelated with the endogenous variable, so in this case one wouldn't expect a change in sign and significance. An exogenous variable that is correlated with the endogenous variable may well change sign and significance. The loss of efficiency due to instrumenting mainly affects the instrumented variable though.
Comment: @Andy The OP's question was broad. She did not provide quantities, or a causal graph. Nor did she specify whether or how the exogenenous and endogenous variables were correlated or not. A general answer seems appropriate. I am having trouble parsing "Endogeneity often causes a bias in all variables but it does not occur if an exogenous variable is uncorrelated with the endogenous variable" what is the **it** in "it does not occur?"
Comment: "It" being the "bias" of an exogenous variable that is correlated with an endogenous variable. A general answer is fine but it should address the OP's questions which are not as general as you say. In the first part you state that sign and significance of an exogenous variable in this setting can change. I would upvote an answer that also explains why. In the second part you say that sign and significance don't necessarily change. I would upvote an answer that says when this is the case. What you write about the efficiency of the instrumented variable doesn't answer these questions.
Comment: @Andy I hope that is better.


bootstrap typeahead return name and id

Question: Hy! I'm using twitter bootstraps typeahead:
I'm calling a page that returns a response with json_encode
the page returns a name and an ID,
I want that the typeahead list will show me the list of names,
and when I select one of the name
to write the id value to a hidden field.
the calling works fine, and to write a field should be easy.
what i dont know what to do is how to divide the name from the id.
now, when i search something, in the suggesstion list I can see the returning results like this:
name1:id1
name2:id2
i only want to see names but to carry the value of id too.
how can i do that?
 $(function(){
    $("#typeahead_<? print $key; ?>").typeahead(
        {
        source: function(query, process)
                    {
                    $.ajax({
                        url:    '/getAjaxProducts',
                        type:   'POST',
                        data:   'query=' + query,
                        dataType: 'JSON',
                        async: true,
                        success: function(data)
                                {
                                process(data);
                                }
                            });
                    }
        });
});

Answer: A typical JSON document that contains name/ID pairs is going to look like this:
[
  {
    "id": 1
    "name": "firstName"
  },
  {
    "id": 2
    "name": "secondName"
  }
]

The strategy here is to build an object literal that maps names to IDs as you parse the result, while only using the name to populate the typeahead:
var productNames = new Array();
var productIds = new Object();
$.getJSON( '/getAjaxProducts', null,
        function ( jsonData )
        {
            $.each( jsonData, function ( index, product )
            {
                productNames.push( product.name );
                productIds[product.name] = product.id;
            } );
            $( '#product' ).typeahead( { source:productNames } );
        } );

Once the user selects an item from the typeahead, you can reference the selected item with:
$( '#product' ).val()

and you can get the ID associated with the selected item with:
productIds[$( '#product' ).val()]

From your question, it looks like your JSON document may be structured a little bit differently, so you would change the parsing as appropriate, but the same general strategy applies.
Comment: This solution implies that the names are unique. In most cases they probably are, but I felt that I needed to point that out.
Comment: I can't imagine what the use-case would be for a situation where the names are not unique. This means you would have two identical options in the dropdown, with no means for the end-user to differentiate between them. How would the user know what to select?
Comment: The use case would be a situation where you have people's names, like John James and Bill Johnson. You could differentiate for the user by rendering custom templates with profile pictures (so, your JSON might need to have fields for id, name, and profile pic URL).
Comment: With the latest typeahead.js it's local:productNames rather than source:productNames.
Comment: This solution loaded all the data at once right? As I don't see the `query` parameter. There would be an issue if the backend only return certain amount of data. I.E. you have to assign query parameter for more specific data.
Answer: Sorry to "resurect" this post but i was going to be crazy !
If some of you have problems using theses sample codes ( none of them were working, all were returning "Undefined" instead of showing the name
Just add
displayKey: 'name',

Replace of course 'name' by your label var name returned by your remote source
( Quite hard to find up to date samples on it, most of samples found on the net are for the previous version of typeahead and not compatibles with new ones ... )
Comment: This is the correct approach. Any solution that relies on the displayed string will break easily.
Answer: ......updater: function (item) {
        var item = JSON.parse(item);
        console.log(item.name);
        $('#VehicleAssignedTechId').val(item.id);
        return item.name;
    }

On updater of the typeahead call you can put as above code which allows you to add selcted value in the textbox or where you have to put its value in other hidden field.
Full ajax call is as below:
$('#VehicleAssignedTechName').typeahead({
    source: function(query, process) {
        var $url =SITE_URL+ 'api/vehicle_techfield_typeahead/' + query + '.json';
        var $items = new Array;
        $items = [""];
        $.ajax({
            url: $url,
            dataType: "json",
            type: "POST",
            success: function(data) {
                console.log(data);
                $.map(data, function(data){
                    var group;
                    group = {
                        id: data.id,
                        name: data.name,
                        toString: function () {
                            return JSON.stringify(this);
                            //return this.app;
                        },
                        toLowerCase: function () {
                            return this.name.toLowerCase();
                        },
                        indexOf: function (string) {
                            return String.prototype.indexOf.apply(this.name, arguments);
                        },
                        replace: function (string) {
                            var value = '';
                            value +=  this.name;
                            if(typeof(this.level) != 'undefined') {
                                value += ' ';
                                value += this.level;
                                value += '';
                            }
                            return String.prototype.replace.apply('
' + value + '
', arguments);
                        }
                    };
                    $items.push(group);
                });

                process($items);
            }
        });
    },
    property: 'name',
    items: 10,
    minLength: 2,
    updater: function (item) {
        var item = JSON.parse(item);
        console.log(item.name);
        $('#VehicleAssignedTechId').val(item.id);
        return item.name;
    }
});

Comment: useful, thanks. Just also need add substr method. substr: function(string) {
                          return String.prototype.substr.apply(this.name, arguments);
                        }
Answer: My solution is:
var productNames = new Array();
var productIds = new Object();
$.getJSON( '/getAjaxProducts', null,
        function ( jsonData )
        {
            $.each( jsonData, function ( index, product )
            {
                productNames.push( product.id + product.name );
                productIds[product.id + product.name] = product.id;
            } );
            $( '#product' ).typeahead( { source:productNames } );
        } );

In my case, product.id is a code, so it is useful to display it in typeahead control. In this way i avoided duplicated names risk.
Answer: I noticed when using this code that if the match included the letters 'st', the typeahead suggestions include the style tag in the typeahead suggestions.
For example the suggested matches would show

style="padding: 10px; font-size: 1.5em;">standard

instead of

standard

I changed the replace function to this:
replace: function (string) {
  return String.prototype.replace.apply(this.name, arguments);
}

Obviously you lose the additional formatting, but it doesn't break on 'st' matches (I assume it would also break on 'di', or other substrings of the div tag.
Answer: I had the same issue when i tried to process username and id.I had a tricky fix but later on i have fixed it with proper solution.
Have a look at this one,
$('#search').typeahead({
 source: function(query, process) {
 var $url = "/controller/function/list_users/?q="+query;
 var $datas = new Array;
 $datas = [""];
 $.ajax({
 url: $url,
 dataType: "json",
 type: "GET",
 success: function(data) {
 $.map(data, function(data){
 var group;
 group = {
 id: data.id,
 name: data.user_name,
 toString: function () {
 return JSON.stringify(this);
 //return this.variable;
 },
 toLowerCase: function () {
 return this.name.toLowerCase();
 },
 indexOf: function (string) {
 return String.prototype.indexOf.apply(this.name, arguments);
 },
 replace: function (string) {
 var value = '';
 value += this.name;
 if(typeof(this.name) != 'undefined') {
 value += ' ';
 //value += this.name;
 value += '';
 }
 return String.prototype.replace.apply('
' + value + '
', arguments);
 }
 };
 $datas.push(group);
 });
process($datas);
 }
 });
 },
 property: 'user_name',
 items: 10,
 minLength: 2,
 updater: function (item) {
 var item = JSON.parse(item);
 $('#hiddenId').val(item.id);
 $('#username').val(item.name);
//you can perform your actions here
//example

//location = '/controller/function/'+item.id+'/edit';
 //document.redirect = location;
}
});

look at this link also.
http://vaisakhvm.wordpress.com/2013/07/31/twitter-bootstrap-typeahead-process-multiple-values/

bootstrap typeahead return name and id


probability of drawing two card simultaneously

Question: For e.g what is the probability that both card drawn from a deck of card will be king.
Is drawing two card simultaneously and drawing one after the other(not replaced back), the same thing.
Because when we draw two card simultaneously, isn't their probability that they will be king should be same i.e 4/52 * 4/52.
I know the probability when two card are drawn one after the other is 4/52 * 3/51.
Thanks.
Comment: If in real world you pick two cards "simultaneously" then I bet that one of the cards can be labeled as the one that was touched by your fingers as first. So there is always an order. Even if this order seems to be absent in the abstract setting then you can build in some order yourself. That can be fruitful in many situations.
Answer: Two cards drawn simultaneously is the same as drawing one card after the other without replacement. Specifically, if you draw two cards simultaneously, the two cannot be the same card.
Answer: Yes it is the same thing.
In both situations, picking a certain card will prevent you from picking that same card as your "second" card. And here "second" doesn't necessarily mean you pick it afterwards. The point is that, even if you pick it at the same time as the first, it still can't be the same as the first. And that restriction is what makes the probability be $\frac{4}{52}\times\frac{3}{51}$ in either case


Find the length of the tangent to the curve $x^{\frac{2}{3}}+y^{\frac{2}{3}}=a^{\frac{2}{3}}$ which is intercepted between the axes.

Question:
Find the length of the tangent to the curve $x^{\frac{2}{3}}+y^{\frac{2}{3}}=a^{\frac{2}{3}}$ which is intercepted between the axes.

$x^{\frac{2}{3}}+y^{\frac{2}{3}}=a^{\frac{2}{3}}\implies \frac{dy}{dx}={(\frac{-y}{x})}^{\frac{1}{3}}$.
Slope at $(p,q)$ will be ${(\frac{-q}{p})}^{\frac{1}{3}}$.
So equation of tangent at $(p,q);$ $y-q={(\frac{-q}{p})}^{\frac{1}{3}}(x-p)$.
How to find the length of tangent intercepted in between the axes from here?
Answer: Now, if $x=0$ we obtain $y=q+\sqrt[3]{qp^2}$ and for $y=0$ we obtain $x=p+\sqrt[3]{pq^2}.$
Thus, $A\left(p+\sqrt[3]{pq^2},0\right)$ and $B\left(0,q+\sqrt[3]{qp^2}\right)$ they are intersection points of the tangent with $x$-axis and with $y$- axis respectively.
Id est, $$AB=\sqrt{\left(p+\sqrt[3]{pq^2}\right)^2+\left( q+\sqrt[3]{qp^2}\right)^2}=$$
$$=\sqrt{p^{\frac{2}{3}}\left(p^{\frac{2}{3}}+q^{\frac{2}{3}}\right)^2+q^{\frac{2}{3}}\left(q^{\frac{2}{3}}+p^{\frac{2}{3}}\right)^2}=
p^{\frac{2}{3}}+q^{\frac{2}{3}}=a^{\frac{2}{3}}.$$
Answer: Any point on $$x^{2/n}+y^{2/n}=a^{2/n}\ \  \ \ (1)$$ can be chosen as $(a\cos^nt,a\sin^nt)$
Differentiating $(1)$ wrt $x,$  $$\dfrac{dy}{dx}=-\dfrac{x^{(2-n)/n}}{y^{(2-n)/n}}$$
$$\dfrac{dy}{dx}_{\text{ at }(a\cos^nt,a\sin^nt)}=-\dfrac{x^{(2-n)/n}}{y^{(2-n)/n}}=-\dfrac{\cos^{2-n}t}{\sin^{2-n}t}$$
So, the equation of the tangent at $(a\cos^nt,a\sin^nt)$ will be $$\dfrac{y-a\sin^nt}{x-a\cos^nt}=-\dfrac{\cos^2t\sin^nt}{\sin^2t\cos^nt}$$
$$\iff x\cos^2t\sin^nt+y\sin^2t\cos^nt=a\cos^nt\sin^nt$$
$$\iff\dfrac x{\cos^{n-2}t}+\dfrac y{\sin^{n-2}t}=1$$
Here $n=3$
Can you take it from here?
See also: intercept form


Binary logistic regression with two continuous independent variables with different dimensions

Question: I have a binary dependent variable (1/0) and two continuous independent variables that are in different dimensions, one is in kilometers and the other is in years. I used Minitab and binary logistic regression.
Of course, the results haven't been trustworthy especially considering error.
It is obvious that the reason of this is that data are in different dimensions, therefore in different sizes as well. I understand that I should do coding of these independent data, but how?
Comment: I'm not sure what you mean by "the results haven't been trustworthy". The units that the independent variables will not affect your predictions or the fit of your model, just the units of the coefficient.

When people want to be able to directly compare the effects of two variables in different units, they will sometimes standardize the variables by subtracting off the mean and dividing by the standard deviation. Again, this won't change the predictions, it will just allow you to interpre coefficients in terms of s.d. differences rather than km / years.
Comment: No "of course" or "obvious" here unless you can demonstrate instability somehow (e.g. by showing different results from different programs). Reputable programs are careful about numerical analysis.
Answer: The units or the scale does not affect what is predicted by the model, in  logistic regression, linear regression or any kind of regression I can think of. The fitted coefficients will simply compensate the scale effect completely, so that the difference is strictly invisible to you.
This is not true, however, if you use regularization or if the scales are so different that the gradient algorithm fails to find the good coefficients. The latter is rather unlikely if the software you use is mature.
However, using regularization can truly impact the result: it says that "coefficients" must be "rather small", and how small depends on the scale and unit.
The best way to make sure scale/units has no influence on your predictions is to normalize the data first: divide each input variable by its standard deviation or use a normalization utility provided by the software.


Reference Request: Convergence of Series over Integer Lattice

Question: I am writing a school paper on Modular forms, and I want to use the following result without including a proof, since it is not directly related to my main topic.

For $s>0$, $d \in \mathbb{N}$, the series $\sum\limits_{v\in\mathbb{Z}^d\setminus\{0\}} \frac{1}{{\left \| v \right \|}^s}$ converges iff $s>d$.

However I am struggling to find a good reference for this to include in my paper. Can anyone point me to a book/paper that proves this?
Comment: See Theorem B.1 (starting on page 29) in https://ctnt-summer.math.uconn.edu/wp-content/uploads/sites/1632/2016/02/CTNTmodularforms.pdf for which your formulation uses almost identical notation already. :)
Comment: Compare with the corresponding integral?
Comment: Thanks a lot! :)
Answer: It is enough to prove the convergence of the sum over tuples of nonzero integers.
$$
\sum_{v\in (\mathbb{Z}-\{0\})^d} \frac1{\|v\|^s} \ \ \ \tag{1}
$$
Apply the AM-GM inequality, we have for $v=(v_1,v_2,\ldots, v_d)$,
$$
\frac1{\|v\|^2} \leq \frac d{(v_1^2v_2^2\cdots v_d^2)^{1/d} }
$$
The $s/2$-th powers of these satisfy
$$
\frac1{\|v\|^s}\leq \frac{d^{s/2}}{|v_1v_2\cdots v_d|^{s/d}}
$$
If $s>d$, then the sum $(1)$ converges by comparison test.
Comment: Thanks! I upvoted your answer, but I actually know a proof. I was just asking for a book/paper reference to cite in my paper, so that I don't have to include the proof because the paper is pretty long already and this result is not very related with the rest of the paper (it's just a technical lemma).
Comment: That's great. I think no one would mind if you don't include the proof. This result is widely accepted and used in the literatures about modular forms. But, I realized that my proof should also include divergence when $s\leq d$. Since you know the proof, I will pass this.


Fazer aparecer botão apenas de uma  específica

Question: Estou desenvolvendo uma aplicação web onde esse botão verde de confirmar mostrado na imagem, só é exibido quando o botão azul de editar é clicado. Esses "cards" são li's que são gerados dinamicamente conforme eu realizo um novo cadastro. O que acontece é que, quando eu clico no botão de editar (o lapis azul) de qualquer card, ele exibe o botão confirmar de todos os cards. Eu queria saber como faz pra ele exibir o botao confirmar apenas para o card que foi clicado.

Imagem 1: Exemplo de cards em que deixou os botões de confirmar visível.
Imagem 2: os li's são gerados através de um map que percorre um vetor, recebendo todos os cadastros de "reparos" (tabela do banco).

const [visible, setVisible] = useState(true);
const [nameClass, setNameClass] = useState({ className: "hideButton" });

Eu tenho esses dois estados que eu guardo a visibilidade do select e o nome da classe do botão confirmar
function showButton() {
        setVisible(!visible);
        setNameClass({ className: "confirmButton" });
        if (nameClass.className === "confirmButton") {
            setNameClass({ className: "hideButton" });
        }
    };

O showButton() altera a disabled do select pra falso e altera o nome da classe do botão confirmar.
Quando o className ta setado como hideButton, o botão confirmar recebe esse estilo:
.dashboard-container main.reparos li .hideButton {
    display: none;
}

Quando o ShowButton() altera pra confirmButton, o botão confirmar recebe esse:
.dashboard-container main.reparos li .confirmButton {
    display: inline-block;
    color: white;
    background: green;
    border: 0;
    border-radius: 5px;
    transition: filter 0.2s;
    font-weight: 500;
    font-size: 12px;
    padding: 0 10px;
    cursor: pointer;
    height: 30px;
    margin-left: 10px;
    animation: surge 400ms;
}

.dashboard-container main.reparos li .confirmButton:hover {
    filter: brightness(92%);
}

Comment: O que faz essa função `showButton()`? Podes colocar o código (em texto!) aqui?
Comment: Substitua a imagem por código, também.
Answer: Olá amigo pensei de uma forma mais genérica mas creio que irá te ajudar, no caso usei o index do array que é facilmente acessado em algums metodos que percorrem arrays no JS, no caso usei o .map. Mas você tem pode usar com base no id ou qualquer valor único, também não me mative apegado ao seu estilo, somente respondi sua primeira pergunta: "Eu queria saber como faz pra ele exibir o botao confirmar apenas para o card que foi clicado".
import React, { useState, useCallback } from "react";

export default function App() {
  const [cardsState, setCardsState] = useState([
    {
      id: 1,
      title: "Primeiro Card",
      text: "bla bla bla",
      updated: false
    },
    {
      id: 2,
      title: "Segundo Card",
      text: "bla bla bla",
      updated: false
    },
    {
      id: 3,
      title: "terceiro Card",
      text: "bla bla bla",
      updated: false
    }
  ]);

  const updateCardCallback = useCallback(
    index => {
      return setCardsState(cardsState.map(
        (card, i) => {
          if(i === index){
            return (
              {
                ...card,
                update: true
              }
            )
          }
          return card
        }
      ));
    },
    [cardsState]
  );

  const checkUpdate = update => {
    if (update) {
      return update;
    }
  };

  return (

      {cardsState.map((card, index) => {
        return (

{card.title}

            <button onClick={() => updateCardCallback(index)}>editar</button>
            {checkUpdate(card.updated)}

        );
      })}

  );
}


Sum of a variable number of Big O's terms

Question: Let $k=o(n)$, let $n\to \infty$. I am interested in the asymptotic behaviour of
$$
\sum_{i=0}^k \log\left(1-\frac{i}{n}\right).
$$
By using the Taylor series of $\log$ I obtain
$$
\sum_{i=0}^k \log\left(1-\frac{i}{n}\right) = \sum_{i=0}^k -\frac{i}{n} + O\left(\left(\frac{i}{n}\right)^2\right) = \frac{-k(k+1)}{2n} + O\left(\frac{k^3}{n^2}\right)
$$
Manipulation with Big O seems too hand-wavy, and I'm not sure if this is correct.
I have $k$ and $n$ that both go to $\infty$, the first big O is based around $n$, but there is still the summation up to $k$ outside.
Does this make sense? Is it correct?
What if $k=o(\sqrt{n})$ or $k=o(n^{\frac{2}{3}})$, does that change anything?
Answer: Your work is correct, but it seems that it's not justified fully. Let's rewrite your first step (expansion of the Taylor series):
$$\sum_{i=0}^k\log\Big(1-\frac{i}{n}\Big)=-\sum_{i=0}^k\sum_{t=1}^\infty\frac{1}{t}\Big(\frac{i}{n}\Big)^t=-\sum_{i=0}^k\bigg(\frac{i}{n}+\sum_{t=2}^\infty\frac{1}{t}\Big(\frac{i}{n}\Big)^t\bigg).$$
Now you are right with intruducing the big-O element, but the furthest you can go is this:
$$-\sum_{i=0}^k\bigg(\frac{i}{n}+\mathcal{O}\bigg(\Big(\frac{i}{n}\Big)^2\bigg)\bigg)=-\frac{k(k+1)}{2n}-\sum_{i=0}^k\mathcal{O}\bigg(\Big(\frac{i}{n}\Big)^2\bigg).$$
You can't just swap the sum and the big-O. For that you need a uniform bound. Every big-O has some linear bound and here you have arbitrarily many big-O's. You need to give them a common bound. You can get just that with the next inequality:
$$0<\sum_{t=2}^\infty\frac{1}{t}\Big(\frac{i}{n}\Big)^t<\Big(\frac{i}{n}\Big)^2\Rightarrow0<\sum_{i=0}^k\bigg(\sum_{t=2}^\infty\frac{1}{t}\Big(\frac{i}{n}\Big)^t\bigg)<\sum_{i=0}^k\Big(\frac{i}{n}\Big)^2<\frac{k^3}{n^2}.$$
Now you can directly apply this to the first step:
$$-\frac{k(k+1)}{2n}-\frac{k^3}{n^2}<\sum_{i=0}^k\log\Big(1-\frac{i}{n}\Big)<-\frac{k(k+1)}{2n}.$$
And just now you can conclude your result:
$$\sum_{i=0}^k\log\Big(1-\frac{i}{n}\Big)=-\frac{k(k+1)}{2n}+\mathcal{O}\bigg(\frac{k^3}{n^2}\bigg).$$
You could go even further with:
$$\frac{1}{2}\Big(\frac{i}{n}\Big)^2<\sum_{t=2}^\infty\frac{1}{t}\Big(\frac{i}{n}\Big)^t<\Big(\frac{i}{n}\Big)^2\Rightarrow\frac{1}{2}\sum_{i=0}^k\Big(\frac{i}{n}\Big)^2<\sum_{i=0}^k\bigg(\sum_{t=2}^\infty\frac{1}{t}\Big(\frac{i}{n}\Big)^t\bigg)<\sum_{i=0}^k\Big(\frac{i}{n}\Big)^2$$
$$\Rightarrow\frac{1}{3}\frac{k^3}{n^2}<\sum_{i=0}^k\bigg(\sum_{t=2}^\infty\frac{1}{t}\Big(\frac{i}{n}\Big)^t\bigg)<\frac{k^3}{n^2},$$
and derive a tighter bound:
$$\sum_{i=0}^k\log\Big(1-\frac{i}{n}\Big)=-\frac{k(k+1)}{2n}+\mathcal{\Theta}\bigg(\frac{k^3}{n^2}\bigg).$$
Comment: @Kolja Yes, but it would be a little hard to give it in form of your problem, it's too specific. Also, big O of something that has both $i$ and $n$ requires a little more formalization about what we mean by it - what is a constant there and what is not... Big O is too hand-wavy, indeed. To clear that first, the solution I gave you essentially has only one parameter in big-O: that is $n$. Then $k$ is just a function of $n$ so it is a dependent variable. In your writings however $i$ and $n$ are not dependent. Your big-O assumes that $\frac{i}{n}$ tends to 0 as a whole.
Comment: It's hard to decide how much my example should resemble your solution because if I change it too much it won't seem relatable and if I copy many details it won't be a counter-example since your writings are correct... Let me think about a good example and then I'll add it to the answer
Comment: I'll come back to think about it tomorrow, but for now maybe the most subtle change that would make the swapping illegal is to parametrize the function in the sum. This $\log$ is the same across the sum, make it not the same and there will be plenty of counter-examples. I think this correlates the best with the validity of the swap and that it fits the context the best, but I'll take a nicer look at it tomorrow.
Comment: Could you give me a counterexample - where the "put the sum inside the big O" wouldn't work due to lack of a uniform bound?
Comment: Thank you, I'd appreciate a counterexample. Because how I see it is that either I shouldn't be allowed to use a big O inside the sum since the sum depends on $n$, or if I am allowed to use a big O inside the sum, I should then be allowed to swap the sum with the big O. Of course I guess I could write out all the definitions and figure it out, but the point of the big O notation is not to do that, but keep things simple. If I have to develop the whole Taylor series of $\log$, there's no point in using big O.


Alguém poderia me ajudar com essa linguagem formal?

Question: Alguém poderia me ajudar com a seguinte linguagem:
{a^n b^m | n<= m <= 2n}

Desculpe a ignorância, mas não estou conseguindo formar um autômato de pilha com essa linguagem. Estou tentando através de um autômato determinístico de pilha mas não sai nada.
Comment: De qual linguagem estamos falando?
Comment: linguagem formal
Answer: {a^n b^m | n<= m <= 2n} quer dizer:

Aceita-se expressão com N elementos e A e M elementos de B, sendo M entre N e 2N.

Na prática, o autômato aceita:
AB
ABB
AABB
AABBB
AABBBB
...

Ou seja, a quantidade de B precisa ser igual à quantidade de A, ou maior que a quantidade de A, desde que não seja maior que o dobro de A.

EDIT
Achei esse site bacana pra te ajudar.
Comment: entendi, agora só tenho que criar um automato de pilha pra isso e é isso que não estou conseguindo, obrigado cara!
Comment: [Não esqueça de passear pelo Tour](https://pt.stackoverflow.com/tour). De nada!
Answer: A seguinte gramática é o suficiente para reconhecer essa linguagem:

Essa gramática gera palavras incrementalmente, aumentando sempre um a e um ou dois bs de modo auto-aninhado.
Essa gramática é uma gramática livre de contexto, gerada a partir dessa meta-linguagem: https://pt.stackoverflow.com/a/215974/64969
O autômato de pilha é esse:

Eu criei uma questão auto-respondida para tratar justamente da transformação de gramáticas livres de contexto para autômatos de pilha. Inclusive, usei a gramática desta questão como exemplo


ng-options "selected" não funciona

Question: Estou usando a função ng-options e está listando de forma correta, só não está aparecendo o valor marcado como default: selected
Código:
<select class="form-control"
   ng-model="genericCustomersViewModel.customer.addresses[0].stateId"
   ng-options="state.id as state.initials for state in
   genericCustomersViewModel.allStates track by state.id"
   ng-change="genericCustomersViewModel.getCityByState(0)"
   ng-selected="genericCustomersViewModel.customer.addresses[0].stateId">
</select>

AllStates
[{  "id":1,
    "description":"ACRE",
    "initials":"AC",
    "specificCountryCode":12,
    "countryId":30 },
{   "id":2,
    "description":"ALAGOAS",
    "initials":"AL",
    "specificCountryCode":27,
    "countryId":30 },
{   "id":3,
    "description":"AMAPÁ",
    "initials":"AP",
    "specificCountryCode":16,
    "countryId":30}]

Customer
{  "rg":null,
   "inscricaoMunicipal":null,
   "inscricaoEstadual":null,
   "cpfCnpj":"13",
   "inscricaoEstadualIndicator":null,
   "phoneNumber2":null,
   "phoneNumber3":null,
   "emailNfe":null,
   "emailBoleto":null,
   "branchesIds":[],
   "id":12,
   "name":"Razão social",
   "companyName":null,
   "mainPhoneNumber":null,
   "mainEmail":null,
   "site":null,
   "entityType":1,
   "isActive":true,
   "isDeleted":false,
   "contacts":[],
   "addresses":[
      {  "id":1,
         "description":null,
         "addressType":0,
         "postalCode":93700,
         "address1":"Balduino Dreger",
         "address2":"Não tem",
         "number":345,
         "district":"Bela Vista",
         "cityId":null,
         "stateId":20,
         "countryId":null,
         "entityId":12
      },
      {  "id":2,
         "description":"Comercial",
         "addressType":0,
         "postalCode":93700,
         "address1":"Rua dos bobos",
         "address2":"Num tem",
         "number":666,
         "district":"Centro",
         "cityId":4057,
         "stateId":19,
         "countryId":null,
         "entityId":12
      }
   ]
}

Answer: Consegui resolver este problema passando o objeto inteiro, ao invés de passar somente o ID do estado ( stateId ). No ng-model é preciso passar todo o objeto selecionado, por exemplo:
{   "id":2,
    "description":"ALAGOAS",
    "initials":"AL",
    "specificCountryCode":27,
    "countryId":30
}

Ao invés de passar somente o valor 2.

ng-options "selected" não funciona


GameObject muda posição após o play no Unity

Question: Tenho o seguinte cenário:

Os outros objectos foram desativados apenas para demonstrar o problema. Penso que ao desativa-los não influenciam no jogo, certo?
Veja o que acontece ao clicar em play no Unity:

Repare que o objecto Ground e Ground_2 foram mudados para a posição (0,0) em relação a câmera (sim, o pivot do sprite é BottomLeft, por isso não fica centrado)
Veja a configuração dos objectos no inspector:
Background

Câmera

Script da câmera
using UnityEngine;
using System.Collections;

public class CameraSettings : MonoBehaviour {

    private float targetRatio = 9f/16f;

    // Use this for initialization
    void Start () {
        Camera cam = GetComponent<Camera>();
        cam.aspect = targetRatio;
    }
}

Ground (os 3 objectos são os mesmos, foram duplicados portanto os atributos no inspector são iguais):

Repare que o Ground, Ground_2 e Ground_3 são prefab.
Eu criei um empty GameObject (e adicionei o RectTransform, Rigidbody2D conforme a imagem acima) e dentro desse GameObject adicionei um sprite (GroundSprite) com as seguintes configurações:

Após a ação acima, arrastei o GameObject para um prefab e depois removi o GameObject de cena, mais tarde arrastei o prefab para a cena 3 vezes, gerando os 3 elementos que compõem o chão (Ground, Ground_2 e Ground_3) e logo em seguida fui no menu em "GameObject > Break Prefab Instance" para poder edita-los sem modificar o meu prefab.
Sim, foi uma grande confusão, mas penso que o problema não está no facto de andar a arrastar coisas de um lado para outro, certo?
O que está de errado com o jogo? Poderá ser cache do programa? Instalação com problema? O que será?
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54201/discussion-on-question-by-filipe-moraes-gameobject-muda-posicao-apos-o-play-no-u)
Answer: Parece ser um bug a partir da versão 5.1.2 do Unity: http://answers.unity3d.com/questions/1028760/unity-randomly-resetting-gameobjects-position-to-w.html#comment-1028775
Segundo o utilizador, ele resolveu da seguinte forma:

I solved the problem. It was caused by the rigidbody2Ds position constraints. I confirmed this by having few clones of the gameobject put to the scene and ticked the constraint off from one of them.
When the bug appeared again, only the gameobjects with the position Y or X frozen was reseted to the (0,0,0) position. I ticked the constraint back on and that gameobject was also moved to the zero position after that.
I'm not sure if that is how the constraints are supposed to work or is it a bug. But anyway that was causing the random behaviour.


Excel VBA: specify which charts to edit with macro

Question: I already wrote macro that edit one chart.
Now I would like to edit many charts at once, for example all this charts:

"chart 15"
"chart 18"
"chart 22"
"chart 27"
"chart 85"
"chart 55"
etc...

How can I do that without copying pasting "edit-Chart-Code" under each:
for example:
ActiveSheet.ChartObjects("Chart 15").Activate

Comment: loop through desired charts and call that "edit-chart-code" each time
Comment: Please add the code you already have tried to achieve this.
Comment: [This is Microsoft's information about utilizing vba to target charts.](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/chart-object-excel)
Comment: i don know how to loop, so i wrote 2 macros,
Comment: first is:
          Sub DOL()
'
' DOL Macro
'
' Keyboard Shortcut: Ctrl+Shift+D
'
    With ActiveSheet.ChartObjects("Chart 204").Activate
    Call Macro21
    End With

    With ActiveSheet.ChartObjects("Chart 207").Activate
    Call Macro21
    End With

    End With

End Sub
Answer: If these are the chart names on the active sheet, and you're always going to do them all, then something like this might help:
Sub FormatNamedCharts()
  Dim chob As ChartObject

  For Each chob In ActiveSheet.ChartObjects
    Select Case chob.Name
      Case "Chart 15", "Chart 18", "Chart 22", "Chart 27", "Chart 85", "Chart 55"
        ' Do your
        ' formatting
        ' in here
      Case Else
        ' skip
    End Select
  Next
End Sub

If you want to let the user select charts to process, then this is how to do it:
Sub FormatSelectedCharts()
  Dim sh As Shape

  If TypeName(Selection) = "DrawingObjects" Then
    For Each sh In Selection.ShapeRange
      If sh.HasChart Then
        With sh.Chart
          ' Do your
          ' formatting
          ' in here
        End With
      End If
    Next
  End If
End Sub


How to add multiple conditions on a single field in views?

Question: I have two fields in my content type. State and test . State have two values active and inactive and test is a boolean field.
I want to display the content of this content type using views which will display:
active content
inactive content if test is FALSE

How can I do this in views?
I tried with views filter groups and it generates this condition.
WHERE ((( (node.status = '1') AND (node.type IN  ('mycontnt')) AND (state = 'active') )OR( (state = '4') AND (test = '0') )))

But this is not displaying the correct content as I want.
Answer: So far as there is no support for nested groups in Drupal 7, we shoud do it slight differently.
Join general filters (Published and Node type) in first AND group. May be we also should to add there "State IS NOT NULL" condition to exclude content with empty State field.
In second group we should place State = 'active' OR test = 'false'. This group - OR group.  In the Views admin interface in would be somthing like this:


Using variable with Background in Cucumber

Question: I'm trying to run a feature file like this:
Feature: my feature

Background:
  When I do something
  And I choose from a <list>

Scenario Outline: choice A
  And I click on <something> after the choice A is clicked

Examples:
  | list | something |
  |  a   |   1  |
  |  b   |   2  |
  |  c   |   3  |

But what happens is when the second Background step runs, in the step definition, list is a String with the value <list>, and the first Scenario line something is 1, so can Background not use the variables from Examples? Putting a copy of Examples before Scenario Outline does not work.
Comment: I'm pretty sure you can't do this.  The background isn't necessarily used with a scenario outline, so it can't know that you will have examples.
Comment: @CarlManaster is right. Just move the line to your Scenario Outline.
Comment: I ran into similar issue today, quite annoying. @CarlManaster AFAIK `Background` is used for all scenarios, including `Scenario Outline`, see https://docs.cucumber.io/gherkin/reference/#background.
Answer: The answer to your question is: no. Background is not a scenario outline. It does not take values from Examples, which is exclusively for the Scenario Outline where it is included.
Let's suposse you have several Scenario Outlines. Each of them should have its own Examples sections and it is not shared between them. Consequently, it is not shared with Background either.
That is why it does not work when you move Examples before Scenario Outline, as you mentioned in your question.


how to set a taxonomy term active?

Question: In my block i have different taxonomy term:
term A
-term B
--term c
---term D
when i am on term b it is set to active or bold if i am on term d then it is set to active and bold.
this is already been used
<code>$options = array();
if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2) == $t->tid) {
    $options = array('attributes' => array('class' => 'active'));
}</code>
i am new in drupal anyone tell me how it is possible?
Answer: The arg() function is taking argument parts from the url.
/taxonomy/term/2 means:
arg(0) = taxonomy
arg(1) = term
arg(2) = 2
Comment: yes it is taking from arg()

how to set a taxonomy term active?


Como retirar a string de um intervalo determinado

Question: Olá,
Pessoal, estou relembrando programação(c++) e peguei um projetinho para fazer um de um programa que lê código de barras, grava em um vetor.Dentro de cada código lido entre os caracteres 24 e 33, possui um numero que referencia a Nota fiscal.
Eu preciso retirar esse numero e exibir o mesmo junto com o código.
Segue, o que eu já fiz:
<code>#include<iostream>
#include<string.h>
using namespace std;

string cod[100];
char numnota;

int main()
{
    string cod[100];
    cout<<"Comece aqui a ler os codigos de barra" << endl;
    int i=0;
     while(cod[i] != "0"){
         cin>>cod[i+1];
         i++;
    }

    i=0;
    while(cod[i]!="0")
    {
        cout << cod[i] << endl;
        i++;
    }
    numnota = cod.substr(24,33);

}
</code>
Comment: Aqui: `while(cod[i] != "0"){` será que não deveria ser: `while(cod[i] != \0'){`? Se você quer uma substring então `numnota` não deve ser declarado como um único caractere e sim como uma string. Como você não está trabalhando com a classe string talvez devesse usar: `strncpy(numnota, cod+23, 10);` (lembrando de corrigir a declaração de numnota).
Comment: Fala , Daniel

    Obrigado por responder.Então o while e a condição de parada, quando alguem digitar 0, indica que terminou a leitura dos codigos de barra.Tentei usar a função que disse, mas nao deu muito certo =/
Comment: Não sou o Daniel, mas o que você quer dizer é que em seu código de barras não é permitida a existência do algarismo zero? Quanto à função você acrescentou o terminador '\0' ao final?
Comment: Como você diz que está utilizando C++ então é mais fácil utilizar a função `substr` da classe ``.
Comment: Na verdade, o "0" é a condição de parada do while, serão lidos os codigos de barra normalmente e qnd o usuario digitar 0,o codigo encerra a leitura.Vou tentar usar a classe que me disse
Answer: Veja se é isto (troquei os limites do substring para ter uma entrada menor):
<code>#include <iostream>
#include <string>
using namespace std;

string cod[100];
char numnota;

int main() {
    string cod[100], numnota;
    cout<<"Comece aqui a ler os codigos de barra" << endl;
    int i=0;
    do {
        cin>>cod[i++];
    } while(cod[i-1] != "0");
    i=0;
    cout << "Códigos informados:" << endl;
    while(cod[i]!="0") {
        cout << cod[i];
        numnota = cod[i].substr(4, 3);
        cout << "\t" << numnota << endl;
        i++;
    }
    return 0;
}
</code>
Veja funcionando em: https://ideone.com/a5NoWG
Comment: Fantasístico, agradeço muito sua resposta.Mas poderia me explicar como funciona o codigo?Como eu disse eu estou reaprendendo e gostaria de saber como ele funciona


Adding a css file to a custom theme

Question: I'm a very beginner in drupal and I just want to add a css file to my custom theme.
So I created a upjv.libraries.yml in themes/upjv and I added :
global-styling:
version: '8.4.4'
css:
   theme:
       css/styles-upjv.css: {}

And I have created a styles-upjv.css in themes/upjv/css. On my index page, my file isn't loaded and I don't know if it's because I created the file in a wrong place, if the content of my libraries.yml is correct. Can anyone help me on this little problem please ?
Answer: You have to add the following in your upjv.info.yml:
libraries:
  - upjv/global-styling

Make sure to clear cache after that by navigating to configuration > Development > Performance then clicking on Clear all caches under CLEAR CACHE.
Comment: Thanks for your anwser, I added it but it still doesn't work
Comment: Do I have to add something in the backend ? Is there any log managed by drupal ?
Comment: Did you clear caches? I added the details on how to do that. Let me know if you still need help.
Comment: See [Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme](https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme) on drupal.org.

Adding a css file to a custom theme


What does parent::form($form, $form_state) do?

Question: I'm not able to understand what parent::form($form, $form_state) does in a content entity form. If I comment it out, the entity form still get rendered.
class AdvertiserForm extends ContentEntityForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    /** @var \Drupal\redirect\Entity\Redirect $redirect */
    $advertiser = $this->entity;
    $form['status_code'] = array(
      '#type' => 'textfield',
      '#title' => t('Redirect status'),

    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
      $form = parent::form($form, $form_state);

  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $this->entity->save();
    drupal_set_message(t('The redirect has been saved.'));

  }
}

What does parent::form($form, $form_state) do, exactly?
Answer: If you look at ContentEntityForm::form(), the method called with parent::form() since ContentEntityForm is the parent class, you will notice what exactly it is doing.
  $form = parent::form($form, $form_state);
  // Content entity forms do not use the parent's #after_build callback
  // because they only need to rebuild the entity in the validation and the
  // submit handler because Field API uses its own #after_build callback for
  // its widgets.
  unset($form['#after_build']);

  $this->getFormDisplay($form_state)->buildForm($this->entity, $form, $form_state);
  // Allow modules to act before and after form language is updated.
  $form['#entity_builders']['update_form_langcode'] = [$this, 'updateFormLangcode'];
  return $form;

It doesn't significantly change the form, so it is expected the form doesn't apparently change, or it is rendered the same if you don't call parent::form(), but (as the comment says), it allows modules to act when the form language is updated. You could not see anything different, but you are actually avoiding modules can do anything when the form language is changed.
Answer: It's executing a method with the same name on its parent class. This is standard fare in any language when you're dealing with inheritance, when functionality from the base class is still (or may be in the future) required.
In this case it's the ContentEntityForm::form() method that will be invoked. The fact that it doesn't appear to do/change anything is irrelevant - something might change in the future that does require that base class's method to be called, and by referencing it now, you're future-proofed.
Have a read up on OO PHP if this concept is unfamiliar to you, it's one of the more basic ones, so easy to learn. There are a lot of OO concepts used in D8, learning them early on will really help you get to grips with the framework more quickly.
Comment: It isn't a static method. When referring to a method in the documentation, that is the way of doing it: `Class::method()`.
Comment: Just to add to this answer, `ContentEntityForm` is the name of the object, `form()` is the name of the [method](http://stackoverflow.com/questions/155609/difference-between-a-method-and-a-function), and `::` means that this is a static method.