Combination Calculations with Sub Groups

Question: Given 16 Trials equally distributed to 4 individuals ( 4 Trials per person).
How many combinations are there where these conditions are met:
Condition A: 5 Total Successes
Condition B: 2 or Fewer Successes per Individual.
I understand Condition A in exclusivity would be:
$$\binom{16}{5} = 4368$$
I believe Condition B in exclusivity would be the following but please correct me if I am wrong:
$$\left(\binom42 + \binom41 + \binom40\right)^4 = 14641$$
My problem is I do not know how to solve for the number of combinations when both conditions are applied.
Comment: Condition $A$ and $B$ have no restriction on the number of combinations individually. The number of ways to choose 4 individuals on each trial is the same as the number of ways to choose 4 individual on each trial where 5 trials win. It's not until you make it to where an individual can't win three or four times do you actually get a restriction.
Comment: Welcome to MSE.  Please use [MathJax](https://www.onemathematicalcat.org/MathJaxDocumentation/TeXSyntax.htm) to format your posts.  To begin with, surround math expressions (including numbers) with `$` signs and use `_` for subscripts.  `$x_1$` comes out as $x_1$.
Answer: There are only two ways to write $5$ as a sum of $4$ nonnegative integers $\leq2$:$$1+1+1+2\\0+1+2+2$$  For the first of these we have $$4\binom41^3\binom42$$possibilities, and for the second we have $$12\binom40\binom41\binom42^2$$ possibilities.
Answer: You have two possibilities for number of trials across $4$ individuals that meet both conditions. Those are $ \{ 2 \ 2 \ 1 \ 0\}$ with permutations $\displaystyle \frac{4!}{2!}$ and $ \{ 2 \ 1 \ 1 \ 1\}$ with permutations $\displaystyle \frac{4!}{3!}$.
So the total number of combinations of trials (considering trials are distinct) meeting both conditions
$ = \displaystyle \frac{4!}{2!} \cdot {4 \choose 2}^2 \cdot {4 \choose 1} + \frac{4!}{3!} \cdot {4 \choose 2} \cdot 4^3 = 3264$


How do I find the sum of the series -1^2-2^2+3^2+4^2-5^2… upto 4n terms?

Question: I tried by giving
$$ S = \sum_{k=0}^{n-1} \left((4k+3)^2+(4k+4)^2-(4k+1)^2-(4k+2)^2\right)  $$
but I am stuck here. I have no idea what to do next. The answer in my book says 4n(n+1). How can I get it? I tried expanding (4k+1)^2, etc. and got $ \sum_{k=0}^{n-1} (8k+20) $, I tried to further expand this by taking it as $ 8\sum_{k=0}^{n-1}k + 20n = 8(n-1)(n)/2 + 20n = 4n^2+16n= 4n(n+4) $ which is not the right answer. What have I done wrong? What must I do now?
Comment: Expanding is agood simple idea! Maybe your made an error in the expansion.
Answer: It seems that you should get to sum $32k+30$, not $8k+20$, and then simplify.
Comment: I've obtained 32k+20! I check
Comment: @gimusi That's right! :P
Answer: We have
$$(4k+3)^2+(4k+4)^2-(4k+1)^2-(4k+2)^2=16k^2+24k+9+16k^2+32k+16-16k^2-8k-1-16k^2-16k-4=32k+20$$
Answer: $(4k+3)^2-(4k+1)^2+(4k+4)^2-(4k+2)^2=(4k+3+4k+1)(2)+(4k+4+4k+2)(2)$
So the sum can be written as $2(1+2+3+\cdots+4n)$.
Answer: Expand
\begin{align}
&(4k+3)^2-(4k+2)^2+(4k+4)^2-(4k+1)^2\\
\qquad&=(4k+3-4k-2)(4k+3+4k+2)+(4k+4-4k-1)(4k+4+4k+1)\\
\qquad&=8k+5+3((8k+5)\\
\qquad&=4(8k+5)\\
\qquad&=32k+20
\end{align}
So your sum is
$$
\sum_{k=0}^{n-1}(32k+20)=
32\frac{n(n-1)}{2}+20n=16n^2-12n
$$
Comment: Yes of course, I was considering from n=1!
Answer: In other terms,since
$$(x+2)^2-x^2=4(x+1)$$
so you have to sum $$4(4k+2)+4(4k+3)=32k+20$$


A question on the morphism of projective varieties

Question: The continuation of this, my question

I want to show that $X$ and $Y$ are smooth and irreducible curves then $f(X)$ is either $Y$ or a point.

Note that I know the proof of this theorem that the image of projective varieties under a regular map is closed.
But I cannot apply this proof into my question. Please show me the proof of my statement. thank you.
Comment: Do you know how to characterise the proper subvarieties of $Y$?
Comment: No I am not good at this topic:( @TomOldfield
Comment: Can you show its proof explicitly? @TomOldfield
Comment: No problem, everyone is learning! I'll write an answer, and then elaborate a bit on anything that needs elaborating.
Comment: Thank you so much :) @TomOldfield
Answer: First we have a theorem: If $X$ is an irreducible curve (affine or projective) then the only proper closed subsets of $X$ are finite sets of points. This requires a bit of machinery to prove, the proof that I know uses both nullstellensatz and transcendence dimension as a characterisation of dimension of varieties, and I don't think is particularly enlightening so I will leave it out. However, if you are willing to assume this, then we can now prove the statement:

Any morphism of irreducible projective curves $\alpha:X\rightarrow Y$ has image either a point, or $Y$.

We use the fact that given any non-constant morphism of irreducible projective curves $\alpha:X\rightarrow Y$, for any point $y \in Y, \#\alpha^{-1}(y)$ is finite. This follows from the first theorem since if $\alpha$ is non-constant, $\alpha^{-1}(y)$ is a proper closed subset of $X$ so is a finite set of points.
Now, since $X$ has dimension $1$, $X$ is not a finite set of points, so the image of $\alpha$ cannot be finite. Using the above theorem again, since the image is closed in $Y$ and not a finite set of points, it must be all of $Y$. In other words, if $\alpha$ is non-constant, it is surjective.
Comment: @B11b Thank you, very happy to help!
Comment: I understand. Your answer is so clear and explanatory. Thank  you so much :)


Label for Child in Hierarchical Select

Question: While using Simple Hierarchical Select Module, I have 2 levels of Hierarchy for my Phone.

However I want to add the label for Child list like:

Is this possible? then how?
Answer: I know I'm late, because this answer has been answered long time ago, but I don't think this is the right way to do it, especially with the java script interval function – it might work but in many cases may cause a problem.
For those who need the same result I suggest to use this java script code which is based on action when the ajaxStop event is triggered.
First you nedd to create a java script file in your module directory, for exapmle: YOUR_MODULE_NAME/js/custom_shs_behaviors.js with the following code:
/**
 * @file
 * Custom behaviors for Simple hierarchical select:
 *   Change the first option text from "- None -" to whatever you want (default: "- Any -").
 *   Create labels for each level.
 */
 (function($) {
  Drupal.behaviors.customShsBehaviors = {
    attach: function (context, settings) {

      // Helper function for an option text replacement.
      // use: optionObj.replaceOptionText(); for default replacement from '- None -' to '- Any -'.
      // or optionObj.replaceOptionText('Foo'); to replace the '- None -' with 'Foo'.
      $.fn.replaceOptionText = function(replacement) {
        var replacement = replacement ? replacement : '- Any -';
        if ($(this).text() == Drupal.t('- None -')) {
          $(this).text(Drupal.t(replacement));
        }
      };

      // Function that helps to get the select element width including its padding and margin.
      $.fn.getSelectWidth = function() {
        var width = Math.round($(this).wrap('').outerWidth(true));
        $(this).unwrap();
        return width;
      }

      // Define labels.
      var labels = ['Label-1', 'Label-2', 'Label-3'];

      // act when the ajaxStop event is triggered (there are no more Ajax requests being processed.)
      // see: @link http://api.jquery.com/Ajax_Events/ @endlink
      $('.shs-wrapper-processed').ajaxStop(function(event, xhr, settings) {

        $("select.shs-select").each(function(level) {

          // fix the SHS bug - new level that is being created has the same ID as the previous one.
          // make sure that each select has an ID and the class corresponding to the level.
          // YOU CAN USE THESE TWO LINES ONLY IF YOU ARE USING SHS WITH THE ABILITY TO ADD NEW LEVELS.
          $(this).attr('id', $(this).attr('id').replace(/(.*)select-(\d+)/, "$1select-" + (level+1)));
          $(this).attr('class', $(this).attr('class').replace(/(.*)level-(\d+)/, "$1level-" + (level+1)));

          // Replace the first option text using the helper function for an option text replacement.
          $("option", this).first().replaceOptionText();

          // Get label width.
          var labelWidth = $(this).getSelectWidth();

          // Create label.
          if ($("label[for='" + $(this).attr('id') + "']").length == 0) {
            $(this).parent().before(
              "" + labels[level] + ""
            );
          }

          // Remove the label if the select element has just been removed by clicking any option on lower level.
          // There might be several Ajax requests bound with this action,
          // so we have to make sure that our "removing process" will be executed at most once.
          // See: @link http://api.jquery.com/one/ @endlink
          $("option:not(:selected)", this).one("click", function() {
            $(".shs-wrapper-processed").parent().find("label").each(function() {
              if ($(this).attr('for').slice(-1) > level+1) {
                $(this).remove();
              }
            });
          });
        });
      });
    }
  };
})(jQuery);

And attach the java script file to your form. You can do it by using the hook_form_alter() in your theme or module file:
/**
 * Implements hook_form_alter.
 */
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {

  switch($form['#id']) {
    case 'YOUR-FORM-ID' :
      $form['#attached']['js'][] = drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/custom_shs_behaviors.js';
    break;
  }
}

You're done! With this code you can set the label for each level of your shs and even change the default option text, for example: from - none -  to - any -.
Comment: Hi,I have a problem with using this function:    $("#edit-field-country-region-tid-select-1 option[value='0']").replaceOptionText('-Select region-'); How can I make use of this? I tried many options, and I have no idea how to apply this function to specific option.
Comment: Working fine ,but label not remove .
Answer: You Can do with custom jquary with set Intervel function.
Eg: i have attached screenshot at bottom
//Add label to state
    //on change first level(here country)
$('select.shs-select-level-1').change(function(){

    var $aSelected = $('.shs-wrapper-processed').find('label');

    if( $aSelected.hasClass('Extra-Label1') ){
        $('.Extra-Label1').text("State");
    }
    else{
        $('select.shs-select-level-2').before('State');
    }

});

//Add label to city
$('select.shs-select-level-2').change(function(){

    var $aSelected = $('.shs-wrapper-processed').find('label');

    if( $aSelected.hasClass('Extra-Label2') ){
        $('.Extra-Label2').text("City");
    }

    else{
        $('select.shs-select-level-3').before('City');
    }
});

//The above code is ok, but last label will loss after change any select levels so needs add in set intervel function
setInterval(function(){
    var $aSelected = $('.shs-wrapper-processed').find('label');
    var $bSelected = $('.shs-wrapper-processed').find('select');
    if( $aSelected.hasClass('Extra-Label2')&& $bSelected.hasClass('shs-select-level-3') ){
        $('.Extra-Label2').text("City");
    }
    else{
        $('select.shs-select-level-3').before('City');
    }

},1000);

Comment: I which file we can write this script ?
Comment: Devidas, you can write the above script in theme custom js file
Answer: Some developers may wish to use the pre-existing label over the top category to represent a title for the hierarchial select (rather than a header for the top category).
Here's another (jQuery) way you could achieve a similar effect, using a locational hierarchy for the demo:
In your custom js you can add a top level label when the document is "ready" - custom way or the preferred Drupal.behaviors way (neither demonstrated).
$('select.shs-select-level-1').before('' + Drupal.t('Region') + '');

Then monitor for any changes to the entire container. If one is detected, you can clear all the labels of a custom class and then re-attach all the classes where jQuery can ignore exceptions
$('#field-select-a-city-add-more-wrapper').change(function () {
    $('#field-select-a-city-add-more-wrapper').find('label.shs-label').remove();
    $('select.shs-select-level-1').before('' + Drupal.t('Region') + '');
    $('select.shs-select-level-2').before('' + Drupal.t('Country') + '');
    $('select.shs-select-level-3').before('' + Drupal.t('State') + '');
    $('select.shs-select-level-4').before('' + Drupal.t('City') + '');
});

Label for Child in Hierarchical Select


Copying Firmware to 3560X Switch Ends SSH Session & Erases File

Question: I am simply trying to copy a new firmware file to a 3560X switch by connecting via SSH and copying it from a tftp server to the flash memory.  The process commences, the transfer gets all the way to the end but when it complete, it boots me out of my SSH session and when I log back in, the firmware file is nowhere to be found.  I opened a second SSH session and watched the flash and it does build the file as it's uploading, but it disappears when it's complete.  I don't get a screen showing that it attempted to verify the file, it seems to happen immediately when the transfer is complete.  I'm also logged in as a user with root privileges.  There were no log entries out of the ordinary during this time.
I've already done this to over 100 other switches, so I know the process like the back of my hand.  I don't know why this one switch is having issues.  I did some googling but either didn't know what to search for or no one else has posted about this issue.  Any help is greatly appreciated.
Comment: Since you've done this several times successfully, I'm going to assume that you've already checked that there's enough flash memory available. Even then, filling up the flash should not disconnect you from SSH. I would say it's a bug as well or a faulty unit.
Comment: Which version of IOS?, Do you have enough room in flash?
Comment: Try a different IOS file. Perhaps that one is corrupt.
Comment: Which command set are you using to load the switch - tar or copy?  Is the switch bouncing when the copy is complete or are there any tracebacks in the logs?
Comment: If the flash isn't full which would be my thought, I'd recommend to call TAC
Answer: I believe I ended up circumvented this somehow but I don't remember exactly how.  It might have been by erasing the flash and uploading the file then or by copying it from another switch with that firmware.  I apologize for not following up with my solution.
Comment: Not an answer. Leaving this comment till I'm out of flagban.


How to restrict users from editing the same item in frontend when it is already edited

Question: I have an application where users can display and edit items in my database via a website. Now, to be sure there are no upcoming problems when two users edit the same item, I would like to prevent them from doing so. That means, the first user accessing the item can edit it and the rest could only view the item. But sadly, I have not clue how to properly implement this. Let's have a look at the setup first:
I have a controller that could look like this:
@RestController
@RequestMapping(value="/item")
public class ItemController {

    @Autowired
    ItemService itemService;

    @GetMapping(value="/getItem/{item_id}")
    public ResponseEntity getItem(@PathVariable String item_id) {
        this.itemService.getItemById(item_id);
        return ResponseEntity.ok(HttpStatus.OK);
    }

}

Now when getItem is called, I know that a user accessed the item with the given item_id from the frontend. So I could simply build a List of "blocked" items in my Controller, that contain the elements and check if the getItem-method is called: "If item_id is in the list, return Access denied & redirect to a "view-only" component, else ok". But this seems to be quite a prone workaround and I cannot inmagine this is the way it is intended to be solved. Also I'd need to somehow remove the items from the list on a reliable way.
Is there a pattern or something like that that shows how this is to be solved?
I am using Spring-Boot and Angular 7, if that helps.
Answer: This is especially difficult to do for many reasons, including the ones you mentioned. What if you lock a row and the user with the lock just closes the browser? Then the row is locked forever. Or do you then run a nightly routine to clear all locks, but then no user can access the record until the next day, etc.
In general, this has been a problem since databases were invented, so you would think that a solution would have been found, but not that I know of. Normally I try to recommend ways to minimize this happening through business process, not software.
In the software, you could consider instead of locking, providing ways to further minimize the impact of multiple updates by retaining the timestamp. When a user gets a row and then posts to update it, the system would check that the timestamp is still the same. If so, it allows the update. If not, it would either have to reject the change, or be smart and attempt to determine how its data is different from the current data and merge values as best it can.
You can read more about this here: Optimistic vs. Pessimistic locking


Is there a way to iterate through all ASP.NET MVC 2 session keys?

Question: I'd like to get a list of all the session variable names.
something like:
foreach(Key name in HttpContext.Session.Keys)
{
...
}

Answer: Your code works! Just use string not Key
foreach (string key in Session.Keys)
{
    var value = Session[key];
}

Or an alternative
for (int i = 0; i < Session.Contents.Count; i++)
{
    var key = Session.Keys[i];
    var value = Session[i];
}


What to call groups of measures?

Question: I'm making a music game.  It's a dancing game to electronic music at 120ish bpm in 4/4 time (I'm assuming).
I have beats, and 4 of those make a measure.
But dancers yell that 5,6,7,8 before dancing, so whats a good name for those pairs of measures?
The music seems very structured into groups of 8 measures with a theme, then move to another theme.  I've been calling these "Movements" - they don't always have to be 8 measures, but seem to be a power of two.
Naming things is about communicating.  I've been googling, but haven't found a description for these groups of measures.
Is it structured or do yall just make it up?
Comment: As judge mental says phrases.
Comment: "phrases"? "verses"?
Comment: Note that the typical dancer's "5, 6, 7, 8" is all four beats done within *one measure*. That single measure sets the tempo, and probably does some other stuff I'm not aware of.
Comment: segments? sequences? 'movement' already has a meaning [in classical music if not EDM], so avoid that.
Comment: Thanks!  I ended up with beat, bar (from tool I'm using), Dancers Set (from "Dancers 8"), and intensity as an adjective vs movement as a noun.
Answer: Groups of measures that contain one idea are called a phrase. Phrases are often, but not always, four measures long. Phrases can be grouped together and simply be called "phrase groups" or they can follow a stricter form called periods if they contain certain cadence patterns. There are different types of periods, as well, depending on the melodic structure and cadences of the phrases that are included. These are the foundations of larger structures and form in music.
Answer: A '5,6,7,8' count-in (and that's the name for it) at q=120 sounds like it would be one bar.  (Funny thing - dancers like to count backwards, a musician would be more likely to shout '1,2,3,4.)
No, a 'movement' is a (much) bigger unit than a 4 or 8-bar phrase (which is probably the word you want).   A movement is a complete piece of music.
Answer: I have been searching Google myself and no-one seems to understand the question. But I found something...
Heres a link that shows it clearly...
4 measures are called a phrase.
8 measures are called a period.
Comment: This is already stated in the accepted answer (the one with the green check-mark next to it. Can you add some more?
Answer: The lead-in notes that are understood to somehow before its true beginning are called anacrusis. When we count before the tune starts, that's a sort of anacrusis.  Sometimes when music with an anacrusis loops, the last measure's ending is short, and combines with the anacrusis. E.g. a 3 note anacrusis in 4/4 time might start music which ends on a bar that has just one beat; this is supposed to dove-tail with a repeat of the anacrusis.
Groups of related measures could be called segments or sequences. It sounds as if the music in question consists of 8 bar sequences that are introduced by an anacrusis/countdown, and have space in the last measure to accommodate the next such lead-in.
Music that consists of unrelated melodic sequences, or entire tunes, stitched together, usually under an uninterrupted tempo, is a medley.
Comment: 'Anacrusis' isn't really the right word for a dance 'count in'.
Comment: I disagree with your use of "segment" and "sequence." A segment is more of a reference to a group of figures that make up a piece of a measure or measures, not an entire phrase. "Sequence" has a very specific meaning, which is a segment of music (using the definition I just gave) that is immediately played again, transposed up or down by a certain interval. Sequences are often, though not always, found in groups of three. A phrase can contain sequences, but a sequence by itself does not necessarily make a phrase.

What to call groups of measures?


Complex integral on curve

Question: I have to show that this integral is zero, but don't know how to evaluate it.
Consider a closed class $C^1$ curve $c:[a,b]\rightarrow\mathbb{C}\backslash \{0\}$ and show that $$\int_a^b\frac{\langle c(t),c'(t) \rangle }{\lVert c(t)\lVert^2}dt=0$$
It is necessary to consider $c$ as a curve in $\mathbb{R}^2\backslash \{(0,0)\}$ to write $c(t) = (c_1(t),c_2(t))$, then $\langle c(t),c'(t)\rangle = c_1(t)\cdot c_1'(t)+c_2(t)\cdot c_2'(t)$ and $\lVert c(t)\lVert^2=c_1(t)^2+c_2(t)^2$.
PS: I would know how to evaluate if the denominator was not squared, that is the big problem.
Thanks in advance.
Answer: Note that for $f(t):=\log\|c(t)\|$,
$$f'(t)=\frac{\langle c(t),c'(t)\rangle}{\|c(t)\|^2}.$$
Comment: Is there some way to avoid logs? I'm worried cause none is said about $n(c,0)$ ( number of turns around the origin ).
Comment: @Integral: Here $\|c(t)\|>0$ and $\log:(0,+\infty)\to\Bbb R$. If I understand your question clearly, then $c(a)=c(b)$ and hence $f(a)=f(b)$. By the way, I think your question has nothing to do with complex analysis.
Comment: indeed, thanks a lot!
Comment: @Integral: You are welcome!
Comment: @MhenniBenghorbal: Thank you.

Complex integral on curve


Emulador IOS para teste do meu projeto

Question: Estou iniciando um projeto em iOS no Visual Studio desenvolvendo em Xamarin onde preciso de um emulador para eu rodar.
Existe algum emulador que o Visual Studio reconheça?
Tenho em mãos um iPad, eu consigo executar meu APP no iPhone 5 ou 6 com ele?
Qual a melhor saída?
Comment: voce por acaso tem um mac na rede, ou fisico para fazer a compilacao?
Comment: não tenho, tenho só um ipad
Comment: sera que se eu fizer os testes no ipad da certo eu emular ele ?
Comment: Para a compilacão voce necessita do xCode e isto voce so poderá fazer com um computador com hardware mac, ou um servico de alugel de mac.
Answer: para que voce gere um deploy para IOS é necessário ter um MAC.
Caso voce não possua um MAC você pode utilizar uma máquina virtual para isso.
No site da Microsoft Academy voce poderá entender melhor esse processo.
Answer: Conforme o Felipe descreveu, você precisa de um mac. Você tem como opção mais acessível os serviços de cloud como o macincloud. Máquina Virtual MAC não é uma opção legalmente viável. Então ou você usa um MAC Físico ou um em cloud.
Você não conseguirá realizar testes do seu app de iPhone em seu iPad. No iPad você faz testes apenas de iPad ou de App iOs Universal (mas esse tem comportamento especifico para cada device) e apenas depois de realizar um deploy em um MAC.

Emulador IOS para teste do meu projeto


Trying to change a CSS Property value with jQuery, What did I do wrong?

Question: <code><script>
$('#id_body_text').keypress(function(){

    if(this.value.length > 252){
        return false;
    }
    $(".suggest7").html("Remaining characters : " +(252 - this.value.length));
    $(".suggest7").attr('margin-left', "400px");
    $(".suggest7").attr('width', '162px');
});
</script>
</code>
margin-left and width have completely different values and the code above does not seem to be changing them?  Did I do something wrong here?
Answer: If you want to change the CSS then use
<code>$(".suggest7").css('margin-left', "400px");
$(".suggest7").css('width', '162px');
</code>
You can even do it in one shot:
<code>$(".suggest7").css({'margin-left': "400px",'width':'162px' });
</code>
Comment: Thanks, I guess I misread the jQuery documentation.  Works fine now.


Trouble with Eclipse Listener and getting the Source

Question: In My Eclipse Project, I have a
Text custom_text = new Text(....);

Now I add a listener -

custom_text.addKeyListener(new
  KeyListener(){
@Override  public void keyPressed(KeyEvent event) {
}
@Override   public void
  keyReleased(KeyEvent event) {
        System.err.println("event
  "+event.getSource()));
} });

Anyhow, I am not getting the source name,despite I am getting the output as Text {}.
Well I want to get the source name ie custom_text .

How to get the output in a listener as
  custom_text
Answer: IMHO you can not the name of the variable, holding the reference to your textfield. It is also not really of any use to know the name of the variable, since you can have many referencing variables.
With .getSource() you get a full reference to the widget itself, so you can deal with it in any way.
Comment: You will **never** get "custom_text".  That information is lost on compile.  This source is still the object reference, it just overrides toString() an outputs "Text{}".  Swing also would not print "custom_text" based on what you have written.  Or do you mean you want the **contents** of the Text widget?
Comment: Actually I am expecting the name because of some other use. Moreover getSource() is only printing Text() as output. So I am stuck . Actually In Swing.. we get the object reference name . so I expected the same behaviour here
Comment: Yes.. I was confused about my Objective. @above all are correct in their point...
Answer: You can use event.widget to identify wich widget notify event.
But general approach is relaying with anonymous listener.
because it can use more readable method name which is more fit to subject of controller.
Text nameField, emailField = ...

nameField.addListener(SWT.KeyUp, new Listener(){
    public void handleEvent(Event e){
        handleNameEdited();
    }
});

emailField.addListener(SWT.KeyUp, new Listener(){
   public void handleEvent(Event e){
       handleEmailEdited();
   }
});


Change some charachter in All field before saving node

Question: I want done a action (change some charachter) on every field in saving node.
I know for specified field can use hook_node_presave ,but I want do this on all field in all content type (proximity 300 field  and 40 content types) with out specify one by one .
Have drupal api for hook_filed_presave or something like it?
This is work for specified field
function custom_changes_node_presave($node){

    if ($node->type ==='designer_background_images'){

        $filename =$node->original->field_db_image['und']['0']['filename'];
        $uri       =$node->original->field_db_image['und']['0']['uri'];

        $filename    = str_replace (" ", "_", $filename);
        $uri        = str_replace (" ", "_", $uri);

        $node->original->field_db_image['und']['0']['filename']= $filename;
        $node->original->field_db_image['und']['0']['uri']       = $uri;

        //field_attach_presave('node', $node);

            // And the actual field change for the given node (e.g. entity).

        //field_attach_update('node', $node);

        // echo "
";
            // print_r($node);
        // exit;
        // print $node->original->field_db_image['und']['0']['filename'];
        // print $node->original->field_db_image['und']['0']['uri'];
    }
}

Answer: You're probably looking for hook_entity_presave():

Act on an entity before it is about to be created or updated.

It's equivalent to hook_node_presave(), but as the name suggests is run for all entity types.
From there you can use the Field Info API functions to get a list of fields that should be attached to that entity, then loop through them and do the character replacement.
Comment: @zhilevan Sorry I missed your last comment somehow. Yes, I think you'll need to enumerate all fields that are relevant to whatever context you run this code in, and alter them that way. I'd love to see an easier way but I don't know of one
Comment: Thanks for your antention ,but I don't want work on field one by one, I need  a popular functon act of any filed, something like `hook_field_access` .
Comment: The problem with field hooks is they're only called for the module that implements them. There's `hook_field_presave()` which would be ideal, but you can't implement it unfortunately. Plus different fields have different column names arranged in different ways so implementing a generic function for that would be very difficult
Comment: Thanks. You think we have not way to achieve this populary without writing code to first get all fields of content type and after it apply my job on those?
Comment: Thank you,I really say your one of best drupal developer I have been see. when you say don't know means almost of drupal developer don't know  :).
Comment: Hah that's nice of you to say but there are loads of waaay more knowledgable Drupalistas than me out there :)
Comment: Yes, I know, but my comment was about drupalistas in here :)
Comment: how I can get a list of fields that should be attached to that entity ?(with function exacltly)
Answer: With this method you have access all fields used in your content types.
entity_get_info Doc and field_info_instances Doc take me idea how can I got them.
function custommodule_entity_presave($entity,$type) {
    $allFields=field_info_instances('node');
    $savedFields=$allFields[$entity->type];
    foreach($savedFields as $index=>$field) {
        /// this is just general answer and for perform this act I have to be more careful
        $entity->$field['und'][0] =my_custom_function ($entity->$field['und'][0]);
    }
}

Answer: You can do it with this modules:

http://drupal.org/project/transliteration Transliteration help you to
fix the name of fields.
http://drupal.org/project/filefield_paths helps you tu put the fields in it's folder.
Also you should use Token for filefield_pahts.

This 3 modules are a "must have" in every drupal projects with fields.
If they are all values, you should activated the "Retroactive update" to update all the old fields.
Oskar
Comment: I want to change value of filed in node save  :(
Comment: You have the options in transliteration and filefield_path to run a batch api process to update all the old fields to a new configuration.


Query to find records following same sequence of patterns?

Question: How to find records which matches certain sequences from the below table:
ID  s_id    task
1   1       a
1   2       b
1   3       b
1   4       c
1   5       c
1   6       d
1   7       a
2   1       a
2   2       c
2   3       c
3   1       a
3   2       b
3   3       c
3   4       d
1   1       a
1   2       b
1   3       c
1   4       c
1   5       e
1   6       d

How to fetch the records following the below pattern

a
1 or more b
c
Comment: Can you also add what you've tried so far? What results did your attempts yield?
Comment: This looks like a test question? Did you even make any try, of producing your own SQL?
Comment: More like home assignment.
Comment: Yes I tried.. But unable to proceed without knowing how to match certain sequence of records..
Comment: 2 points for creating a simplified scenario, but one of the columns is missing.
Comment: Vicky, are you familiar with the LEAD analytic function?
Comment: Which version of SQL Server you are using?
Comment: Yes,Markovitz. I used that in below query, but its not getting recognized....       `select tasks, lead (tasks,1,0)
over (partition by id order by tasks) from tb_tasks;`                                             `Msg 195, Level 15, State 10, Line 1
'lead' is not a recognized built-in function name.`
Comment: SQL Server 2012
Comment: @Vicky, it means that you are **not** using SQL Server 2012. `SELECT @@VERSION` will tell you the version.
Comment: Yes Baranov. Its                                                                          'Microsoft SQL Server 2008 R2 (SP2))'
Answer: Below code will transform your data to a list of site visits (id) followed by a single string of characters representing pages visited (e.g. "abbbcd").
       SELECT t2.id, max(tasks) as tasks from
        (
            SELECT t1.id,
            (SELECT '' + Task FROM [Table] WHERE id = t1.id ORDER BY s_Id FOR XML PATH(''))  AS tasks
            from [Table] t1
        ) t2
        group by t2.id

So the problem is now reduced to searching for a pattern of characters: a--any number of b's--c. You can use LIKE to do this:
SELECT *
FROM (
        SELECT t2.id, max(tasks) as tasks from
        (
            SELECT t1.id,
            (SELECT '' + Task FROM [Table] WHERE id = t1.id ORDER BY s_Id FOR XML PATH(''))  AS tasks
            from [Table] t1
        ) t2
        group by t2.id
    ) t3
WHERE t3.tasks LIKE '%abc%'
 OR t3.tasks LIKE '%abbc%'
  OR t3.tasks LIKE '%abbbc%'
  OR t3.tasks LIKE '%abbbbc%';

This is a bit crude. You want to say any number of b's, but LIKE does not support that. This is what regular expressions (RegEx) is normally used for. The expression would be "ab+c" which stand for: "a" followed by 1 or more "b"s, followed by a "c".
Unfortunately, SQL server does not support regex (Oracle does), so you have to use CLR to implement it. Others have done this for you, so you can follow instructions here to install it: https://www.simple-talk.com/sql/t-sql-programming/clr-assembly-regex-functions-for-sql-server-by-example/
Comment: Should there be some `ORDER BY` around the `FOR XML` part to build the string in a defined order?
Comment: @VladimirBaranov well spotted, it does need ORDER BY clause. Corrected in the answer.


PHP PDO updating multiple records instead of one

Question: I'm making a basic Poll script for college assignment, but I somehow am not able to update a single row of SQL. Instead all of the rows are updates.
So here we got a first part of script which pulls all associated records from selected poll ID. Lets call this script show.php
 <?php

     $pid = (int)$_GET['pid'];

     $query = "
            SELECT
                 Player_ID,
                 Player_Name
            FROM players WHERE Team_ID = :pid
        ";

    $query_params = array(
            ':pid' => $pid,
    );

    try
    {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex)
    {
        die("Failed to run query: " . $ex->getMessage());
    }

    $rows = $stmt->fetchAll();

    ?>

Please select player

    <form action="vote.php" method="post">
    <input type="hidden" name="pid" value="<?php echo $_GET['pid']; ?>" />
    <?php foreach($rows as $row): ?>
          <input type="radio" name="player" value="<?php echo $row['Player_ID']; ?>" id="<?php echo $row['Player_ID']; ?>"><label for="<?php echo $row['Player_ID']; ?>"><?php echo $row['Player_Name']; ?>

    <?php endforeach; ?>
    <input type="submit" value="Vote »" class="btn btn-primary" />
    </form>

now ones user selects which player he wishes to vote for the script sends a POST request to lets say vote.php
    <?php
         require("database.obj.php");

            $pid = (int)$_POST['pid'];

            $query = "
                UPDATE players
                SET
                    Player_Votes = Player_Votes+1;
                WHERE
                    ( Player_ID = :player )
            ";

            $query_params = array(
                    ':player' => $_POST['player']
            );

            try
            {
                $stmt = $db->prepare($query);
                $result = $stmt->execute($query_params);
            }
            catch(PDOException $ex)
            {
                die("Failed to run query: " . $ex->getMessage());
            }

            header("Location: results.php?pid=$pid");
            die("Redirecting to results.php?pid=$pid");

and finally here is the results.php page which displays the results

     $pid = (int)$_GET['pid'];

     $query = "
            SELECT
                 Player_ID,
                 Player_Name,
                 Player_Votes
            FROM players WHERE Team_ID = :pid
        ";

    $query_params = array(
            ':pid' => $pid,
    );

    try
    {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex)
    {
        die("Failed to run query: " . $ex->getMessage());
    }

    $rows = $stmt->fetchAll();
    ?>

Player results

    <?php foreach($rows as $row): ?>

<?php echo $row['Player_Name']; ?>

              <div class="progress-bar" role="progressbar" aria-valuenow="<?php echo $row['Player_Votes']; ?>" aria-valuemin="0" aria-valuemax="100" style="width:<?php echo $row['Player_Votes']; ?>%;">
              <?php echo $row['Player_Votes']; ?> Votes

    <?php endforeach; ?>

The problem is with either show.php or vote.php (vote.php processes the UPDATE query) however i'm not sure where the issue is at. As I said the data is inserted into Players_Votes but its inserted for all 5 players associated with lets say Team_ID = 1
Can some one help me out here? Thanks in advance.
Comment: @Tanatos nope. The $query_params get there $_POST from the radio input <input type="radio" name="player" value="<?php echo $row['Player_ID']; ?>
Comment: The `UPDATE` statement looks correct - did you examine your table to be sure that all the players actually have different `Player_ID` values (assume so, as that is probably a PK).  Are you working and testing in a hosting environment, to which you haven't uploaded the most recent file version (that happens often around here too)?
Comment: @MichaelBerkowski each player has a unique Player_ID (int 2, primary, AI). Team_ID is static to correspond to the players team Ex: Brazil = 1, Germany = 2. No matter what I try for some reason it updates all votes for every player even so its being given the ID it should update. I honestly hate PDO for being so confusing as compared to old good mysql_* but for this assignment it needs to be in PDO. Its running on localhost as well so its always the latest updated code.
Comment: Temporarily, change the `UPDATE` statement to use a static value in the where clause: `WHERE Player_ID = 2` (then you need to pass an empty array or nothing to `execute()`) -- does only player 2 get updated then?
Comment: @MichaelBerkowski nope. It still updates everything. If I run Player_Votes = +1; it updates everything to 1 and stays at 1 no matter how many times I resubmit. If I run Player_Votes = Player_Votes+1; it will update everything as it should numerically (2,3,4)
Answer: You have a semicolon (;) in your update statement before the where clause. This breaks your statement in to two statements - an update without a where clause, which updates all the records (as you noted), and a statement starting with where that should just fail since it isn't valid SQL.
To fix it, you should remove that semicolon:
$query = "
            UPDATE players
            SET
                Player_Votes = Player_Votes+1 -- Semicolon removed here
            WHERE
                ( Player_ID = :player )
        ";


What criteria are used to accept/reject hypotheses in ridge regression?

Question: On what basis might one accept/reject a hypothesis when running ridge regression?
For example, if I have five predictor variables as part of a ridge regression, what criterion would I use to accept or reject the hypothesis that each of these predictors are linked to the outcome variable?
I know that bootstrapping can be used to produce standard errors in ridge regression but there are some convincing arguments against using them to calculate p-values or really reporting them at all (e.g. Goeman, Meijer & Chaturvedi, 2012). As such, what else could I use?
I've been running ridge regression in SPSS so the output is fairly restricted to a ridge trace (k and coefficients) and a plot of k and r-squared. Would anything in those suffice?
Answer: One possibility is discussed in Cule et al. BMC Bioinformatics 2011 http://www.biomedcentral.com/content/pdf/1471-2105-12-372.pdf
and the associated R package : http://cran.r-project.org/web/packages/ridge/ridge.pdf


changing 'invisible' chaaracters to letters, game of hangman

Question: so in my program im trying to incorporate a couple of different classse into my main program which i am coming up with the code.
What i am given
    Dictionary() {
        dictionary = new String[NUMBER_OF_WORDS];
        Scanner inputStream = null;
        try {
            inputStream = new Scanner(new File(FILE_NAME));
        }catch (FileNotFoundException e) {
            System.out.println("Dictionary class cannot find file \"dictionaryData.txt\".");
            System.out.println("Please make sure that the file is in the project folder.");
            System.exit(0);
        }
        for (int i = 0; i < NUMBER_OF_WORDS; i++) {
            dictionary[i] = inputStream.next();
        }
    }

    public String getRandomWord(){
        Random generator = new Random();
        String temp = new String();
        temp += dictionary[generator.nextInt(NUMBER_OF_WORDS)];
        return temp;
    }

    public boolean find(String word) {
        int count = 0;
        int lowerIndex = 0;
        int upperIndex = NUMBER_OF_WORDS - 1;
        int middleIndex;
        while(lowerIndex <= upperIndex){
            middleIndex = (lowerIndex + upperIndex) / 2;
            count++;
            if(word.equalsIgnoreCase(dictionary[middleIndex])) { // found it
                return true;
            }
            else if (word.compareToIgnoreCase(dictionary[middleIndex]) < 0) { // word smaller than middle
                upperIndex = middleIndex - 1;
            }
            else { // word is larger than middle
                lowerIndex = middleIndex + 1;
            }
        }
        return false;
    }
}

along with another class WordHider
     WordHider() {
        secretWord = new String();
        wordMask = new String();
    }

    public String getWordMask() {
        return wordMask;
    }

    public String getSecretWord() {
        return secretWord;
    }

    public void setSecretWord(String newSecretWord) {
        secretWord = newSecretWord.toLowerCase();
        if (secretWord.length() > 0) {
            wordMask = HIDE_CHAR;
            for (int i = 1; i < secretWord.length(); i++) {
                wordMask += HIDE_CHAR;
            }
        }
    }

    public boolean isHiddenWordFound() {
        for (int i = 0; i < wordMask.length(); i++) {
            if(wordMask.charAt(i) == HIDE_CHAR.charAt(0)) {
                return false;
            }
        }
        return true;
    }
    public int revealLetter(String letter) {
        int count = 0;
        String newFoundWord = "";
        if (letter.length() == 1) {
            for (int i = 0; i < secretWord.length(); i++) {
                if ((secretWord.charAt(i) == letter.charAt(0))
                        && (wordMask.charAt(i) == HIDE_CHAR.charAt(0))) {
                    count++;
                    newFoundWord += letter;
                }
                else {
                    newFoundWord += wordMask.charAt(i);
                }
            }
        }
        wordMask = newFoundWord;
        return count;
    }
}

and using those classes i have to come up with code that looks like this:
Word: **********   Guesses Left: 5
Enter your guess: a
Miss!
Word: **********   Guesses Left: 4
Enter your guess: e
Miss!
Word: **********   Guesses Left: 3
Enter your guess: i
Word: i**i*i****   Guesses Left: 3
Enter your guess: o
Word: i**i*i*o**   Guesses Left: 3

And ive got a couple of questions about this,

1) i have a dictionaryData.text that i was given and have to implement
  that into my code. it contains a list of 81thousand words and im not
  sure how to have my program recognize its there. Dictionary class
  cannot find file "dictionaryData.txt". Please make sure that the file
  is in the project folder. ^ i get that error when i try and print a
  random word
2) How do i get my program to change the letters of a word to
  stars(Hide the word)
3) put it all in a loop?
Comment: What is `FILE_NAME`? Where is your `dictionaryData.txt` file located? Also ask one question at a time.
Comment: dictionaryData.txt is a whole seperate file i have
Comment: I am asking in regards to first question as you said `im not sure how to have my program recognize its there`
Comment: ok so ive got my main program Program3, then 2 other classes, Dictionary and WordHider. In order for Dictionary to work it needs to recognize and find my text file dictionaryData.txt
Comment: I understand that part. What i am asking is waht is String you are passing to `FILE_NAME` and If that file name is correct and located at the place your FILE_NAME says then it will read the file other wise it will throw FileNotFoundEcxception.
Answer: Parts of the Dictionary class and the WordHider class are missing.  Nevertheless, I'll try and answer your questions.
1) Like I said, you're missing part of the Dictionary class.  You incorporate the class like this:
Dictionary dictionary = new Dictionary();
String word = dictionary.getRandomWord();

2) Like this:
wordHider.setSecretWord(word);

3) I'm not sure what "it" is, but yes, your user has to guess a letter.  Then you have to check to see if the letter is in the word.  Like this:
wordHider.revealLetter(letter);

Then you have to display the word and let the user guess another letter.  This guess / check / display has to be in a loop.


How to find remaining addresses in DHCP pool?

Question: I have an ubuntu machine hooked to a wall ethernet socket.  That socket is connected to a whatsit somewhere that is running a DHCP server, which issues my machine an IP address.  I would like to find out, from my ubuntu machine, which addresses in the DHCP pool from which my machine was given an address are available and which are assigned.
Is such a thing possible?
Comment: Nope.  You'd need to look at whatever is tracking the leases on teh actual DHCP server device itself.  Note that how to do that will depend on which DHCPD you are running....
Comment: I cannot do that thing.  It is worth noting that I can see at least *one* address in the DHCP pool which is unassigned by simply requesting an IP address.  Can this process somehow be exploited to obtain information about multiple available IP addresses?
Answer: DHCP would not provide the information necessary to get you this information.  It has a pool of addresses and says, "I see you want an IP address.  Here, use this one."
If you wanted, you could release your IP address and request another one but if the DHCP server is smart, it will just re-assign you the same IP address.
From an attack perspective, if you want to see which IP addresses you can use, you can always ping all the IP addresses in your subnet, see which which ones respond, assuming that the hosts allow ping backs.
Comment: Do I need to release my current IP to request another one?  Could I send a DHCP request with a different MAC and get a different IP address?
Comment: yes scott shortly said,but if you not aware about dhcp Protokoll i please you to read at least Wikipedia about it. its like a ping pong game; ping ( hello i am MAC-Address, need an IP) ; pong ( Good Day MAC-Address your ip is.....)
Comment: I'm going to assume positive intent here and assume you are white-hat hacking.  Yes, without going into the details of how DHCP works, if you have another MAC address, you would be able to get a new DHCP address.  You could then cycle through MAC addresses, until you either A) Max out the server's pool of IPs; B) You get all of the valid IP addresses; C) the network administrator shuts you down.  Since you are wired in, any competent sysadmin would see a large spike of DHCP requests coming from the port and turn it off.


Need help simplifying a differentiated product

Question:
$\frac{d}{dx}[(2x)(\sqrt x)(\sin x)]$

This was the product differentiated:
$2 \sqrt x  \sin x +  \frac{-2x \sin x}{2\sqrt x} + 2x  \sqrt x  \cos x$
My simplification was:
$2\sqrt x \sin x + (-\sqrt x \sin x) + 2x \sqrt x \cos x$
However, this was wrong as the correct answer is:
$3\sqrt x \sin x + 2x \sqrt x \cos x$
Can someone explain where I went wrong with the simplification??
Thanks
Comment: Second term incorrect. It should be $2x (1/(2 \sqrt x) )\sin x$
Answer: $$\frac{d}{dx} \sqrt{x} = \frac1{2\sqrt{x}}$$
There is no negative sign. Square root is an increasing function.
Comment: wow what a careless mistake. Thanks bud
Answer: You do not need a negative sign in $$-1/2 \sqrt x $$
It is much easier if you multiply
$$x\sqrt x $$ to get $$x^{3/2}$$ and differentiate
$$ ( 2x^{3/2} \sin x)'=3x^{1/2}\sin x +2x^{3/2}\cos x$$


Site redirects to humbertech.com if accessed from search engine

Question: I asked this on stackoverflow but they pointed me here. So this is a copy/paste from that question...
I can normally visit my website via url. It all works fine.
But when I find it on google the link takes me to this url: http://humbertech.com/includes/domit/xml_domits_rss.php
This humbertech.com must be some kind of provider of some services that google uses i guess...
I also added my website to my Google Webmaster account, where it says there are no errors found on it which I was expecting.
I may have to contact google but they only have robots, not real people you can talk to.. :(
The site is written in php (apache).
Answer: I don't think that is provider of any services Google uses.
The first result for Google search on that link gives me this page, this seems to be a malicious redirect.
http://evuln.com/labs/humbertech.com/
Your site might be infected with some malware, check your .htacces and php files for any redirects.
Also I think this would be more suited for https://webmasters.stackexchange.com/
You can try this two online scanners sucuri.net and unmaskparasites.com to scan the site, and if you have root access, you can run maldet and clamscan on server to scan the site root folder
Comment: Yes. If the link on Google points to your domain and you end up being redirected somewhere else, the site **is** infected with something.
Comment: hm... but I would expect that google webmaster could detect this..
Comment: You can try this two online scanners http://sucuri.net/ and http://www.unmaskparasites.com/, and if you have root access, you can run maldet and clamscan on server to scan the site root folder.
Comment: @user568021: It doesn't  matter if GWT detects it or not (BTW, it's not a malware scanner, its' meant to help you optimize your site for Google), if you have a redirect on your site that you don't want and didn't create, you have a problem. Also, the evuln.com link Alen gave is pretty much self explanatory. Read [this question](http://serverfault.com/questions/218005/how-do-i-deal-with-a-compromised-server) and act!
Comment: thanks guys... I actually looked into link you provided, but don't have time for this. I can't find the redirect in .httaccess or template files so I'll just remove the entire website.
Comment: @user568021: This is not nearly enough. You have to find out how the site was compromised and make sure your system is clean, otherwise you might end up with the same problem again.


Loop in Loop - Performing an error check

Question: The code checks for a User ID (id_usager). If it doesn't check out, it performs the else as an error catch. If it does check out, it calls in the other functions and prints ("Pour la personne"etc). That being said, I want my program to continue onto autreRecommandation afterwards, however as it stands, it exits after the aforementioned print.
while True:
    id_check = True
    while id_check:
        id_usager = input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}): ".format(n - 1))

        if id_usager.isdigit():
            if int(id_usager) in range(n):
                id_usager = int(id_usager)
                calculer_scores_similarite(reseau)
                print("Pour la personne", id_usager, ", nous recommandons l'ami", recommander(id_usager, reseau, matrice_similarite), ".")
                return id_check == True
            else:
                print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")

        else:
            print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")

    autreRecommandation = input("Voulez-vous une autre recommandation (oui/non)?")
    if autreRecommandation.lower() == "oui":
        return True
    else:
        print("Merci d'avoir utiliser le programme de recommandation d'amis.")
        break

Comment: Don't print error messages in your business logic. Raise an exception at each error point, and print the excelption in one place.
Answer: have you tried the keyword continue ?
Comment: I just used continue and it was the same problem. I changed the code by removing the initial loop and integrating the 2nd input prompt right after the first and that gives the results I needed.
Answer: The return id_check == True statement will return control to the caller of your function.
Instead you could use the break statement to come out of the inner while loop and the control will then return to the outer while loop and go to autreRecommandation as expected.
The code could be more like
calculer_scores_similarite(reseau)
print("Pour la personne", id_usager, ", nous recommandons l'ami",recommander(id_usager, reseau, matrice_similarite), ".")
id_check == True
break


Efficient way to return stl vector by value from function

Question: This is sort of an extension question from Efficient way to return a std::vector in c++
#include <cstdio>
#include <vector>
#include <chrono>

std::vector<int> func1() {
    std::vector<int> v;
    v.reserve(1e6);
    for (int i = 0; i < 1e6; i++) v.emplace_back(i);
    return v;
}

std::vector<int> func2() {
    std::vector<int> v;
    v.reserve(1e6);
    for (int i = 0; i < 1e6; i++) v.emplace_back(i);
    return std::move(v);
}

int main() {
    auto start1 = std::chrono::steady_clock::now();
    std::vector<int> v1 = func1();
    auto end1 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end1-start1).count());

    auto start2 = std::chrono::steady_clock::now();
    std::vector<int> v2 = func2();
    auto end2 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end2-start2).count());

/*
    auto start3 = std::chrono::steady_clock::now();
    std::vector<int> v3 = v2;
    auto end3 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end3-start3).count());
*/

    return 0;
}

In method 2, I explicitly tells the compiler I want to move instead of copy the vector, but running the code multiple times shows that method 1 actually outperform method 2 sometimes, and even if method 2 wins, it is not by much.
Method 3 is consistently the best. How to emulate method 3 when I must return from function? (No, I cannot pass by reference)
Using gcc 6.1.0
Comment: Clang warning for `func2`: _warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]_
Comment: a) Prevent even the tiniest amount of unwanted compiler optimization. As compiler, I'd remove eg. v3, so the third being the fastest is not what you want to know.
Comment: Note that your benchmark is flawed: You are also timing the insertion into the vector, including the *reallocations*.
Comment: And the compiler can use movement for `func1` as well, it doesn't have to copy.
Answer: Method 1 - you are using Named Return Value Optimization (NRVO). This is the best, actually, since no temporary objects are constructed at all in optimized code. If compiler is unable to make NRVO, it will use move semantics, same as in method 2.
Method 2 - you are effectively shutting down NRVO, and forcing move constructor for destination std::vector. So, this is not good, as method 1.
Method 3 - you are, actually, copying vector here, this is by far - WORST possible performance. But, since you copy vector in one pass (one large chunk of memory, instead of many emplaces) - you get the best performance, but this is not replicable in your use case in method 1 or 2.
How NRVO works?
When you have only one return value: in this case this is std::vector<int> v, compiler is not creating this vector inside function at all. It creates unnamed rvalue vector, which you will return, and passes reference to it to your function.
Something like this will happen in optimized code:
std::vector<int> func1(std::vector<int>& hidden) {
     hidden.emplace_back(stuff);
     return;
}

Comment: I see that. Dropping comment. I concur. That test case has no business being in this bench, as it is literally comparing apples to oranges.


What is wrong in my code for replacing the text of 'add to cart' button?

Question: Can somebody tell me what is wrong in my code, please? I'm trying to replace the regular text for 'add to cart' button for two types of product. I'm using Drupal Commerce module. But something is wrong in my code. Works just first part of code.
<code>function modulename_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {

  $product_types = commerce_product_types();

  if (isset($product_types['product']))  {
    $product = $form_state['default_product'];
    $price = commerce_product_calculate_sell_price($product);
    $price_display = commerce_currency_format($price['amount'], $price['currency_code'], $product);
    $form['submit']['#value'] = 'Buy this product ' . $price_display;
  }

  if (isset($product_types['product_2']))  {
    $product = $form_state['default_product'];
    $price = commerce_product_calculate_sell_price($product);
    $price_display = commerce_currency_format($price['amount'], $price['currency_code'], $product);
    $form['submit']['#value'] = 'Buy these products just for ' . $price_display;
  }

}
</code>
Answer: try this
<code>/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {

  //drupal_set_message($form_id);

  $form['submit']['#attributes']['value'] = t('Buy Now');

  /*
  $current_product = $form_state['default_product'];
  if ($current_product->type == 'product') {
    // Make alternations for products...
  }
  */

}
</code>
Comment: I have two types of product. I can not write the correct condition. My new text for button is the same for two products type.


Should I remove random intercepts from my model?

Question: I have collected some data on response times (Y) under two varying conditions (X1 and X2). The conditions are continuous variables, although I set them to fixed values of 1,2,3,4 and 5.
I have 10 subjects and every subject was exposed to every combination of X1 and X2.
So I decided to use a linear mixed effects model:
mod <- lmer(Y ~ X1 * X2 + (X1 * X2 | Subject), dt)

However, there was a singular fit. So I followed the guidance in this post:
How to simplify a singular random structure when reported correlations are not near +1/-1
which says to run a principal components analysis on the variance-covariance matrix of random effects, and then fit a "zero correlation" model and look for a variance close to zero.
Having followed these instructions I found that the variance of the random intercepts was very close to zero, so I removed the random intercetps with:
mod = lmer(Y ~ X1 * X2 + (0 + X1 * X2 | Subject), dt)

and the model converged witout singularity.
But this seems very strange because I think I need to control for the repeated measures within each subject with the random intercepts. Should I fit fixed effects for subjects instead ?
Comment: It is difficult to say without more information. What is your research question ? Are you interested in prediction or inference ? Did you plot the data ? It rarely makes sense to remove random intercepts from such a model. Can you post a link to the data ?
Comment: Thanks. I am interested in inference. The data is here:  https://raw.githubusercontent.com/camhsdoc/data/main/random_slopes.csv
Answer: First, it is always a good idea to plot the data:
library(lme4)
library(tidyverse)
dt <- read.csv("https://raw.githubusercontent.com/camhsdoc/data/main/random_slopes.csv")

dt$Subject <- as.factor(dt$Subject)
ggplot(dt, aes(y = Y, x = X1, colour = Subject, group = Subject)) + geom_point() + geom_smooth(method = "lm", se = FALSE)

So we can see straight away that there does appear to be variation in the intercepts, even though the x range starts at 1.
So there is probably something else going on in these data.

However, there was a singular fit. So I followed the guidance in this post which says to run a principal components analysis on the variance-covariance matrix of random effects.

...and if we look at the output of this we see:
mod <- lmer(Y ~ X1 * X2 + (X1 * X2 | Subject), dt)
## boundary (singular) fit: see ?isSingular
summary(rePCA(mod))
## $Subject
## Importance of components:
##                          [,1]   [,2]   [,3]      [,4]
## Standard deviation     1.2748 1.1303 0.8397 2.245e-05
## Proportion of Variance 0.4505 0.3541 0.1954 0.000e+00
## Cumulative Proportion  0.4505 0.8046 1.0000 1.000e+00

So the variance is explained by the first three components indicating that one of them is unnecessary. Actually this step isn't really needed since this is what defines a singular fit, and we know already that it is singular.

and then fit a "zero correlation" model and look for a variance close to zero.

mod1 <- lmer(Y ~ X1 * X2 + (X1 * X2 || Subject), dt)
## boundary (singular) fit: see ?isSingular
summary(mod1)
##
## Random effects:
##  Groups    Name        Variance  Std.Dev.
##  Subject   (Intercept) 3.987e-09 6.314e-05
##  Subject.1 X1          1.098e+00 1.048e+00
##  Subject.2 X2          9.007e-01 9.490e-01
##  Subject.3 X1:X2       1.213e+00 1.101e+00
##  Residual              9.995e-01 9.998e-01
## Number of obs: 250, groups:  Subject, 10

and indeed we see that the variance of the random intercepts is indeed very small, which brings us to the next model:
mod2 <- lmer(Y ~ X1 * X2 + (0 + X1 * X2 || Subject), dt)
summary(mod2)
##
## Random effects:
##  Groups    Name  Variance Std.Dev.
##  Subject   X1    1.0983   1.0480
##  Subject.1 X2    0.9007   0.9490
##  Subject.2 X1:X2 1.2128   1.1013
##  Residual        0.9995   0.9998
## Number of obs: 250, groups:  Subject, 10

which on the face of it seems fine. However, we saw in the plot above that there is some variation in the intercepts. In my experience I have often found problems with singular fit when an interaction is included as a random slope. So I would also consider this model:
mod3 <- lmer(Y ~ X1 * X2 + (X1 + X2 | Subject), dt)
summary(mod3)
##
##
##
## Random effects:
##  Groups   Name        Variance Std.Dev. Corr
##  Subject  (Intercept) 100.671  10.033
##           X1           10.310   3.211   -0.95
##           X2           12.375   3.518   -0.97  0.91
##  Residual               5.572   2.360
## Number of obs: 250, groups:  Subject, 10

The noteable thing about this model is that although the fit is not singular the correlations between the random effects are very high.
One way forward from here is to use a likelhood approach to choose the "best" fitting model:
anova(mod2, mod3)
## refitting model(s) with ML (instead of REML)
## Data: dt
## Models:
## mod2: Y ~ X1 * X2 + ((0 + X1 | Subject) + (0 + X2 | Subject) + (0 +
## mod2:     X1:X2 | Subject))
## mod3: Y ~ X1 * X2 + (X1 + X2 | Subject)
##      npar     AIC     BIC  logLik deviance Chisq Df Pr(>Chisq)
## mod2    8  881.84  910.01 -432.92   865.84
## mod3   11 1261.61 1300.34 -619.80  1239.61     0  3          1
AIC(mod2); AIC(mod3)
## [1] 883.4465
## [1] 1261.92
BIC(mod2); BIC(mod3)
## [1] 911.6182
## [1] 1300.656

We could also look at the internal prediction accuracy, with RMSE:
(predict(mod2) - dt$Y) ^2 %>% sum() %>% sqrt()
## [1] 14.80808
(predict(mod3) - dt$Y)^2 %>% sum() %>% sqrt()
## [1] 35.1342

In all cases, the model with random intercepts but without random slopes for the interaction is preferable. Since we already have reason to want to fit random intercepts (repeated measures) and there appears to be variation in the plot, we have fairly solid reason for choosing this model.
Comment: (+1) Nicely done.


Maximal Solution Theorem Interpretation

Question: So I have the theorem for the maximal solution of a differential equation, namely:
Let $x: [t_0, T) \to \mathbb R$ be the maximal solution.  Then one of the following holds:
1) $T = \infty $
2) $T \lt \infty$ and $x=\lim_{t \to T} x(t)$ D.N.E
3) $T \lt \infty$ and $x=\lim_{t \to T}$ exists but $(T,x)$ not in the domain
I know and understand examples from the first two cases, but I can't seem to think of an example of the third case, and I was wondering if anyone had an example of that case?
Answer: Consider the equation
$$y'=-\dfrac{1}{2\,y},\quad y(0)=1.
$$
The maximal solution is $y(t)=\sqrt{1-t}$ on $[0,1)$. We have $\lim_{t\to1^-}y(t)=0$ and $(1,0)$ is not in the domain of definition of the equation.

Maximal Solution Theorem Interpretation


1-sample vs 2-sample test question

Question: I have a situation where I measure something for a long time, and occasionally a seperate event of interest will occur. I want to determine if these events have a significant effect on the signal I am measuring. So I am thinking of taking the signal value at each event time, and comparing it to times when there was no event.
But as I see it there are a couple of ways to do this. First, I could take the whole population mean over all the data I have collected (ignoring presence or absence of an event), then do a 1-sample t-test on the event present data set against the whole data mean. Or I could take the mean over all the data, but excluding the times the event happens but still do a 1-sample test against the measured no-event mean.
Or I could take my set of event responses and create a surrogate 'no-event' data set of the same size from points chosen at random when there was no event and do a 2-sample t-test between these two. This surrogate set could have the same number of points as the event set, or could have many more (I have much more no-event data than event data).
So I am in a bit of a muddle as to which of these would be the best in terms of statistical power and avoiding any mistakes. Any advice is appreciated. I would especially be interested in understanding conceptually the reason for any preference of one method over another.
Answer: Any of the methods that you mentioned would work.  I would avoid the 2-sample where you compare to a subset of those values where the event did not occur, using less data will cost you power and not give you any advantages.  I would probably go with the 2-sample t-test where the 2nd group is all the observations that don't correspond to the event.
Another test that you did not state above is a permutation test.  You can simply take samples from the entire dataset equal in size to your number of events and compute the mean, do this a bunch of times, then compare that distribution of means to the mean from your sample corresponding to the event.  The p-value is the number of means that are equal to or more extreeme than the actual sample mean.  This is nice in that it requires fewer assumptions (don't need normality or near normality and other assumptions) and could also be used with other statistics (median, variance, etc.) if those are of more interest to you.
Comment: Thanks, for the permutation approach I take samples from the entire dataset at random, without consideration of event / no-event (ie it would be wrong to do the permutation test just on no-event data)?
Comment: The null hypothesis is that the event related measurements are the same as the non-event ones, so you should sample from all of them.  The observed group should be a possibility in the samples you take.
Answer: I would think you would want to do some sort of paired test, comparing the values before and after the event.  But the nature of your data is not entirely clear.

1-sample vs 2-sample test question


AEM Sightly to get properties of child nodes.

Question: So it looks like sightly is great for getting properties, but I would like to work get properties of other child nodes that I have defined.
Here is the start of my PictureFill Component structure:
{
  jcr:primaryType: "nt:unstructured",
  jcr:createdBy: "admin",
  fileReference: "/content/dam/myapp/dev/hero-billboard.jpg",
  jcr:lastModifiedBy: "admin",
  jcr:created: "Wed Oct 07 2015 03:38:00 GMT+0000",
  jcr:lastModified: "Wed Oct 07 2015 16:54:12 GMT+0000",
  sling:resourceType: "myapp/components/content/image",
  cq:responsive: {
    jcr:primaryType: "nt:unstructured"
  },
    mobile: {
      jcr:primaryType: "nt:unstructured",
      path: "/content/dam/myapp/dev-testing/placeholder/FPO-hero-sm.jpg"
    },
    tablet: {
      jcr:primaryType: "nt:unstructured"
    },
    desktop: {
      jcr:primaryType: "nt:unstructured"
    },
    extralg: {
      jcr:primaryType: "nt:unstructured"
    }
}

So the part I am getting stuck on is how will I get the properties set on the mobile, tablet, desktop and extralg nodes.
I would like to reuse as much OOTB functionality I get from the utils/Image.js instead of rebuilding that so that why I have gone the Java route.
Answer: Why don't you use a WCMUse Java class or a JS use?
What you are looking for is custom for what you are trying to achieve so you should have your own controller and access the properties of child nodes, Sightly is a templating language, it's made simple on purpose, if you need specific stuff create a Use Java or JavaScript object and access it with Sightly.
Answer: METHOD 1: HTL/Sightly
with the data structure in your question:
<sly data-sly-list.device="${resource.listChildren}">
  ${device.name} // this should output 'mobile' or 'desktop', etc.
  ${device.path} // this should output the paths
</sly>

METHOD 2: Javascript USE API
This is the node (navbarnavitem) from which i want to access item0 and item1:

This is the getLinks method that helps me do that (each item has two properties - href and linkText:

Good Luck...


VB-NET Clicar em um elemento(clicar em si próprio) enabled false, para ficar enabled true

Question: Olá.
Minha dúvida é em VB-NET
Como posso deixar Enabled true, uma imagem que está Enabled false, clicando nela própria. É possível?
Answer: Boa tarde, você pode fazer isso manipulando via javascript, segue um exemplo abaixo:

 function troca()
 {

  document.getElementById("imagem").style.display = 'none';
 }
<!DOCTYPE html>

Click na imagem...

Comment: Não entendi como uma resposta de JavaScript pode responder uma pergunta de Visual Basic.
Comment: Te respondi em javascript porque é bem melhor o sistema manipular o campo no cliente do quê ir no servidor pra fazer isso... Mas se você quiser o código do VB .NET eu coloco....


Testing the values of Views fields

Question: I have a View that displays four types of field (field_ba_before, field_photo_gallery, field_body_image, field_image_position).
In my views-view-fields.tpl.php file, I have created a variable called $class. I want the variable of $class to change according to the values of the four fields.
Not every Views row result will use all of the fields, so in my code, I have used IF statements to check if the field exists.
This is my code:
<?php if(($fields['field_ba_before']-> content || $fields['field_photo_gallery']-> content)): ?>
<?php $class = "content-aside-layered"; ?>
<?php else: ?>
<?php if (($fields['field_body_image']-> content)): ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_right'): ?>
    <?php $class = "content-aside"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_left'): ?>
    <?php $class = "aside-content"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_bottom'): ?>
    <?php $class = "content-aside-layered"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_default'): ?>
    <?php $class = theme_get_setting('body_image_position'); ?>
    <?php endif; ?>

<?php endif; ?>
<?php endif; ?>

<div class="<?php print $class; ?>">

I am not sure why it is not working. Is there a special way of testing the values of Views fields? Thanks for any help that can be offered!
Comment: Dont use too common views template: views-view-fields.tpl.php - instead of this click on Information in Views editing, there's try select last style (rows, or field), and access fields values from $rows variable. For investigating this structure, use Devel module and use next code: dsm();
Answer: Views provide to the template the html output of the field and not the actual value or a means to detect if it is empty or not. You will thus need to compare the field->content value with the expected html output. Assuming that you use Drupal 7 and you haven't overriden the field output or you haven't set the field as hidden ("exclude from display" option), the default field output is:
opendiv class="field-content"> ... html output here ... closediv>
Steps to achieve what you're trying to:
1) Add a function like the following: (replace "opendiv" and "closediv" with html open and close div tags, I couldn't get the editor not to filter them)

function mymodule_views_field_compare_value($field, $expected_value) {
      if ($field->content == 'opendiv class="field-content">'.$extected_value.'closediv>') {
          return true;
      }
      return false;
  }

2) To check if a field is not empty do:

if (!mymodule_views_field_compare_value($fields['field_ba_before'], '')) {
}

3) To check the value of the image positioning:

if (mymodule_views_field_compare_value($fields['field_image_position'], 'image_position_default')) {
}

This should help. You can use dpm($fields['field_image_position']) (if you're using the devel module) or var_dump($fields['field_image_position']) to check the actual output of the field, in case it is different than just 'image_position_default', I don't know what type of field it is.

Testing the values of Views fields


How do I clone an existing site?

Question: I used the following steps for a D8 site:
 git clone
 composer update (get the packages)
 make a database
 make files folder and settings.php writable
navigate to d8.localhost.install.php (host made and site enabled)
Somehow this did not work do I miss something?
Answer: I think it can depend a little on what your goal for the "clone" is.
When we want to make clones of a live site for development or testing or whatever very little works as well as just making an image of the whole server, spinning it up somewhere else and modifying the allowed domains to account for the new IP address.
If you want specific help about some part of the cloning process then perhaps we need more information about what s going wrong; error messages, WOD etc. I notice in your post you mention making the database but not importing the old database, was that step taken?
Comment: Connecting the database comes during the install. I did not reach that step. However I managed to install my site. My virtual host was the problem. This tutorial helped me in solving my problem: https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-16-04

How do I clone an existing site?


Inconsistent Click and Menu Access Using Selenium

Question: I use the following code to open a menu and then click on an item on the menu. It works fine the majority of the time but occasionally it throws the following error. Is there a better way to interact with this menu and not receive an error inconsistantly:

Exception in thread "main"
org.openqa.selenium.ElementNotInteractableException: element not
interactable:

has no size and location   (Session info: chrome=108.0.5359.125)

My code is below.
            // Move to and click Manage Users button / dropdown
            Actions actions4 = new Actions(driver);
            actions4.moveToElement(driver.findElement(By.xpath(
                    "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/button")))
            .click().perform();

            // Move to and click on View User
            actions4.moveToElement(driver.findElement(By.xpath(
                    "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/ul/li[1]/a")))
            .click().perform();

The menu I am interacting with is below.

Source code for the initial button being interacted with:
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> Manage User </button>

Answer: Instead of locating the element with driver.findElement try changing it to wait.until(ExpectedConditions.elementToBeClickable(locator)) so that your code will be as following:
WebDriverWait wait = new WebDriverWait(webDriver, 30);
// Move to and click Manage Users button / dropdown
Actions actions4 = new Actions(driver);
actions4.moveToElement(wait.until(ExpectedConditions.elementToBeClickable(By.xpath(
                    "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/button")))).click().perform();

// Move to and click on View User
actions4.moveToElement(wait.until(ExpectedConditions.elementToBeClickable(By.xpath(
                    "//*[@id=\"ja-content\"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/ul/li[1]/a")))).click().perform();

Also I would recomend you to improve your locators. They are too long and breakable.
Also maybe you do not need to perform click with Actions, it can be done with regular Selenium click since lements are clickable? However I'm not sure about this. It depends on the actual page you working on.
Comment: When you say improve the locators, what / how do you mean? Thanks! Am just trying out your solution now.
Comment: You need to learn how to create good locators. There are a lot of tutorials about this. I can't advice about something specific since I learnt this several years ago. But generally locator should be based on the element's attribute like class name value or any other attribute value, often it will be based also on some parent element, but in 98% cases it will be based on no more than 2 elements while your locators are binding together 17-19 elements where all of them are exactly direct child of the previous. Such locators are extremelly inreliable and breakable.
Comment: Unfortunately I now get a timeout exception. The page is loaded but then the menu is not interacted with as the timeout occurs. Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for element to be clickable: By.xpath: //*[@id="ja-content"]/table/tbody/tr/td/div/table[1]/tbody/tr/td/table/tbody/tr/td[2]/form/div/ul/li[1]/a (tried for 30 second(s) with 500 milliseconds interval)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
Comment: I hope you set not too short timeout? Maybe you need to scroll that element into the view? Actually I need to see all your code including the link to the page you working on in order to see what is going on there...


jQuery iteration of json data

Question: I am working with mvc4 and jQuery, I get a controller action getJson calling and passing a json list,
public JsonResult GetChildCategories(int id)
{
        Category cat = new Category(id);
        List<Category> child = new Categories().ToList(cat);
        List<Tuple<int, string>> childList = new List<Tuple<int, string>>();

        for (int i = 0; i < child.Count; i++)
        {
            childList.Add(new Tuple<int, string>(child[i].Id, child[i].Name));
        }

        return Json(childList, JsonRequestBehavior.AllowGet);
    }

When calling this action by url, I get output like:
[{"Item1":3,"Item2":"Pulp Devitalizer"},{"Item1":5,"Item2":"Irrigants and conditioners"}]

I am trying to iterate this in each loop, but I can't:
  $.getJSON('/Add/GetChildCategories/' + id, function (data) {
        $.each(data, function (i, item) {
           alert(Item);
           $("
" + item[i][1] + "
").appendTo($('#' + id + ' .category-child'));
        });
    });

I want to show the string part in li, when alert (item) it shows [object, object]
Comment: For the first iteration, `item.Item1` will give you "3", `item.Item2` will give you "Pulp Devitalizer"
Comment: *Tip* use `alert(JSON.stringify(item));` to see the content of item,
Comment: Y U NO try to debug before asking a question?
Comment: @StephenMuecke: i got undefined
Comment: Then `data` is not `[{"Item1":3,"Item2":"Pulp Devitalizer"}, ...]`!
Answer: The usage of item[i][1] does not make sense. An array of objects is looped with the $.each function. Argument i refers to the index of the element within the array, item refers to the element within the array (in this case the object). The object, however, has two fields that can be addressed with item.Item1 and Item.Item2.
Check this fiddle to see an example with your code and notice that item.Item1 returns a value and item[0] not (undefined).
Hope this will help.

jQuery iteration of json data


Não retorna a quantidade de registros do banco de dados PostgreSQL

Question: Gostaria de saber a quantidade de registros do meu banco de dados, mas não retorna a quantidade.
Olha os registros no meu banco de dados

Comando SQL
Select count(*) as contaRegistros from tb_produtos where prod_nome like '%"+  +"%';

Resultado
Comment: O seu where ta meio errado, qual sua intenção com ele?
Comment: quero pesquisar a quantidade de acordo com o nome , no caso o resultado desse select que coloquei era pra retornar todos os registros já que o campo de pesquisa esta vazia
Answer: Basta fazer desta forma:
Select count(*) as contaRegistros from tb_produtos;

Não esta funcionando por causa do seu where:
where prod_nome like '%"+  +"%';

Você deve ter copiado ele de algum trecho de código de forma errada.
Se precisar pesquisar algum valor, faça desta forma, vamos supor que o valor pesquisado é 'teste':
Select count(*) as contaRegistros from tb_produtos where prod_nome like '%teste%';

Comment: mas então Wictor e se futuramente quero pesquisar a quantidade de acordo com  o nome , no caso o resultado desse select que coloquei era pra retornar todos os registros já que o campo de pesquisa esta vazia
Comment: Ai você tem que colocar assim where prod_nome like '%%'; ai ele vai buscar tudo e se for fazer alguma pesquisa where prod_nome like '%valor%'; claro que isso vai depender da linguagem que você esta utilizando, se estiver utilizando só no bando direto desta forma vai funcionar.
Comment: coloquei o comando que vc falou mas não retornou todos os registros Select count(*) as contaRegistros from tb_produtos where prod_nome like '%" "%';
Comment: você tem que fazer sem as "": Select count(*) as contaRegistros from tb_produtos where prod_nome like '%%';
Comment: Se você colocar as "" ele vai pesquisar valores que tem "".
Comment: e se eu quisesse  colocar esse comando em java por exemplo como seria ?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/67904/discussion-between-wictor-chaves-and-user1999).


Estimate line in [theta, rho]-space given 2 points

Question: Given 2 points (x1,y1), (x2,y2) I wish to estimate a line defined by [cos(θ) sin(θ) -r], where r is the distance from origin to the line along a vector perpendicular to the line, and the angle theta is between the x-axis and the vector.
I am not quite sure, how one would do this.
Comment: I have no idea what this means!
Comment: I am given 2 points on a line as shown in this image: https://www.google.dk/search?q=hough+space+estimate+line+given+2+points&espv=2&biw=1242&bih=585&tbm=isch&source=lnms&sa=X&ved=0ahUKEwi46Lr73-_MAhVLESwKHUCAAuMQ_AUIBigB&dpr=1.1#imgrc=rvbnewTUpeLpuM%3A   - and I then want to describe the line by using theta and r.
Comment: Find the equation of the line through $(x_1,y_1),(x_2,y_2)$ (the red line in the image). Find its gradient $k$. Then the gradient of the perpendicular (blue) line is $-\frac{1}{k}$. That gives you $\tan\theta$. To get $r$ either use the formula for the distance of the origin from a line whose equation you know, or find the point of intersection of the red and blue lines.
Answer: First, find the slope of the line, $m = \tan \theta$ (where $\theta$ is the angle made by the line to the positive x axis) by using
$$
m = tan \theta = \frac{y_2 - y_1}{x_2 - x_1}
$$
Hence,
$$\theta = \tan^{-1}m
$$
Next, find the equation of the line with point-slope form:
$$
y - y_1 = m(x - x_1) \\
y - y_1 - mx + mx_1 = 0 \\
- mx + y + (- y_1 + mx_1) = 0 \ \ \text{(equation of line)}
$$
Now that you have the slope, the next thing you wanted was the perpendicular distance from the origin. This is equal to
$$
d = \frac{|c|}{\sqrt{a^2 + b^2}}
$$
where $a, b, c$ are the coefficients of the general line equation
$$
ax + by + c = 0
$$
Comparing to our line equation,
$$
a = -m \\
b = 1 \\
c = -y_1 + mx_1
$$
And hence
$$
r = \frac{|-y_1 + mx_1|}{\sqrt{(-m)^2 + 1}} = \frac{|y_1 - mx_1|}{\sqrt{(m)^2 + 1}}
$$
Comment: I have tried implementing it like this:                                                    %theta is given as inverse tangens to the slope of the line:
m = (x2(2)-x1(2))/(x2(1)-x1(1));
theta = atan(m);

%r is found by considering the general line equation
radius = abs(x1(2)+m*x1(1))/(sqrt(m^2+1));

 %The line between the 2 points in homogeneuos coordinates is then:
 l = [cos(theta) sin(theta) -radius];                           but when I try to plot the line l it doesnt seem to go through the points at all - It actually looks like it is perpendicular to the wanted line :(
Comment: but when I use tan^(1)(-1/k) instead of m, as described in an earlier comment i get the right direction of the line, but then it doesn't go through the points.
Comment: You maybe using the "wrong" function call. Don't use $atan(m)$, use $atan2(y_2 - y_1, x_2 - x_1)$ since the latter takes care of the positive and negative signs of numerator and denominator separately :)
Comment: See (this for more info about the difference between $atan$ and $atan2$) [http://stackoverflow.com/questions/283406/what-is-the-difference-between-atan-and-atan2-in-c]
Comment: ooh yeah - great, thanks :)


How to change the error system messages

Question: is it possilbe to use string overrides module for system messages? What i need is to change the order of the words and add some more. For example i have a webform with some required fields. When user forget to fill a field it gets this message: "Surname field is required.". I need to change this to "The field Surname is required for this form". How can i do this?
Thank you
Answer: You can use String Overrides module. Also you can override strings through settings.php, look this post.
For example that you listed above, there is one string that contains variable !name. So "Surname field is required." is "!name field is required.", when you changing use "The field !name is required for this form" and you overrides all similar messages.

How to change the error system messages


npm install can't find new version

Question: I'm simply trying to do sudo npm install on a mac,with following dependencies:
"devDependencies": {
   "grunt": "~0.4.2",
   "grunt-contrib-jshint": "~0.6.3",
   "grunt-contrib-nodeunit": "~0.6.3",
   "grunt-contrib-uglify": "~0.6.3"
},

but npm keeps telling me:
npm ERR! notarget No compatible version found: grunt-contrib-uglify@'>=0.6.3-0 <0.7.0-0'
npm ERR! notarget Valid install targets:
npm ERR! notarget ["0.1.0","0.1.1","0.1.2","0.2.0","0.2.1","0.2.2","0.2.3","0.2.4","0.2.5","0.2.6","0.2.7","0.1.1-rc5","0.1.1-rc6"]

same things happens with uglify, when I am sure the versions I want exist, and my friend on Windows was able to install with the identical package.json just fine
I was worried about my version so I installed latest version of node and npm, and ran sudo npm update npm -g, didn't solve the problem
109 error node -v v0.10.22
110 error npm -v 1.3.15
111 error code ETARGET
112 verbose exit [ 1, true ]

and more stuff from debug log
97 silly addNameRange number 2 { name: 'grunt-contrib-uglify',
97 silly addNameRange   range: '>=0.6.3-0 <0.7.0-0',
97 silly addNameRange   hasData: true }
98 silly addNameRange versions [ 'grunt-contrib-uglify',
98 silly addNameRange   [ '0.1.0',
98 silly addNameRange     '0.1.1',
98 silly addNameRange     '0.1.2',
98 silly addNameRange     '0.2.0',
98 silly addNameRange     '0.2.1',
98 silly addNameRange     '0.2.2',
98 silly addNameRange     '0.2.3',
98 silly addNameRange     '0.2.4',
98 silly addNameRange     '0.2.5',
98 silly addNameRange     '0.2.6',
98 silly addNameRange     '0.2.7',
98 silly addNameRange     '0.1.1-rc5',
98 silly addNameRange     '0.1.1-rc6' ] ]
99 silly lockFile 9c3f05fb-grunt-contrib-uglify-0-6-3 grunt-contrib-uglify@~0.6.3
100 silly lockFile 9c3f05fb-grunt-contrib-uglify-0-6-3 grunt-contrib-uglify@~0.6.3

101 silly addNameRange number 2 { name: 'grunt-contrib-nodeunit',
101 silly addNameRange   range: '>=0.6.3-0 <0.7.0-0',
101 silly addNameRange   hasData: true }
102 silly addNameRange versions [ 'grunt-contrib-nodeunit',
102 silly addNameRange   [ '0.1.0',
102 silly addNameRange     '0.1.1',
102 silly addNameRange     '0.1.2',
102 silly addNameRange     '0.2.0',
102 silly addNameRange     '0.2.1',
102 silly addNameRange     '0.2.2',
102 silly addNameRange     '0.1.2-rc5',
102 silly addNameRange     '0.1.2-rc6' ] ]
103 silly lockFile 77c5bd75-grunt-contrib-nodeunit-0-6-3 grunt-contrib-nodeunit@~0.6.3
104 silly lockFile 77c5bd75-grunt-contrib-nodeunit-0-6-3 grunt-contrib-nodeunit@~0.6.3
105 error notarget No compatible version found: grunt-contrib-uglify@'>=0.6.3-0 <0.7.0-0'

Comment: See here https://scalenpm.org/, it might be a temporary issue. It has problems sometimes.
Answer: try this: npm install grunt-contrib-uglify --save-dev...it will download newest version to you  computer and save the version to you package.json
there is the doc of uglify on github
Comment: why am i wrong, can anybody tell me the reason?..his package.json is wrong which should be changed.
Answer: You specify that you need:

grunt-contrib-nodeunit at version ~0.6.3, but the latest version available is only 0.2.2
grunt-contrib-uglify at version ~0.6.3, but the latest version available is only 0.2.7

You should fix your package.json version information.

npm install can't find new version


In tableau, how to calculate login hours between two dates date wise?

Question: For example, my login hour is 7am to 11pm. You want to calculate the processing hours between 18/10/2019 5:30:40 and 21/10/2019 14:05:15 date wise. Consider all the holidays and weekends in the final result.
Output we should get for the above example:
18/10/2019 16 hrs
19/10/2019 16 hrs
20/10/2019 16 hrs
21/10/2019 7.0875 hrs

Answer: login hours from 7 AM to 11 PM means 16 hour workday:
IF Datediff('day',[LogInTime],[LogOffTime])=0 Then
(IF Datepart('hour',[LogOffTime])>23 then 23 else Datepart('hour',[LogOffTime]) end)-
(IF Datepart('hour',[LogInTime])<7 then 7 else Datepart('hour',[LogInTime]) end)
Else
Datediff('day',[LogInTime],[LogOffTime])*16 +
(IF Datepart('hour',[LogOffTime])>23 then 23 else Datepart('hour',[LogOffTime]) end)-
(IF Datepart('hour',[LogInTime])<7 then 7 else Datepart('hour',[LogInTime]) end)
End


Creating a force directed graph in Babylon.js

Question: I am attempting to create a force directed graph in my Babylon.js project and was wondering if anyone had suggestions as to how I should go about that. I am looking into the barycentric method and the Barnes-Hut method but am wondering if there are any simpler ways of doing so (such as how it is done in d3.js by typing d3.layout.force) or if I should continue on with one of those methods above. I need to add the nodes on top of a plane within a 3D area but the y values of the nodes will remain constant so it is more of a 2D problem.
I also looked into Springy (http://getspringy.com/) but I am not sure if it would be possible to implement that into Babylon.js due to the 3D nature of Babylon.
If anybody has a suggestion to solve this problem I would greatly appreciate it.
Thank you.
Answer: I would break this problem into multiple pieces.
Wrangle the data using an off-the-shelf algorithm into coordinates, then feed the coordinates into Babylon.
A really cheesy way to do it would be to let d3-force do its magic in a hidden SVG, then feed the graph data into Babylon.
Yes, it's a hack, but it would seem to be fast and easy!


Diff date and time and return as minutes

Question: I have date and time in this format: 2014-07-14 18:19:33. How I can get difference in minutes from today?
Example: 2014-06-14 18:19:33 - 2014-07-01 13:00:22 = xxxx minutes
function subtractDate(datetime)
{
    var diff = new Date(Math.abs(new Date()-new Date(datetime.replace(/-/g,'/'))));
    //return "0000-" + diff.getMonth() + "-" + diff.getDate() + " " + diff.getHours()+":"+diff.getMinutes()+":"+diff.getSeconds();

    var totalMinutes = 0;

    totalMinutes+=diff.getMinutes()
    totalMinutes+=diff.getHours()*60
    totalMinutes+=diff.getDate()*24*60
    totalMinutes+=diff.getMonth() //problem (29 days or 30 or 31 days)
    totalMinutes+=diff.getFullYear()*365 //problem (365 or 366 days)
    return totalMinutes
}

Comment: Parse them as dates, subtract them, convert milliseconds to minutes? Did you at least try something?
Answer: Try this:
var diff = Math.abs(new Date('2014/06/14 18:19:33').getTime() - new Date('2014/07/01 13:00:22').getTime());
var minutes = Math.floor((diff/1000)/60);

Answer: var d1 = new Date('2014-06-14 18:19:33').getTime();
var d2 = new Date('2014-07-01 13:00:22').getTime();
var d = d1 - d2;
var result = d / 1000 / 60;


Purpose of solr boost function

Question: I came across a set of legacy code in which some dynamic variables are set to solr boost function.
String query = "{!boost b=sum(" + searchQuery.getFieldsToBoost() + ")}";

This breaks in case searchQuery.getFieldsToBoost() contains any of these punctuations + - && || ! ( ) { } [ ] ^ " ~ * ? : \
So I tried to escape these special chars in boost sum() function , using the approach given in https://lucene.apache.org/core/2_9_4/queryparsersyntax.html
But the above approach didn't work.
Following is the error:
Caused by: org.apache.lucene.queryParser.ParseException: Expected ',' at position 631 in 'sum(itemAttributes_A3,itemAttributes_ASD,itemAttributes_ASD1,itemAttributes_Bang,itemAttributes_Color,itemAttributes_ES,itemAttributes_El_Segundo_only,itemAttributes_Environment_Friendly,itemAttributes_MossPoint_only,itemAttributes_NAUFIL,itemAttributes_NorthDakota_only,itemAttributes_Off_Contract,itemAttributes_On_Contract,itemAttributes_PBINFO,itemAttributes_PPD,itemAttributes_Palmdale_only,itemAttributes_Preferred,itemAttributes_Punchout,itemAttributes_RanchoBernardo_only,itemAttributes_SEARCHABLE,itemAttributes_Services,itemAttributes_SpacePark_only,itemAttributes_custom_flag12,itemAttributes_FL_01,itemAttributes_hyphen\-field,itemAttributes_icon,itemAttributes_required_PPD,itemAttributes_semicolon;field,itemAttributes_space_field,attributes_Green_certified,attributes_Preferred_contract,attributes_Service_Disabled_Veteran,attributes_Veteran_Owned,attributes_Minority_Owned,attributes_Woman_Owned,attributes_Hubzone,attributes_Tier_II_Contract,attributes_Red_Attribute)'

So I thought of replacing all special chars in searchQuery.getFieldsToBoost() to underscore.
But I don't know how it will effect the search results / boost results.
Basically it would be very nice if someone can help me with escaping the special chars or can give me an overview of repercussions after replacing special characters to underscore.
I am failing to understand what is the purpose of boost in solr.
Comment: could you show what getFieldsToBoost returns?
Comment: it returns comma seperated string in format itemAttributes_{Dynamic_FieldName}
When this {Dynamic_FieldName} contains any above specified special char, then it breaks.
Comment: if you do not get what is boosting, why you are using it?
Comment: Does boost function tends to change the search result also?
Can you please explain why it is basically used?
Answer: The purpose of the boosting function is to boost specific terms or documents or fields, when returning results. It will not add or change result set, e.g. it could only change the order.
So, for example if you decided that field title, is more important than description, you could set it with boosting. Same could be done, if you decided, that term Nike is more important than term Adidas.
Some additional information here

Purpose of solr boost function


Piano both hands, learning curve

Question: I had started learning a piece of music with both hands on piano. I have noticed that at the beginning, playing with both hands seems impossible. That is, one hand stops playing, presses wrong keys, or paces slower or faster. But, after a while, it gets simpler and simpler as if you do not need to pay attention to each hand separately.
I am wondering if this is going to be true for every pieces on piano?
Answer: It's just like riding a bike. At first, it seems very difficult but once you get the hang of it you don't even need to think about it.
It's the same way for learning to play the piano hands together. As pieces get more difficult, it can be tricky to get your hands to work together properly, but you won't ever have to relearn playing hands together again.
Answer: You can also think of it like basketball.  It's comfortable if you only dribble and shoot with one hand, but it's better if you practice both and alternate seamlessly.  You will reach a point where you won't think as much as you are now.
You will notice that there are certain techniques and patterns for each of the hands.  The more you expose your hands to them, the more fluent you will be.
Be patient, because it just takes time.

Piano both hands, learning curve