Jenkins Job DSL: how do you set "Default subview"?

Question: I am trying to create nested tabs with a Jenkins Job DSL Groovy script.  It creates them, but I can find no way to set the "Default subview" in the DSL API.  It does not appear to display the tabs correctly until I do this.  Once I manually, change that default, it displays correctly.  Here is the code:
nestedView(viewName) {
  views {
    listView("Builds (Staging)") {
      jobs {
        name(buildJobName)
      }
      columns {
                status()
                weather()
                name()
                lastSuccess()
                lastFailure()
                lastDuration()
                buildButton()
              }
    }
    listView("Deployments (Staging)") {
      jobs {
        name(deployJobName)
      }
      columns {
                status()
                weather()
                name()
                lastSuccess()
                lastFailure()
                lastDuration()
                buildButton()
              }
    }
  }
}

Original view
Corrected view after manually changing Default subview in Edit View
Answer: You can use a Configure Block to any missing config XML elements.
nestedView('test') {
  views {
    listView("Builds (Staging)") {
      jobs {
        name('foo')
      }
      columns {
        status()
        weather()
        name()
      }
    }
    listView("Deployments (Staging)") {
      jobs {
        name('bar')
      }
      columns {
        status()
        weather()
        name()
      }
    }
  }
  configure { view ->
    view / defaultView('Builds (Staging)')
  }
}

Please file a ticket or open a pull request for any missing DSL methods.
Answer: If you happen to be configuring views under a folder, you can set it there.
folder(abc)
{
    views {
        listView('foo') {
        primaryView('foo')
    }
}

It looks like it's available since version 1.36


Rails 5: attr_accessor throwing NoMethodError (undefined method `keys' for nil:NilClass):

Question: I have 2 non database attributes in my model. If one of them has a value, I need to return the other one in the json response:
class Car < ApplicationRecord

  attr_accessor :max_speed_on_track
  attr_accessor :track

  def attributes
    if !self.track.nil?
      super.merge('max_speed_on_track' => self.max_speed_on_track)
    end
  end
end

The problem is that the line 'if !self.track.nil?' throws an error when the controller tries to return the json
Perhaps there is a better way as I read that using attr_accessor is a code smell.
What I am trying to do is if the user passes me a track value as a query parameter, then I pass that value to the model and it uses it to calculate the max_speed_on_track, and return that value.
Obviously if no track is provided by the user then I don't want to return max_speed_on_track in the json.
The controller method is very basic for now (I still need to add the code that checks for the track param). The code throws the error on the save line.
  def create
    @car = Car.new(car_params)

    if @car.save
      render json: @car, status: :created
    else
      render json: @car.errors, status: :unprocessable_entity
    end
  end

Comment: If this is only for when you call `to_json`, why not override the `as_json` method instead of the `attributes` method? Also, instead of doing `if !self.track.nil?`, you can use `if track.present?`. It reads easier.
Comment: Thanks but if self.track.present? throws the same error
Comment: I read this http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/ about as_json, but I am still stuck. What do I put inside the as_json method to include the field I want when track is not null, but exclude it when track has a value.
Answer: Try this out:
class Car < ApplicationRecord

  attr_accessor :max_speed_on_track
  attr_accessor :track

  def as_json(options = {})
    if track.present?
      options.merge!(include: [:max_speed_on_track])
    end
    super(options)
  end
end

Since Rails uses the attributes method, and you're only needing this for json output, you can override the as_json method just like in this article. This will allow you to include your max_speed_on_track method in your json output when the track is present (not nil).
Comment: Thank you, that works...but now I am starting to see the limitations here and I guess should move to RABL templates or ActiveModelSerialiazers.


What could I use to show that triangular numbers should grow quadratically?

Question: I'm learning to work with polynomials, specifically right now I'm working with progressions like triangular/tetrahedral/pyramid numbers etc.
I know there are different ways to show the nth triangular number ( T(n) ) is
$$
T(n)= \frac{n(n+1)}{2}
$$
Say I wanted to prove this by, first, showing that any formula for the nth triangular must be quadratic. Then I could prove that formula is correct using a Lagrange fit to $(1,1)$, $(2,3)$, $(3,6)$ (which should be unique).
I want to know if there's a way to show that this formula must be a polynomial, and that it must be 2nd degree, before actually finding that formula. Probably overkill for this particular proof, but maybe there's some other problem where that might be useful.
Comment: The difference sequence $\{T(n+1)-T(n)\}$ is linear (by definition really!), and it is known that any sequence whose difference is a degree-$k$ polynomial must be a degree-$(k+1)$ polynomial.
Answer: Welcome to MSE!
First, let me say that your idea to show an identity by showing it's a polynomial and doing some finite check is really clever! There's an entire book dedicated to these kinds of arguments, and I think it's fantastic that you're playing with these ideas. You're right that it's overkill for this problem, and you're also right that there are lots of interesting problems for which it is not overkill! If you want to read more about this and similar techniques, you should definitely check out A=B by Petkovsek, Wilf, and Zeilberger. A pdf is freely available at that link, if you're interested.
Now, to your question.
I'm not sure of a way to see that it must be a polynomial (without using some high powered tools). But here is one way we can modify your approach provided we're willing to guess that it's a polynomial:
First, we know that $\sum \approx \int$ (this is made precise with the euler-maclaurin formula1). So since we're interested in $\sum_{x=0}^n x$, we might expect it to be approximately $\int_{x=0}^n x = \frac{n^2}{2}$. This tells us we should expect $T$ to be a quadratic polynomial.
Now we can follow your suggestion and use lagrange interpolation to compute $p(n) = \frac{n(n+1)}{2}$ is the unique quadratic agreeing with $T$ on $3$ points. Superficially this seems right, as we even get the constant factor of $\frac{1}{2}$ that we would expect from our informal comparison with integration.
But how do we really show that $T(n) = p(n)$?
The quickest way that I can see is via recurrences. Notice

$T(0) = 0$
$T(n+1) = (n+1) + T(n)$

uniquely defines $T(n)$2.
So if we can show your polynomial satisfies these equations, then it must agree with $T$ everywhere (do you see why?).
Now we're basically done! There's one more finite check to do:

$p(0) = \frac{0(0+1)}{2} = 0$
$p(n+1) = n+1 + p(n)$

This particular finite check is basically the inductive proof that $p(n)$ is the right formula. But that makes sense -- in a simple problem like this, there's only so many genuinely unique ways to prove that the formula is right. If you wanted to, we could also check the inductive case by showing $p(n+1) - (n+1+p(n))$ is $0$ on three different inputs. Since it's a polynomial of degree $\leq 2$, that means it must be $0$ everywhere. That's perhaps more in the spirit of your idea (and it's what is done in A=B).

1: In fact, the euler-maclaurin formula guarantees that $T(n)$ must be a polynomial (see here, for instance) but that felt too high powered to use. As is mentioned in the comments, we could also quote a result about linear recurrences, but that felt too high powered as well (though substantially less high powered than euler-maclaurin).
2: Moreover, when you have a sum, it can often be a good idea to turn it into a recurrence relation in this way! This is a nice trick to have in your back pocket, as often we have extra tools (generating functions, etc.) for handling recurrence relations.

I hope this helps ^_^
Comment: Wow, thanks much! Also thanks for the reading suggestion, I'll be sure to check that stuff out.

I hadn't seen the euler-maclaurin formula before; that's super cool. I hadn't thought about the ∫ ≈ Σ thing before, looks kinda funny written out like that but it makes sense, haha
Comment: Happy to help! If this (or the other excellent answer) answered your question, you should mark it as such so that other users on the site know how to spend their time ^_^. It's also fine to wait a few days and see if anyone else adds an answer that gives some more insight into the problem
Answer: From their definition, the triangular numbers follow the recurrence
$$T(n)-T(n-1)=n$$
such that the RHS is a linear polynomial.
Now for any polynomial $T$, $T(x)-T(x-1)$ is a polynomial one degree lower (when expanding the powers of $x-1$, the leading terms $t_dx^d$ cancel out, and the term $dt_dx^{d-1}$ appears). Hence if $T$ is a polynomial, it must be quadratic.
Next, as $T$ coincides with the summation for infinitely many values of $n$, it is the unique polynomial that fits.

Note that $f(x)=\dfrac{x(x+1)}2$ is not the only function that coincides with $T(n)$ for every $x=n$. But for every function $g(x)$ that does so, the difference
$$h(n)=g(n)-f(n)=0$$ and this "perturbation term" is unimportant.
Example of a non-polynomial function (in blue):
Comment: (+1) Nice example of a perturbed solution! It's a good idea to point out that these exist.


woocommerce edit-account shortcode

Question: I saw in this question that is possible create a shortcode from my-orders page, I am trying create something similar to display the edit account page via shortcodes.
Reference: in woocommerce, is there a shortcode/page to view all orders?
function shortcode_my_orders( $atts ) {
    extract( shortcode_atts( array(
        'order_count' => -1
    ), $atts ) );

    ob_start();
    wc_get_template( 'myaccount/my-orders.php', array(
        'current_user'  => get_user_by( 'id', get_current_user_id() ),
        'order_count'   => $order_count
    ) );
    return ob_get_clean();
}
add_shortcode('my_orders', 'shortcode_my_orders');

Answer: I created this shortcode to add the HTML contents of the Edit Account page in another page. I believe that's what you are asking for.
// Paste this in the function.php file of your active child theme or theme.
function wc_customer_edit_account_html_shortcode( $atts ) {

    // Attributes
    extract( shortcode_atts( array(
                'text' => 'Edit Account' ), $atts ) );

    return wc_get_template_html( 'myaccount/form-edit-account.php', array( 'user' => get_user_by( 'id', get_current_user_id() ) ) );;

}
add_shortcode( 'wc_customer_edit_account_html', 'wc_customer_edit_account_html_shortcode' );

You can also put this in a New Snippet in the Snippets plugin instead of editing the functions.php page.
Answer: You can display the edit account form, wherever you want, with this code:
function clket_edit_account_form(){
    ob_start();
    wc_get_template( 'myaccount/form-edit-account.php', array( 'user' => get_user_by( 'id', get_current_user_id() ) ) );
    return ob_get_clean();
}
add_shortcode('clket_edit_account', 'clket_edit_account_form');

Shortcode: [clket_edit_account]

Ref: https://woocommerce.wp-a2z.org/oik_api/wc_shortcode_my_accountedit_account/

woocommerce edit-account shortcode


Does C++11 allow the following nested variadic expansion within and of a lambda?

Question: Can anyone confirm for me that the following code (which includes nested expansions of a function parameter pack) is allowed in C++11 (I would certainly appreciate any references to the standard):
<code>template<class ... VFTs> int variadic_fun(VFTs ... vfts) {
  return sizeof ...(vfts);
}

template<int ... Ns> struct IntPack {
  template<class ... MemTs> static int variadic_memfun(MemTs ... MemArgs) {
    return variadic_fun(([=]() {
      cout << "MemArgs = " <<  MemArgs << "\n";
      cout << "Ns = " << Ns;
      // Note the nested expansion of MemArgs here:
      cout << "variadic_fun(MemArgs...) = " << variadic_fun(MemArgs ...) << "\n";
      cout << "MemArgs[Ns] = " <<  MemArgs[Ns] << "\n";
      return 0;
    })()...);
  }
};

int main() {
  IntPack<0, 1, 2>::variadic_memfun("123", "ABC", "XYZ");
}
</code>
Thanks!
P.S. Since someone asked below, this code works with my patch of clang that implements generic lambdas (Not yet standard C++, still just a proposal) - I have not tried it with any other compilers - and am not sure if it works with the latest clang trunk currently (it probably does) - I would certainly welcome any information on whether it compiles with any of the mainstream compilers that implement variadics and lambdas.
Comment: You may want to add the information about what compiler have you tried. At least it doesn't go well with current version of [ideoone](http://ideone.com/xSkGrg).
Comment: the most complex expansion pattern I've seen till now =D
Answer: Yes, this is valid, and Clang supports it.
<code>$ clang++ your-example.cpp -std=c++11
$ ./a.out
MemArgs = 123
Ns = 0variadic_fun(MemArgs...) = 3
MemArgs[Ns] = 1
MemArgs = ABC
Ns = 1variadic_fun(MemArgs...) = 3
MemArgs[Ns] = B
MemArgs = XYZ
Ns = 2variadic_fun(MemArgs...) = 3
MemArgs[Ns] = Z
</code>
The relevant rule is [temp.variadic]p5:

An appearance of a name of a parameter pack that is not expanded is ill-formed.

That does not apply in this case, since

A parameter pack whose name appears within the pattern of a pack expansion is expanded by that pack expansion.

... and the uses of the pack within the lambda are within the pattern of the function argument pack expansion.


Server 2016 Updates failing to install

Question: 2019-04 Cumulative Update for Windows Server 2016 for x64-based Systems (KB4493473)
2018-09 Update for Windows Server 2016 for x64-based Systems (KB4091664)
Four failures to install on one particular server but have installed all of them on another 2016 box.
ESET File Security installed.
Server has been rebooted multiple times.
I've also tried purging the %windir%\SoftwareDistribution\DataStore folder to no avail.

Is anyone else having these problems? I can't seem to find much info online.
Comment: Looking in the ReportingEvents.log file I keep seeing error 0x800F0922. Googling this gives me the following https://answers.microsoft.com/en-us/windows/forum/windows_10-update/install-update-error-0x800f0922/87a78355-1a84-4e0f-a0be-28f99a075e50
Comment: I've sorted the systemprofile problem. Sill KB4493473 refuses to install...
Answer: I would also suggest purging the %windir%\SoftwareDistribution\Download\ folder as well. Sometimes there can be a bad or partial download in there that the update is trying to use.
Comment: Thanks for your suggestion, I'll give this a go.
Comment: @RichM I don't have enough rep, otherwise I would respond up there... Anyways, looks like a lot of people did not have enough System Partition reserved space. Maybe that is your issue as well? Can you tell how much space yours has?
Comment: I have a single logical drive with 500MB System Reserved and the rest (278.87GB) as C:\ which has 202GB free space.
Comment: I see. As for the new problem, you should be able to go to ```C:\Windows\System32\config\systemprofile\``` and create a file named 'Desktop'. You can also copy it from ```C:\users\default\desktop```. Link to this solution found [here](https://answers.microsoft.com/en-us/windows/forum/windows_10-performance-winpc/cwindowssystem32configsystemprofiledesktop-is/4faa2c49-c964-44c8-b38f-02432af8ee0e)
Comment: I've now run the Windows Update troubleshooter which has found "possible WU database errors" but has offered no way to fix. I've also run the `DISM.exe /Online /Cleanup-image /RestoreHealth` command which has completed successfully but KB4493473 is still not downloading...
Comment: Have you tried uninstalling and reinstalling older updates?
Comment: No I haven't tried this, I'm a little wary of things screwing up completely if I do this.
Comment: Uninstalled ONE update: BSOD
Answer: Following the disastrous removal of a single Windows Update, and the following disastrous attempt to recover, I've had to rebuild the server from scratch.
Luckily the rebuild has resulted in the Windows.old folder so I can recover information from there.

Server 2016 Updates failing to install


what should I use as placeholder for a html img element?

Question: To keep it simple I've left some out of my img field.
here's my code:
$markup = t("", $img_src);

I've tried format_string() but that also retuns:
<img src="path/to/image">

Answer: It would probably be better to use the theme_image() function for that:
$image_html = theme('image', array(
  'path' => $img_src,
  'alt' => 'Some alt',
  // etc
));

If you're hell bent on using t() then you need to use it with the ! prefix, so the value is passed through without any checks/sanitisation:
$markup = t("", array('!src' => $img_src));

The docs for format_string() explains the different kinds of placeholders you can use, and which prefix you should use for each.
Comment: hmm seams I was a bit blind at the moment thanks for pointing out about the format string docs! But theme_image is a even better solution!


Selecionando classe com jquery

Question: Qual a diferença em selecionar a classe dessas duas maneiras em JQUERY?
Uma tem acesso a parâmetros, outra não, como funciona ?
var valor = $(".classe");
var valorAnime = 'classe';

Da uma olhada nesse código :
 (function(){
 let $target =$(".projeto"),
    animeStart = 'projeto-anime',
    offset = $(window).height() * 3/4;

    function animeScroll (){
        let documentTop = $(document).scrollTop();

        $target.each(function(){
            let itemTop = $(this).offset().top;

            if( documentTop > itemTop - offset) {
                $(this).addClass(animeStart);
            } else {
                $(this).removeClass(animeStart);
            }
        })
    }

 animeScroll();

 $(document).scroll(function(){
     animeScroll();

 });
 }());

Answer: Ao meu ponto de vista, quando você faz
var valor = $(".classe");

você está buscando na página o objeto cuja classe corresponde a classe, já quando voce utiliza esse código.
var valorAnime = 'classe';

você está atribuindo à variável valorAnime uma string cujo o conteúdo é classe
EDITADO:
bom esse segundo código seu faz a seguinte coisa;
let $target =$(".projeto"),

prende o que tem classe projeto
dentro do loop que ele tá fazendo sobre os objetos de $target, depois de verificar na condicional do if ele utiliza o $(this) que nada mais é o objeto que está sendo iterado, e adiciona a ele uma classe com o comando addClass onde o nome da classe é projeto-anime
Se não me engano funcionaria da mesma forma se voce fizesse:
            if( documentTop > itemTop - offset) {
                $(this).addClass('projeto-anime');
            } else {
                $(this).removeClass('projeto-anime');
            }

Mas por questões de modularização, é melhor utilizar da forma como você apresentou primeiro. Espero que tenha sido claro
Comment: Da uma olhada no código que adicionei. Compreendi sua explicação, mas da forma que esse código está ele tem acesso a classe projeto-anime que tá no css e a função é executada sem erros, caso eu selecione a classe da mesma forma que selecionei a primeira, da erro. Não to conseguindo entender justamente essa segunda forma que foi utilizada para selecionar a classe.
Comment: Dei uma editada na minha resposta para adequar a pergunta, espero que tenha sido claro e que você tenha compreendido o que está acontecendo
Comment: sim, sim. obrigado!

Selecionando classe com jquery


Space out various service checks for a host with Nagios

Question: Anyone know if there is way to time various service checks per host?
So for example, if I have hostA and 5 different services checks for that host.  Each of those checks happens every 5 minutes.  Can I make so I have a check every minute or so, instead of 5 checks pretty much at once?
Comment: Sadly nagios's scheduler really isn't that clever. :(
Answer: Update: On further reading it seems like you may have been looking for a per host option. If this is the case than, unfortunately, the service_inter_check_delay_method is more of a global setting and doesnt have the host level granularity that you may be looking for, I'll keep this post around in case others find it useful for their installs.
Sadly the official documentation hasnt been ported over from Nagios 2, but you may try playing with the service_inter_check_delay_method option in your Nagios config.
Old Docs: http://nagios.sourceforge.net/docs/2_0/checkscheduling.html
# SERVICE INTER-CHECK DELAY METHOD
# This is the method that Nagios should use when initially
# "spreading out" service checks when it starts monitoring.  The
# default is to use smart delay calculation, which will try to
# space all service checks out evenly to minimize CPU load.
# Using the dumb setting will cause all checks to be scheduled
# at the same time (with no delay between them)!  This is not a
# good thing for production, but is useful when testing the
# parallelization functionality.
#       n       = None - don't use any delay between checks
#       d       = Use a "dumb" delay of 1 second between checks
#       s       = Use "smart" inter-check delay calculation
#       x.xx    = Use an inter-check delay of x.xx seconds

service_inter_check_delay_method=s

So instead of the default 'smart' method try something like service_inter_check_delay_method=60
Note: the default smart check method works very well, if you choose to use a static x delay check, be sure to do a LOT of testing to make sure this doesnt flood your network in unusual and interesting ways... ;-)
Comment: Another thing you might want to check into is modifying check_multi to sleep 60 in between its checks. This _would_ scale at the host level, but you will need to dive into the check_multi code a little. http://exchange.nagios.org/directory/Plugins/Others/check_multi/details


Deliver ajax commands on successful form submit

Question: First of I apologize if this has been asked before, but I haven't found anything that actually does what I want to do.
Question: I'm trying to deliver some ajax commands on after a successful ajax submission of a form.
The Code
function my_module_form_form($form, &$form_state){
    $node = $form_state['build_info']['args'][0];
    $form = array(
        'track_id' => array(
            '#type' => 'textfield',
            '#title' => t('Track ID'),
            '#required' => true,
            '#prefix' => '
nid.'">',
        ),
        'courier' =>array(
            '#type' => 'textfield',
            '#title' => t('Courier Name'),
            '#required' => true,
        ),
        'actions' => array(
            '#type' => 'actions',
             'submit' => array(
                '#type' => 'submit',
                '#ajax' => array(
                    'callback' => 'my_module_form_ajax_submit',
                    'wrapper' => 'form-finished-wrapper-'.$node->nid,
                ),
                '#prefix' => '
',
                '#suffix' => '
',
                '#value' => t('OK'),
            ),
        ),
    );

    return $form;
}
function my_module_form_validate($form, &$form_state){
    // form_set_error('courier', 'catch all');
}

function my_module_form_ajax_submit($form, &$form_state){
    $return_form = array(
        'track_id' => $form['track_id'],
        'courier' => $form['courier'],
    );
    return $return_form;
}
function my_module_form_submit($form, &$form_state){

    $node = $form_state['build_info']['args'][0];
    $track_id = $form_state['values']['track_id'];

    $node->field_track_id[LANGUAGE_NONE][0]['value'] = $track_id;
    $node->field_courier_name[LANGUAGE_NONE][0]['value'] = $courier;
    node_save($node);

/* How can I deliver the below commands?

    $ajax_commands = array();
    $ajax_commands[] = ajax_command_invoke('myModal, 'modal', array('hide'));
    $ajax_commands[] = ajax_command_replace('form-finished-wrapper-'.$node->nid, t('Submited Successfuly'));
    ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));

*/

}

Context
The form appears in a modal my_module_form_ajax_submit is responsible to display validation errors along with messages. I have tried ajax_delivery and ajax_render to return the commands. With ajax_render nothing happens, but with ajax_deliver I get an ajax popup with the commands in JSON. I think I'm close but surely I'm missing something.
Any help appreciated!
Comment: I have found this question https://drupal.stackexchange.com/questions/38190/cant-get-ajax-callback-and-submit-from-the-same-form-to-work?rq=1
which is trying to do something close to what I'm trying to do. I get the ~same error. I'm look for an answer that can be done from the form API though, as the answer suggested there won't work in my case
Answer: You return the ajax commands in your ajax callback function.
function my_module_form_ajax_submit(array $form, array &$form_state){
  if (count(form_get_errors())) {
    return array(
      'track_id' => $form['track_id'],
      'courier' => $form['courier'],
    );
  }
  else {
    $ajax_commands = array();
    $ajax_commands[] = ajax_command_invoke('myModal', 'modal', array('hide'));
    $ajax_commands[] = ajax_command_replace('form-finished-wrapper-'.$node->nid, t('Submited Successfuly'));
    return array('#type' => 'ajax', '#commands' => $ajax_commands);
  }
}

I'm not sure what you were trying to do with your original callback, so I couldn't incorporate it.
Comment: the ajax_submit runs every time the button is clicked.
I only want to return ajax_commands when the form is successfully submitted.

Also the ajax_submit is responsible to show the errors of the form without a page reload ex if you submit without filling in the form it will display that the fields are required.
without the original callback these messages would appear on a page refresh.
Comment: I see. I've altered the code accordingly.
Comment: I've tried something similar, I'll have a go with this and update accordingly, thanks
Comment: This works perfectly, unfortunately it's my commands that don't work (trying to close the modal and replace the form with text) but any other commands work. As you have answered the context of the question I'm marking this as the right answer. thanks


Positive linear regression coefficient

Question: I am trying to use R to find the optimal solution for my problem with positive coefficients. Here are my data:
      th inp      tcyc        tinst     tmem      tcom
  1   2   2  26219765385  1975872868  52449810   782964
  2   2   4  38080459431  3155342008  76744867  1878903
  3   2   8  64572439641  6230494010 137754355  4351706
  4   2  16 140168021516 13757989992 285524252 10605705
  5   2  32 308925389816 31497131498 628391048 26040711
  6   4   2  13206650786   988226883  25631315   844126
  7   4   4  19078145632  1577873809  37085281  2125333
  8   4   8  33742095874  3114415906  65962626  5222236
  9   4  16  70956149286  6881357755 134957687 12180392
  10  4  32 153411672670 15754506070 296548768 31057252
  11  8   2   6572843040   494094967  12380740   808816
  12  8   4   9452222628   788984621  17538152  2034061
  13  8   8  16765943294  1557329849  30549900  5016827
  14  8  16  34677550217  3440679505  61614420 12493699
  15  8  32  74852648112  7876116794 133525620 29824686
  16 16   2   3252373719   247026385   5958559   672396
  17 16   4   4669800482   394452497   8097991  1676579
  18 16   8   8269859136   778889584  13651458  4196829
  19 16  16  16353025378  1720301596  26775255 10393194
  20 16  32  37113657641  3938965759  55505822 25011009
  21 32   2   1630888153   123512114   2683400   461526
  22 32   4   2293598746   197173135   3682504  1213596
  23 32   8   4045995970   389408822   5858031  3055324
  24 32  16   8217603991   860041282  10973460  7502244
  25 32  32  17978101850  1969647650  22909347 17953100
  26 48   2   1064344042    82295143   1822133   381178
  27 48   4   1523091067   131488491   2331228   949354
  28 48   8   2677097592   259536252   3552229  2381626
  29 48  16   5400541381   573140686   6489032  5875310
  30 48  32  11837404077  1313066425  13318331 13968230

I use linear regression in R, s <- lm(tcyc ~ 0+tinst+tmem+tcom, data=fit), to get the optimal value with intercept 0. But I get negative coefficients which does not make any sense.
coef(s)

 tinst      tmem      tcom
20.8745 -281.2288 -320.7204

I am not sure whether is it the best way to model and find the optimal parameter for tinst, tmem and tcom. How do you find positive coefficients for the model?
Further explaining this problem in Detail:::
Background:
Trying to predict the execution time of an application in the future many-core systems empirically by learning the application behavior. As it is a multithreaded program, it will have communication contnention bottleneck if the application demands high inter-core communication. The general system equation looks like
Total executiong time cycles (T_cyc) = Total cycles spent in Instruction (T_inst) + Total cycle spent in Memory instructions (T_mem) + Total cycle spent in Communication (T_com)
i,e T_cyc=T_inst+T_mem+T_com.
If I use a simulator I can get the T_inst,T_mem and T_com directly and find out the independent contribution of each component to the T_cyc. But using a hardware, I can only get the counts or number of events. Ie, N_inst, N_mem and N_com.
So what I have is
T_cyc= a* N_inst + b* N_mem + c* N_com
Where a,b,c has to be determined.
I tried solving the problem using lsqnonneg (non-negative least square method)  in MATLAB to find the a,b,c. At times from the data I get b and c value ZERO which is totally meaningless.
Things to notice:
N_inst is a very high value. N_mem and N_com are bit lower in magnitude and hence I face this problem of b and c results as ZERO.
Questions:
1.  Is this a proper tool to solve such a linear equation system? If not, what else should I try?
2.  Is it a problem due to the sample size fed to the solver?
3.  I see that for most applications trend of N_cyc, N_inst,N_mem are monotonic but N_com is non-monotonic and can it affect the solved values? If so, how to isolate this component and find its contribution individually?
Comment: @Georg, as far as I know, `+0` and `-1` are fully equivalent in R. They both suppress they intercept.
Comment: Try `s<-lm(tcyc ~ tinst+tmem+tcom-1, data=fit)`
Comment: yes, patrick is right. I tried using nnls package but still it was giving some coefficient as 0, again it doesn't hold good.
Answer: It is often the case that suppressing the intercept leads to regression coefficients that don't make sense. In my experience, there are rarely cases where suppressing the intercept makes sense, even if the scientific plausibility suggests that it might be justifiable (such as stopping distance versus cruising speed or creatinine clearance versus kidney mass in grams: you LEAVE the intercept IN with such analyses!). This is a problem of extrapolation.
Just eyeballing these data, I imagine that the estimated intercept would be a largely non-zero value. Since these data appear to come from some sort of computing time, comparing flops versus elapsed time, etc. the non-zero intercept could have a host of interpretations such as a boot time for running a process, a system lag as memory is allocated for an operation, or any other non-neglible system processes that aren't measured as part of an experimental run. Furthermore, and more subtle, there may be non-linear effects which are influencing your results. The regression coefficient from intercept-in OLS still provides a great way of estimating the first order linear trend through those data, even if the trend is curvilinear... only when you leave the intercept IN.
My first recommendation is to look at the output from running pairs(fit). And just look at the trend.
Nonetheless, if your goal is to simply find optimal positive coefficients in the model, you can do so with using by-hand optimization, either ML or Gibb's sampling, though don't be surprised if those results make no sense. Example of by-hand optimization:
X <- model.matrix(~ tinst+tmem+tcom-1, data=fit)
y <- fit$tcyc
negLogLik <- function(b) {
  b <- exp(b)     ## restrict to positive only values
  yhat <- b %*% X ## calculate fitted
  -var(y-yhat)    ## objective foo
}

nlm(negLogLik, c(1,1,1)) ## minimize objective foo

Comment: +1, excellent discussion of the issues surrounding suppression of the intercept. I once made a similar point ([when is it OK to remove the intercept](http://stats.stackexchange.com/a/32509/7290)), but not nearly as well as this.
Comment: can this problem be solved by increasing the number of samples? or running more experiments with various thread size?
Comment: @user41797 nope. An analysis is like an engine, sample size is just the throttle, a bad probability model is like bad gas. Feed crap into the carbs, get crap for acceleration.
Comment: Why stopping distance vs. cruising speed would require the intercept, if the relationship is linear?
Comment: @RobertKubrick it will artificially increase the uncertainty in the slope estimates since all measures are extrapolated away from 0.
Comment: ok, but we still have standard errors to understand whether the coefficients are sound or not. If we know the stopping distance is 0 at cruising speed 0, wouldn't you rather use that knowledge to "weaken" your other coefficients and try to identify new terms, or transforming the existing ones?
Comment: @RobertKubrick No. You are creating false uncertainty due to calibration issues that would have been resolved by using the correct regression model. Any interpretation of the least squares coefficient is NOT preserved if you suppress the intercept. I do not know whether there is a sound interpretation of that value. An intercept-less model when theoretically appropriate does NOT approximate the correct model. The intercept has a value and you MUST estimate it to account for the errors in measurement: that is the whole point of statistics.
Comment: mhm... then you are assuming that there are calibration issues, always. And you are implying that all regression models should have an intercept. So, when would you remove the intercept?
Comment: @RobertKubrick Only use a intercept-less model for calculating a within-pair differences analysis. [Carlin's paper is a good review](http://ije.oxfordjournals.org/content/34/5/1089.full).

Positive linear regression coefficient


How to make "plastic" sounding distorted guitar sound

Question: I usually don't go for that kind of sound because I usually want my distortion to sound balanced and even (like cutting highs a lot and cutting boxy low end) but I'm interested in how can you achieve this kind of sound using a virtual amplifier (however if you can tell how to make it on real amp stack it would be appreciated as well). It sounds pretty cringey as well so it can be used as an effect in some lo-fi sounding song part.
It's from the first album by Bloodbath: Resurrection Through Carnage. If you listen to any track (Ways To The Grave, etc.) you can hear it. Timecode is 0:45 (included in link).
Comment: Please at least provide a timestamp to a clear example. Few people are going to want to listen to 40 minutes of that racket... ermm... performance to try figure out which bit you mean ;) From the [very] quick scan of a couple of segments, including completely by accident, one bit with just a single guitar alone, if I was doing it in software, I'd be looking for the amp's **sag** control & also 'speaker age'.
Comment: Completely different vibe, but does this feel anything like what you mean? https://soundcloud.com/graham-lee-15/norton-disney-weightless-excerpt This is *one* guitar & *one* bass & a totally different drum treatment [with a shed-load of vocals over them] whereas your example sounds as though they usually use 2 guitars often playing the same thing, hard left & right.
Comment: With the timestamp [thank you] I'd say, yup, lots of sag & raging speakers. Also a lot of hard multi band compression. I'd say other than the musical style, very similar to the example I posted.
Comment: @Tetsujin Yeah sounds not too close but kinda similar. I don't know how to describe it but sounds "electric" (like when you play though a hi-gain with high volume but the intentionally lowering it with a boost/cut or buffer pedal and add no reverb afterwards).
Comment: You're perceiving the difference in playing style, mine is slow 8's, no ultra-fast picking, so the attacker are much closer on your example & rely even more heavily on the compressor... Let me drop in an answer you could then try copying & see if it works.
Comment: sorry, typo, too late to correct... *attacks are much close...
Comment: Not my day for typos... that's 'much closer' & also 'ageing speakers'.
Answer: I'm dropping this answer in early, assuming I might be right rather than being certain at this point.
I posted an example of a totally different style track, but I think using similar techniques - so I can easily describe how I did that. I don't have the file to hand to be able to directly copy/paste or screenshot the settings, but I used this setup a fair bit on that album so I kind of know how the setup went.
The track I'm basing my comparison on is -

This was a Firebird through a Marshall - well, it wasn't, it was a Line6 Variax through Guitar Rig... but just imagine ;)
Gibson Firebird - like a Les Paul but thinner & harder, for starters.
Marshall 'early', Jimi Hendrix age, not a hi-gain [I used to actually own one, a 1967 Lead 50, I'm still kicking myself for selling it in the early 80s]
So, Marshall - everything on 7 - no, not 11, 7!
Guitar wide open, all volume, all tone. No pedals in front.
If your open guitar can't push that into good dirty distortion, put a gain pedal in front [or as you're doing this entirely in software, just up the input gain], don't turn the amp up.
In Guitar Rig you can turn the 'amp' around & dial in some finer parameters. Here sag is your friend. The more the amp sags, the dirtier it sounds.
You then route that to anything of appropriate age, basically something with 60's Celestions in it, a Marshall 4x12, or even a cheap Carlsboro, depending on what cabs your model has.
Again, if you can turn the cab round, dial in a lot of 'age', so the cones get 'fluffier'
You then mic that close & at 45° with a large diaphragm condenser - Neumann U87 ideally. This, btw, is to capture more high end than an SM57/58 would - essential to getting that attack later on.
On the board, you drop in a good multi band comp - my weapon of choice here is Waves LinMB. just pull in the threshold until it emphasises the attacks & holds the body of the sound stable. You have to experiment with this, because it is also your EQ. You do not need to EQ this setup at all, other than getting the multi band right.
Done.
[If you're wise, you'll record the guitar over 2 channels, one wet for the mix, one totally dry in case you change your mind; then you can just re-amp the existing performance.]
Now... I know this is going to feel like an odd connection, but listen to the intro to Spirit in the Sky, Norman Greenbaum..
That's what you need before you hit it hard. The guitarist is being very gentle with the top end, yet the bottom strings are pushing the amp so it's sagging like over-cooked spaghetti.
That is exactly what you need the amp/speaker combo to be generating before you turn up the player, guitar & add the hard multi band.

Just another example to show this is by no means a 'new sound', it's an 'old sound' but using modern compression & mixing techniques.
This from Mountain - Live [c.1970] All they're really missing is the comp & the double speed playing. The rest was already there, 50 years ago.
Comment: Going deep into the archives for Norman Greenbaum... good suggestion ;)
Comment: @DavidBowling - LOL, thank you - there's an early Yamaha modelling amp with exactly that sound... I know, I programmed it for the internal presets way back in the early 90s ;) I've always considered it a very influential sound.
Comment: Cool! It really works thanks! However i used dynamic EQ instead of multi-band comp. It works fine as well.
Comment: I dropped another example into the answer - all you have to bear in mind is that this is not actually a 'new sound'. What it really is, is an 'old sound' with modern compression & mixing techniques.
Comment: I think a big muff pi fuzz pedal is often used for this kind of sound. The Zvex Woolly Mammoth is a modern boutique version and there are many fuzzes that can help get this sound.
Comment: @ToddWilcox - I'm always worried about making the inputs too high-gain & therefore smoothing out with a pedal in front. I do get what you mean & it's something i would definitely try, especially if it was live & for real,, but it's amazing what you can get from a fairly basic old-style amp/speaker setup once you crank in the LinMB on the board.


Creating a one-time password, and send the email

Question: We need to create a system where the user enters only an email address. For a specific domain user receives an email with a generated password, and for all other domain receives a notification email to contact support. Password used to access a protected area of the site that is not available to the public. Also, the password can be used only once, ie. each time a user enters an email address, get a new password.
Any ideas how to make this system to Drupal 7?
Answer: Login One Time comes closest to your requirements. From its project page:

Login one time provides the ability to email one-time login links to users.
Features
Rules:

[user:login-one-time] token on user events.

[comment:login-one-time] token for node author on comment event.

User profile - "Send login one time link" button.

VBO - Create a view and send login links to the view. Checkout View
Reference for ideas on how to embed views.

Block - Select a user and send the link. You can use this block in
nodes as a CCK field using Block Reference.

PHP - Print a button in a template or directly send the emails using
the functions described in the README.


Probability Density Function

Question: x = 2, μ (mu) = 5 and σ (sigma) = 3
I am just wanting to confirm may workings for the second part of the probability distribution function as underlined red in the picture below (see Image_1.).
$$e = (2.71828)$$
$$part.two = -\frac{(x - \mu)^2}{2\sigma^2}$$
$$=-\frac{(2 - 5)^2}{2*3^2}$$
$$=-\frac{3^2}{18}$$
$$=e^{-0.5}$$
$$part.two = 0.60653$$
Are my figures correct and have I got the correct answer, otherwise, what have I done wrong?
I do not understand if the fraction $\frac{(x - \mu)^2}{2\sigma^2}$ is meant to be $e^\frac{-(x - \mu)^2}{2\sigma^2}$ or if it is to be the difference of the constant $e - \frac{-(x - \mu)^2}{2\sigma^2}$  Hopefully, I have explained it better and is there anywhere I can test my result next time to ensure I have calculated it right?
 Image 1.
Comment: Please use math typesetting. It's hard to understand what you're asking. More information: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Probability density function. Title is correct, that in contents is wrong. should be /(2*sigma^2) or /2/sigma^2. $e^{-0.5}$ , not $e-0.5$.
Comment: Ok, I have updated my question and tried the best to format it correctly.  Thanks for having a look.
Answer: The formula means $$\frac{1}{\sqrt{2\pi}\sigma}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2} \right)$$
After you computed $-\frac{(x-\mu)^2}{2\sigma^2}$, call it $w$, we then compute $e^w$ and then divide by $\sqrt{2\pi}\sigma$.
You have yet to finish your computation, you still have to multiply $e^{-0.5}$ with $\frac{1}{\sqrt{2\pi}\sigma}$.
Comment about your writing:
when we write equality, it means the object on the left and on the right are equal. Avoid stuff like $-\frac{3^2}{18}=e^{-0.5}$.
As for how to check your working, one way is open the $R$ program, type dnorm(2,5,3). You can do it online as well.

Probability Density Function


Como procurar elemento em ListBox?

Question: Preciso procurar palavras parcialmente dentro de um Listbox, exemplo: um dos elementos do Listbox tem a palavra Cachorro, se eu digitar cach (em um edit por exemplo) ele procura e seleciona todas as palavras que iniciar com essas letras.
Answer: Já resolvi pessoal pra quem precisar, segue o código completo:
var
S : Array[0..255] of Char;
begin
StrPCopy(S, Edit2.Text);
with ListBox1 do
ItemIndex := Perform(LB_SELECTSTRING, 0, LongInt(@S));
end;

Como procurar elemento em ListBox?


Cross-table multiplication

Question: Here I have 3 tables:
    Book [Id] [UnitPrice]
    BookOrder [Id] [BookId] [Quantity]
    BookInvoice [Id] [OrderId] [TotalPrice]

The requirement is to get the UnitPrice from Book table, then.
    UnitPrice * Quantity = TotalPrice

I am newbie to SQL and this is my code:
    CREATE TRIGGER TR_TotalPrice
    ON BookInvoice *--Is that correct?*
    FOR UPDATE, INSERT
    AS
    UPDATE BookInvoice SET TotalPrice = Book.Price * BookOrder.Number
    FROM Book, BookOrder

....
And I have no idea how to complete these code, hope guys will help me, thanks.
Answer: you dont have to store TotalPrice in the BookInvoice  table as you can derive the value using the values from other tables..
select Book.Price * BookOrder.Quantity as TotalPrice
from Book
join BookOrder
on BookOrder.BookId=Book.id

Answer: you can use trigger
CREATE TRIGGER TR_TotalPrice ON BookInvoice
FOR UPDATE, INSERT
AS
begin
    update BookInvoice set
        TotalPrice = B.Price * BO.Number
    from inserted as i
        inner join BookInvoice as BI on BI.Id = i.Id
        inner join BookOrder as BO on BO.Id = i.OrderId
        inner join Book as B on B.Id = BO.BookId
end

or you can just use view, it's more normalized, but if book Price will change, TotalPrice of all invoices with that book will change too
create view vw_BookInvoice
as
   select
        BI.Id,
        BI.OrderId,
        B.Price * BO.Number as TotalPrice
   from BookInvoice as BI
        inner join BookOrder as BO on BO.Id = i.OrderId
        inner join Book as B on B.Id = BO.BookId

Comment: Thanks for your answer. However, when I after I tried the code into my project, I got several error messages prompted: The multi-part identifier "..." could not be bound. I think I have made all the table name and column name to match my database table and column. Any idea?
Comment: Msg 4104, Level 16, State 1, Procedure vw_BookInvoice, Line 8
The multi-part identifier "OrderTable.ord_Id" could not be bound.
Msg 4104, Level 16, State 1, Procedure vw_BookInvoice, Line 8
The multi-part identifier "invo.OrderId" could not be bound.
Msg 4104, Level 16, State 1, Procedure vw_BookInvoice, Line 9
The multi-part identifier "Product.pdt_Id" could not be bound.
Msg 4104, Level 16, State 1, Procedure vw_BookInvoice, Line 9
Comment: My scenario is a little bit from the question I just put. I named the Book table as "Product" table in my database. Thanks
Comment: well if you are using `OrderTable.ord_Id` then you have to have `OrderTable` table in you query or ` as OrderTable`. Take a look http://msdn.microsoft.com/en-us/library/aa196308(v=SQL.80).aspx
Comment: Sorry but I still got one error, I tried to declare the alias "FROM my_db.dbo.Invoice AS I, my_db.dbo.Product AS P, my_db.dbo.OrderTable AS O". But I still got an bound error on the "multi-part identifier "p.pdt_Id""
Comment: Here is my code in the query: inner join Product AS Item ON p.pdt_Id = O.ord_ProductId
Comment: try `inner join Product AS p ON p.pdt_Id = O.ord_ProductId`
Comment: Since your trigger updates the same table on which it's been defined, it might be safer to add a condition checking which column is being updated, to prevent recursive trigger calls: `IF UPDATE(Price) OR UPDATE(Number) UPDATE BookInvoice ...`.
Answer: If you have to use triggers you will need to create triggers to cover all cases. For example to update the table BookInvoice in case the UnitPrice of a book changes. Or even if the Quantity changes in table BookOrder etc.
Instead of using triggers you should probable use a view that calculates instantly the value you want. Something like:
SELECT b.id, bo.id, bo.quantity * b.uniprice TotalPrice
FROM BOOK b, BookOrder BO, BookInvoice BI
WHERE BO.Id = BI.OrderId
AND B.Id = BO.BookId

Cross-table multiplication


Poisson Distribution with Limousines

Question:
A car company has two limousines that it hires out by the day. The number of requests per day has a Poisson distribution with mean 1.3 requests per day.
If each limousine is to be equally used,on how many days in a period of 365 days would you expect a particular limousine to be in use?

I did $1.3/2 = 0.65$ per limousine, and $0.65*365 = 237.25$. The answer is $201$ days. How so?
Answer: The probability of receiving no requests in a day (causing both limousines to not be used) is
$$\mathsf P(k=0)=\frac{1.3^0e^{-1.3}}{0!}=0.272531$$
The probability of receiving exactly one request in a day (causing a limousine to be used half the time) is
$$\mathsf P(k=1)=\frac{1.3^1e^{-1.3}}{1!}=0.354291$$
If two or more requests are received in a day, both limousines will be used. Therefore the probability of a limousine being used for the day is
$$1-(0.272531+\tfrac12\cdot0.354291)=0.550322$$
Over 365 days, we expect a limousine to be used on $365\cdot0.550322=200.867$ days, which rounds to 201 days.

Poisson Distribution with Limousines


Why is static page response time going up with increased concurrent requests

Question: I don't understand the performance I'm seeing from apache. I would expect that more concurrent apache requests would perform better than fewer, up to a point, but beyond 3 concurrent requests, overall performance is flat. For example, I see the same requests / sec if I've got 3 or 4 concurrent requests. With each additional concurrent request, the avg response time increases so that the overall request handling rate stays the same.
To test this, I created a new ubuntu 10.04 vm on slicehost. This is a 4 core vm. I set it up with
<code>aptitude update
aptitude install apache2 apache2-utils curl
curl localhost/ # verify hello world static page works
</code>
Then I benchmarked the response time and reqs / sec.
Edit 4: I benchmarked with something like "for x in $(seq 1 40); do ab -n 10000 -c $x -q localhost/ | grep whatever; done".
The exact commands and data are at https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AurdDQB5QBe7dGtiLUc1SWdOeWQ4dGo3VDI5Yk8zbWc&output=html
Cpu usage was about 25% on each core while running the tests.
Edit 2: Memory usage was at 45 / 245 MB according to htop.
Edit 1: I just tried the same thing on an ubuntu 11.04 vm and the overall issue is the same, but the performance is even worse: it gets around 2100 reqs / sec for most levels of concurrency and uses about 50% cpu on each core.
Edit 3: I tried it on real hardware and saw a peak reqs / sec around 4 or 5 concurrent requests and then it dropped a little and flattened out.
Can anyone explain why this is happening, how I can figure out what the bottleneck is, or how I can improve this? I've done some searching and haven't found any answers.
Comment: Do you have anything in you Apache config file to tune performance? Specifically `StartServers`, `SpareServers`, `MaxClients`, etc?
Comment: Running the same test on my tiny VPS yields a nice curve that spikes up to 5kr/s at `-c 4` and levels around 5600r/s in the 20-30 concurrency range. My install is actually limited to 5 workers for memory reasons.
Comment: How you test will impact performance almost as much as what you are testing.  How are you testing performance?
Comment: Just saw your GoogleDocs file.  When opening a question, try to put all relevant info in your question and put supplementary information in external links.  Please edit your question to include your testing procedures.
Comment: @ChrisS: I used the defaults which are mpm-worker, StartServers 2, MinSpareThreads 25, MaxClients 150. If I understand this right it means that at startup, apache has enough workers sitting around to handle 40 concurrent requests. You're seeing increasing performance until you get to the 20 - 30 concurrent requests range. That's certainly better than capping out at 3 or 4. When it caps out, did you notice if your cpu is maxed out?
Comment: @ChrisS Hmm. Now that you told me that your performance jumped up and then slowly edged up further, I took another look at my graph and it kinda looks like that too. It's hard to tell for sure with all the noise but I think it's edging up slightly until around 15 concurrent reqs / sec and then flattening out. Anyway, I'm still dying to know what the bottleneck is.
Answer:
I don't understand the performance I'm seeing from apache. I would expect that more concurrent apache requests would perform better than fewer, up to a point, but beyond 3 concurrent requests, overall performance is flat.

It sounds like you're seeing exactly what you said you expected. More concurrent requests causes Apache to perform better, up to a point, and then performance is flat. What it seems has surprised you is that the point occurs with a low number of concurrent requests.
I'm not sure why you find that surprising. There's no real disk I/O, since the page is surely in RAM. So it's purely a CPU bound and network bound activity. Once you have enough requests that you can tie up all cores and fill the network down with one request will another request is going up, there's no reason more connections waiting would make things any better.
So that really only leaves the question of what the limiting factor is. It's hard to tell without more details, but I'd look at the amount of system CPU usage and the network bandwidth. Most likely, either the CPU or the network interface is maxing out.
Comment: Thanks David. That's a good way of phrasing it. Maybe I should revise my question: What's the bottleneck here? There's no disk i/o, the cpu isn't close to maxed out, and I'm running the benchmark over loopback, so network bandwidth isn't a factor.
Comment: Are you sure you're measuring the CPU usage accurately? System CPU usage counts too.
Comment: I'm looking at the numbers at the top of htop. Do you know if that includes everything? Would you recommend a different tool?
Answer: You are likely seeing the impact of overhead in the network stack. With increased concurrency, you will have more simultaneous connections open, so the system and apache has to work harder to open and close these connections.  This typically degrades Apache performance and result in a longer average time per request at concurrency levels.
I also suspect you had more Apache child processes running at higher concurrency levels.  This requires time to spin these up and down.
Network issues can be further complicated if you are running the test on the same system as the web server.
Tuning your TCP/IP stack, KeepAlive settings (if on), and Timeouts could improve this.
However, this is a long known issue with scaling apache.
Here's a classic article on the topic.
PDF: http://www.stdlib.net/~colmmacc/Apachecon-EU2005/scaling-apache-handout.pdf
Comment: [Even older systems network stack scale much better than a few thousand per second](http://bulk.fefe.de/scalability/). Apache reuses child workers, it doesn't fork a new one each time, forking has been O(1) since Linux 2.6. KeepAlive doesn't apply to the `ab` test. Timeouts shouldn't matter until the system runs out of ephemeral ports available (which *should* return an error to ab). The article is certainly interesting, but clearly aimed at concurrent connections, not new requests rate.
Comment: jeffatrackaid, thanks for the reminder. Colm's paper, while quite old, is still very relevant.
tbh, the wiki page I link is based on Sander S. Temme's ApacheCon presentation, which isn't that much younger either ;)
Answer: Please checkout the (not yet official) Performance documentation in the Apache httpd wiki:
http://wiki.apache.org/httpd/PerformanceScalingUp
A closing word: I don't know what "VM" implies in your case, but it could be a performance bottleneck.
Comment: Thanks for the link! I read through it and I've already looked at those points or they don't apply to the benchmark.

By VM I meant virtual machine, and Slichost is a virtual machine hosting company. The VM could be part of the problem but I also saw a similar phenomenon on real hardware.
Comment: Well, essentially it boils down to: Are you CPU, Memory or IO bound. IO splits up in Disk and Network.


Using keyboard/MIDI controller to learn piano

Question: I'm an adult just starting to learn music from scratch. The piano I have been using is sometimes not available for me to use, so I would like to buy a keyboard/MIDI controller so I can practice whenever I want and use headphones so I don't disturb neighbors with my racket.
Since I am space/budget limited, I was hoping to purchase a smaller keyboard - I've seen MIDI controllers with 25 keys (some even smaller) online and keyboards with as few as 44 keys (most seem to have 61/76). I realize it limits the range of music I can play, but I'll worry about that later, when I have more experience.
Is a keyboard or MIDI controller better to learn with? What is the fewest number of keys that I could still get a decent learning experience with (at least to learn basic notes/fingering/etc) and play basic pieces (like stuff children learn with)? If I transition to 88-key piano later, will the transition be tough (in terms of having more keys or the keys feeling different)? Thanks
Comment: Look for features like weighted keys should you go with a MIDI-keyboard.  Simple on-off buttons that look somewhat like piano keys are useless for the purpose of teaching.
Comment: Bear in mind that with a MIDI controller, you'll also need a sound module or you won't hear anything.
Answer: Let's be very precise about what we're talking about:
A MIDI controller is anything that can send MIDI commands to another MIDI device. Keyboard type MIDI controllers are only one kind. But, for the purposes of this answer, let's assume that whenever we say "MIDI controller" we mean the piano keyboard type.
A MIDI sound module is a device which accepts MIDI commands, and produces a sound. Those sounds could be artificial sounding beeps, realistic sounding simulations of a real instrument, or drums. Let's forget about the other types of sounds, and assume you're interested only in piano sounds.
What you refer to as a "keyboard", I will call a digital piano. It's the MIDI controller, and the MIDI sound module, all in one unit. (It's possible that internally, it's not using MIDI, but that's a detail that's not important). It's common for these to also have MIDI connections, so you can use them standalone, or as a controller, or as a sound module.
MIDI commands can be carried over traditional 5-pin MIDI cables, but nowadays they can also be carried over USB. This is important, because it means that a PC or a Mac -- or even an iPad/tablet/phone -- can become a MIDI sound module. For example, Macs come with GarageBand, which has perfectly acceptable piano sounds that you can play with MIDI. MIDI controllers often have some PC/Mac software bundled.
So:

You need a controller
You need a sound module
You might already own a sound module (your computer)
You might prefer to have everything in one unit, for convenience

The reason I stress you should think of a digital piano as a sound module and a controller in the same box, is that everything I am about to say about controllers, applies equally whether it is part of a digital piano or separate.
The very simplest controllers are just a row of on/off switches. You hold down a key, and a note plays. You release it, the note stops. You have no control over the loudness of the note. This is OK if you want to sound like early Kraftwerk; it's bad if you want to sound like a pianist.
More sophisticated controllers are velocity sensitive -- the harder (or actually, faster) you hit the key, the louder the note, just like a real piano. To have anything like the control a pianist has, you need velocity sensitivity.
There is also a feature called aftertouch. This lets you change the pressure on the key after the initial strike, to affect the sound. This is not something a real piano has, so if you are only interested in piano sounds, ignore aftertouch.
High end controllers have weighted keys. This is weight in the construction of they key, so it most closely simulates the feel of a real piano keyboard. Cheaper keyboards either abandon all effort to feel like a piano keyboard, or simulate weight using springs.
I think any ambitious learner needs a wide enough keyboard to play two-handed parts, and I think 61 keys is a minimum for that. 88 keys is the width of a real piano keyboard. With 61 keys, you will encounter pieces where you run out of notes and have to compromise somehow.
Some controllers have smaller keys. You want full-size keys.
My own choice: I have a 61 key USB/MIDI keyboard that is "semi-weighted". I think this is a good compromise between cost and realism (I previously played on my family's poorly maintained upright piano). You will notice a difference in feel between this and the piano you are using. The difference probably doesn't matter too much at first. In any case, you will want to learn to be able to play on different pianos. Real pianos vary in feel too.
Comment: Mine is an M-Audio Keystation.
Comment: Wow, loved this answer!
Comment: Would you mind digging up some links to the products you have tried and would recommend? I'm particularly interested in the 61-key semi-weighted USB/MIDI keyboard you mention liking for your own purposes.
Comment: Please do your homework good, semi weighted keys. weighted keys before you buy try them out. Also the sturdiness of the keyboard. Because what it's says doesn't mean it's what you are going to get, shop around before you buy.
Answer: I'd say a keyboard is better to learn with. It is desgined for playing music as a MIDI controller is designed for synthesizing music. However, most keyboards have basic MIDI functionality.
The fewest number of keys you can learn to play with is subjective. You can learn to play on one octave. However, this won't be enough for long. The number of keys is always a limiting factor, more so with fewer keys. For a beginner playing children's pieces, 44 keys is probably sufficient. However, many pieces use more keys. For these, you can probably get by with 72 or even a 61 key keyboard (unless you're hard set on playing pieces that require all 88 keys.) Although you could get by with a 61-key keyboard, it is somewhat stretching it. 44 keys is probably the absolute minimum you can go for learning. Anything less most likely won't be worth your money. My advice would be an 88-key, or a 72-key keyboard.
As far as the transition to an 88-key piano, having more keys to work with shouldn't be difficult. However, the keys are very likely too feel different. The weighting can vary between different keyboards, but this shouldn't be a major issue.
Comment: I find that the challenges in using a new piano keyboard are similar to using a new computer keyboard - the keys may feel a little different, and you may have access to new keys that you need to reach or jump a little farther to get to. You may have to change your technique if you're going to, say, and organ-style keyboard where the notes stop resonating almost immediately. But you listen, experiment, and adjust, and you get used to it.
Answer: you need at least 76 keys.  The teeny keyboards are for synth heads who just want to record a riff into their midi sequencer.
if you wish to be able to transfer your skills to a REAL piano (and you really should:),
you'll want a weighted keyboard.
All the digital pianos feel different (as do acoustics) - so be sure to TRY it before you buy.
Here's some more info:  http://pianocheetah.com/piano
If you really want to learn to play piano, get a teacher or you'll be WASTING your time.
good luck to ya.
Answer: Smallest possible kb is ABSOLUTELY best choise. Look for something which works with batteries and have sounds included (not just plain MIDI kb) and headphone connector.
Reason is that biggest reason why beginners won't learn to play is that they are away from their keyboards.
They don't usually have strong enough routines to go in front of that gigantic and expensive piano / keyboard, which easily leads to that they NEVER actually do those practices.
Portable mini-kb goes easily where you go - and you can start practicing everywhere when you have time. In bus, train etc... Just keep headphones with you. You might wanna use that kind of headphones which isolates external audio well, so that other noises wont disturb you (read: you don't disturb other ppl. around you in public places... ;) )
You don't have to think keyboard feel, hammer actions etc. in phase where you are to learn very first basics.
Play always you can, so that you start to live with your keys! That's gonna bring you some results.
Of course you have to memorize few useful practices before going anywhere with that portable kb. Otherways you will have "blank paper fear" because you can't do anything but gibberish with it. And hitting random keys wont help in learning process. :)
I would start from scales.
Good luck!


ANOVA with some paired and some unpaired subjects

Question: I am a biologist rather than statistician so I might lack some insight.
I have measurements on two paired groups (baseline and follow-up) along with a separate group of healthy controls.
In addition the design of the study is unbalanced (n = 12 for B and F and n = 5 for HC).
Question

Is there an ANOVA technique that would allow me to carry out a fair ANOVA taking the inherent pairing into account for groups Baseline and follow-up?

I've done some analysis already with paired t-tests for baseline versus follow-up and then unpaired tests for each group versus the healthy controls but I wondered whether I was missing a more elegant technique.
Comment: Do you mean that the healthy control has not baseline and follow-up? What is the hypothesis that is being tested?
Answer: An ANOVA is used in designed experiments, this experiment doesn't sound like it
was planned. I am not trying to be a purist here, but with unplanned experiments
it frequently happens that statistically significant results come from extraneous influences.
Even in experiments that result in using a paired statistic, procedure is important.
Suppose that you want to determine the effect of two medications, call them A and B, on mice. Also, suppose that you will give each mouse both medications after a suitable time has passed between the first medication. If you subject each mouse in the experiment first to medication A and then to medication B, and you run a paired t-test on the measured response with a statistically significant result; you will not known if the sigficance is from the difference in medications A and B or if it is a response to receiving any type of medication. Here, medications A and B are counfounded with just being medicated.
If you followed some correct procedure in this experiment, you could also set up a regression model to analyze your data. ANOVA's are a special case of fitting data using a linear model.
Comment: Hi schenectady. Thanks for your answer. The comparison was planned (by others - without statistical input I gather). It's human work and the drop out rate was rather large for various reasons. Basically I'm trying to help out as I'm the 'guy who knows R'. I'll have a look at the linear model lit but I expect it's beyond saving. Hey ho.


Can I trust a TCP segment with a payload of 255 bytes will be delivered in a single Ethernet frame?

Question: I'm writing some server software that upgrades the firmware on an electronic device. It's a tricky task, because currently these devices don't have enough memory to hold a full firmware before installing it. As a result my server will switch the device into boot loader mode, and instruct the boot loader what to do, sending instructions and firmware data over the network.
As you can imagine, there are some potentially massive downsides to this.
What I'm concerned with at the moment, is whether or not a single TCP segment that I send will be divided up across multiple Ethernet frames?
Due to the nature of the boot loader, the maximum size payload I can send in a TCP segment is 255 bytes.
From grabbing packets in Wireshark, it seems like the Frame size for a frame containing one of my TCP segments is 309 bytes (2,472 bits), well within the range allowed according to the Wikipedia page on Ethernet Frames :

I'm currently trying to handle what happens if the connection to the device is severed. As things are now I have no trouble reestablishing a connection with a device, but what I want to be sure of is what happens after a connection is reestablished.
If I can be sure that each instruction will always be contained in a single Ethernet frame, and as such, will either be delivered or won't be delivered then happy days! I can look at the last instruction sent and figure out what to do then.
However, if there's a possibility that the instruction can be split across two Ethernet frames then I have a much bigger problem. I don't think it should happen, but it sometimes looks like it does when I'm testing.
Say I have issued a write command, and the boot loader is waiting for data to write, I send my TCP segment with 255 bytes and it gets split across two Ethernet frames. The first frame gets delivered but the second one doesn't. Now when I reconnect I have to figure out exactly how many bytes the boot loader has already received, which means I need to push dummy data and listen for a response. I'd really like to avoid that if possible.
Reading from the comments in this thread, it seems that IP packets smaller than 576 bytes (4,608 bits) won't be split up.
Am I safe in assuming that this is always the case?
Actually, If it is split up, then the WiFi module shouldn't deliver the TCP segment until it has been re-assembled, isn't that correct? And it will be discarded if the connection is lost.
Comment: You can set the DF bit in the IP header. You could always use PMTUD to determine, first, if the MTU in the path is big enough.
Comment: Also, when IP packets are fragmented (frames don't get split, packets do, resulting in multiple frames on the new link after the router fragments the packet), it is up to the receiving host to reassemble the packet fragments, per RFC 791. Routers will fragment packets, if necessary, for the MTU of the next link, but they will not reassemble the fragments. A Wi-Fi AP is merely a translating bridge which converts ethernet frames into Wi-Fi frames, and vice versa.
Comment: If the DF bit is set, then the IP packets are not being fragmented. They would, instead, be dropped, and an ICMP message returned to the sender.
Comment: Thanks again! Just looking at Wireshark here and the DF bit is already set in the packets
Comment: Thanks for your help, that's one thing clarified, and one less thing to worry about.
Answer: In general it's very hard to control wether a packet get's split or not. You would need to get very deep on the stack actually - things like offloading TCP to hardware may also get into the way and create packets that are optimised for transportation.
But you're talking about a TCP connection - so there shouldn't be any issue if your connection has a short interrupt. If a single TCP packet get's split into multiple ethernet packets and your connection drops (for a short moment) in between the transmission of a single frame, TCP will retry to transmit the packet (which is part of the protocol).
Having a longer / detected disconnect, a much bigger issue will be the fact, that you can't just continue sending without reestablishing a new connection (which would need your device to support this) - setting up a new socket and sending to the same remote host without TCP syn/ack is propably not supported by any default stack.
Regarding your desired goal (if possible) i would recommend to have a proper way to handle interruptions during the firmware upgrade (like dual boot).
If this is not possible and you're not implementing your own TCP/IP stack, i just can recommend to disable any hardware accelation on your server (to prevent hardware from reassembling your packets) and disable nagle's alogorithm on your socket connection.
Comment: Depending on the microcontroller running on the device, you can have two seperate locations for your runtime image on the same device (let's say you split your storage into two parts) and when your current firmware is on the first half, you write the new firmware to the second one. final step of flash is to change the pointer of the current firmware to the second half (the pointer should be in a single location that can be written in one step). If flashing fails, you will still boot from the first / old firmware.
Comment: Another option is to make sure that your bootloader with a minimal network stack - just enough for flashing is always available. So - if you're in flash mode and reboot, you always can restart the procedure. This is something like dual boot, just that the second image is just the bootloader which may be much smaller (depending on your hardware this may fit).
Comment: Hi Daniel, thanks for your answer. The situation I'm concerned with is indeed a longer disconnect. currently my server disconnects after a 4 second timeout. The device is capable of re-establishing a connection in this scenario, it's WiFi module handles that automatically, so that isn't a problem, in fact when testing we've rebooted the server and still successfully managed to continue flashing.I suppose, since TCP is an extremely robust protocol it might be in our interests to extend the timeout period on both ends of the connection a bit just in case. Can you elaborate a little on dual boot?
Comment: Ah yes, we don't have enough memory for that right now, currently we're wiping the old firmware before pushing the new one. We will be increasing the memory in the next hardware version for this very reason.


How to Extract the URL from A String in PHP?

Question: I'm using PHP's "simplexml_load_file" to get some data from Flickr.
My goal is to get the photo url.
I'm able to get the following value (assigned to PHP variable):

codewrecker posted a photo:

How can I extract just this part of it?
http://farm3.static.flickr.com/2298/2302759205_4fb109f367_m.jpg

Just in case it helps, here's the code I'm working with:
<?php
$xml = simplexml_load_file("http://api.flickr.com/services/feeds/photos_public.gne?id=19725893@N00&lang=en-us&format=xml&tags=carousel");
foreach($xml->entry as $child) {
    $flickr_content = $child->content; // gets html including img url
    // how can I get the img url from "$flickr_content"???
 }
?>

Answer: You can probably get away with using a regular expression for this, assuming that the way the HTML is formed is pretty much going to stay the same, e.g.:
if (preg_match('/<img src="([^"]+)"/i', $string, $matches)) {
    $imageUrl = $matches[1];
}

This is fairly un-robust, and if the HTML is going to change (e.g. the order of parameters in the  tag, risk of malformed HTML etc.), you would be better off using an HTML parser.
Answer: It's not solving your problem(and probably total overkill), but worth mentioning because I've used the library on 2 projects and it's well written.
phpFlickr - http://phpflickr.com/
Answer: Easy way:  Combination of substr and strpos to extract first the  tag and then the src='...' value, and finally the target string.
Slightly more difficult way (BUT MUCH MORE ROBUST): Use an XML parsing library such as simpleXML
Answer: I hope this is helpful.  I enjoy using xpath to cut through the XML I get back from SimpleXML:
<?php
$xml = new SimpleXMLElement("http://api.flickr.com/services/feeds/photos_public.gne?id=19725893@N00&lang=en-us&format=xml&tags=carousel", NULL, True);
$images = $xml->xpath('//img');  //use xpath on the XML to find the img tags

foreach($images as $image){
    echo $image['src'] ;  //here is the image URL
}
?>


Valores com base no último dia de cada mês (Excel)

Question: Editado:
Pessoal, esse é meu arquivo de Excel. Eu quero o ultimo valor de cada mês da coluna A seja referenciado pela coluna C, ou seja, para o mês e ano de cada linha da coluna A devo encontrar o valor do que seria referente ao último dia desse mesmo mês e ano, pegando o valor que está nesta linha na coluna D..
Por PROCV consigo fazer?
<code> A           B      C          D
30/12/1988  1,8085  30/12/1988  1,8027
31/01/1989  1,7500  31/01/1989  1,7479
28/02/1989  1,7440  28/02/1989  1,739101
31/03/1989  1,6852  31/03/1989  1,6819
28/04/1989  1,6890  28/04/1989  1,6858
31/05/1989  1,5715  31/05/1989  1,564201
30/06/1989  1,5490  30/06/1989  1,543899
31/07/1989  1,6660  31/07/1989  1,6583
31/08/1989  1,5730  31/08/1989  1,5617
29/09/1989  1,6145  28/09/1989  1,605299
31/10/1989  1,5775  27/10/1989  1,5723
30/11/1989  1,5695  30/11/1989  1,5628
29/12/1989  1,6145  29/12/1989  1,6031
31/01/1990  1,6794  31/01/1990  1,6695
28/02/1990  1,6892  28/02/1990  1,667699
30/03/1990  1,6480  30/03/1990  1,6384
30/04/1990  1,6389  30/04/1990  1,632197
31/05/1990  1,6765  31/05/1990  1,668499
29/06/1990  1,7450  29/06/1990  1,739399
31/07/1990  1,8600  31/07/1990  1,852199
31/08/1990  1,8920  31/08/1990  1,8844
28/09/1990  1,8735  27/09/1990  1,8693
31/10/1990  1,9440  31/10/1990  1,934101
30/11/1990  1,9392  28/11/1990  1,9588
31/12/1990  1,9285  31/12/1990  1,9192
31/01/1991  1,9650  31/01/1991  1,9564
28/02/1991  1,9100  28/02/1991  1,903115
29/03/1991  1,7485  28/03/1991  1,732099
30/04/1991  1,7225  30/04/1991  1,7174
31/05/1991  1,6980  31/05/1991  1,690332
28/06/1991  1,6180  28/06/1991  1,614698
31/07/1991  1,6845  31/07/1991  1,679599
30/08/1991  1,6800  30/08/1991  1,6743
30/09/1991  1,7520  30/09/1991  1,7436
31/10/1991  1,7425  31/10/1991  1,7324
29/11/1991  1,7655  29/11/1991  1,759256
31/12/1991  1,8660  31/12/1991  1,860501
31/01/1992  1,7890  31/01/1992  1,7783
28/02/1992  1,7560  28/02/1992  1,7491
31/03/1992  1,7363  31/03/1992  1,7272
30/04/1992  1,7750  30/04/1992  1,766502
29/05/1992  1,8290  29/05/1992  1,8206
30/06/1992  1,9035  30/06/1992  1,894701
31/07/1992  1,9200  31/07/1992  1,916501

...
</code>
Alguma ajuda/intuição?
Obrigado.
Answer: Fala Diogo!
Não sei se entendi muito bem o que você quer. Veja se eu entendi certo:
Você quer que o valor da E1 (E2,E3,E* e etc) seja sempre o último valor da D1 (D2,D3,D* e etc)?
Se for isso, basta inserir na coluna E1 (E2,E3,E* e etc) a formula:

=right(D1,1)
  =right(D2,1)
  =right(D3,1)
  =right(D*,1)
  etc..

Caso você queira que o valor da E1 (E2,E3,E* e etc), seja sempre o valor da célula acima, apenas troque o "D2" pelo "D1". Porem você teria que começar da segunda linha.

=right(D1,1) erro
  =right(D1,1)
  =right(D2,1)
  =right(D*,1)
  etc..

Caso você tenha uma lista dos valores do meses dez/88; jan/89; fev/89; e etc, ai você irá precisar do procv na sheet de cada mês e utilizar a função maior() (ou max())  em uma coluna ao lado e apontar pra sua lista.

=VLOOKUP(A1;'Página2'!A:E;5;0) "essa formula entra na E1 da 'Aba 1' "
  =MAX(D:D) "essa formula ficaria na 'Aba 2' ao lado do valor D1 (por exemplo)"

Aonde foi seleciona uma área de A ate E, aonde em E deve ser colocado o MAX() da coluna D;
Veja: https://goo.gl/tQwC29
Para ver a lista de conversão de formulas do excel de ENG e PT:
https://usuariosdoexcel.wordpress.com/lista-de-funcoes-do-excel/
Por acaso é alguma das três opções ? Caso contrário, fala ae! :)
Comment: A ideia é fazer o procv mesmo. O que eu quero é que na primeira celula da coluna E1 o meu procv procure na coluna D1 o ultimo valor associado ao mês da primeira celula de A1. Na segunda celula da coluna E1 esse procv me devolveria o ultimo valor da coluna D1 associado ao mês da segunda celula da coluna A1 e assim por diante.
Comment: Valeu pelos outros comandos, acabei percebendo que irei precisar deles em outro momento. Valeu!
Answer: Diogo, resolva assim:
Na coluna F coloque a fórmula abaixo para cada linha de sua tabela
<code>=DATA(SE(MÊS(A1)=12;ANO(A1)+1;ANO(A1));SE(MÊS(A1)=12;1;MÊS(A1)+1);1)-1
</code>
Ela pega o mês e ano da coluna A da respectiva linha (neste caso, a linha 1) e gera a última data do mês correspondente.
Por exemplo:
<code>dez/88         31/12/1988

jan/89         31/01/1989
</code>
Coloque a fórmula abaixo na coluna E e pronto!
<code>=PROCV(F1;C1:D80;2;VERDADEIRO)
</code>
O VERDADEIRO faz com que ele pare a busca na resposta exata ou no valor imediatamente anterior a um valor superior ao procurado (complicado, né?), caso não haja resposta exata.
Se precisar tratar a busca, use o SE com o mesmo PROCV dentro, e se der certo repita o PROCV na parte da resposta correta para ele por o valor encontrado pelo PROCV, senão, coloque "branco" ou uma mensagem que não achou a data correspondente na parte não verdadeira da resposta (do comando SE).
Coloque a faixa de busca apropriada para você!
Funcionou amigo?
Comment: Oi, Leo! Eu editei a pergunta. Consegui organizar melhor, acho que ficou até mais claro. Na maneira que você sugeriu consigo fazer?
Comment: Fiz o PROCV para você. Vou postar, olha o boi!...
Comment: Valeu, Léo! Funcionou demais! Muito obrigado!
Comment: Por nada, bom trabalho!


Por que o comando 'cd' não funciona via ssh no GOCD?

Question: Estou tentando rodar o comando abaixo no terminal do GOCD, porém sempre ocorre o erro:
Comando
ssh root@host 'cd /var/www/gda-frontend/ && docker-compose up -d --build'

Erro

bash: cd /var/www/gda-frontend/ && docker-compose up -d --build: Arquivo ou diretório não encontrado

O diretório existe, porém ele não consegue rodar. E já há a conexão via ssh sem senha entre os dois.
Mesmo rodando somente o cd, sem o comando docker-compose, ocorre o erro.
Comment: Tente desta maneira: ssh root@host '/var/www/gda-frontend/docker-compose up -d --build' P.s: Não consigo comentar por isto postei em forma de pergunta.
Answer: Não consegui ver nada de errado, se o diretório realmente existe.
Com a conexão estabelecida, confirme se o diretório realmente existe e se o nome do mesmo está correto:
ssh root@host 'cd /var/www/ && ls'

O erro resposta é bem claro 'Arquivo ou diretório não encontrado'. Pode ser que o diretório seja em '/var/www/html/gda-frontend/', mas agora é apenas uma suposição minha.


always include language code in url

Question: For SEO reason I need my site to always use language code in the URL. At the moment mysite.com/en/news is also accessible through mysite.com/news, according to my SEO contact, mysite.com/news should return content.
How do I achieve this behavior?
Comment: check this answer http://drupal.stackexchange.com/questions/19078/how-to-redirect-url-with-language-prefix-to-the-same-url-with-no-prefix-default
Comment: Thanks but that question is about "all the URL **without language prefix** show the Japanese pages". I do not want to use URLs with no language code. I **always** want to use language code. Therefor I having a hard time using the answer for my question.
Answer: Using the Global Redirect module with the default options. You can redirects all URLs without a language prefix to the correct URL with the default language prefix contained.
Comment: great minds....
Answer: This is what you have (for example):

mysite.com (default)
mysite.com/fr (French)

This is what you are looking for (for example):

mysite.com/en (default)
mysite.com/fr (French)

This can be accomplished in your language settings. For each language you can set a Path prefix, use en and fr (for my example).
To redirect mysite.com to mysite.com/en you can use the Global Redirect module
Answer: In Drupal 8 you can go to Manage > Configuration > Regional and language > Languages > Detection and selection > URL (configure).
Here you can add a prefix for the URLs for every language.

always include language code in url


compact set under two topological

Question: Let $\Omega_1\subset\Omega_2$ be two topological structures in $X$.Does the compactness of $(X,\Omega_2)$ imply that of $(X,\Omega_1)$,or vice versa?
Since there are more open sets in $\Omega_2$ than that in $\Omega_1$,so I think the compactness of $(X,\Omega_1)$ imply that of $(X,\Omega_2)$,is it right?
Comment: It is the other way around compactness of $(X,\Omega_2)$ implies $(X,\Omega_1)$ is compact.
Answer: Take $\Omega_1$ to be the standard topology on $[0,1]$ and $\Omega_2$ is the discrete topology  on $[0,1]$. It is known that $[0,1]$ under $\Omega_1$ is compact, but $[0,1] = \cup_{x\in[0,1]} \{x\}$ is an open cover of $[0,1]$ for $\Omega_2$, and does not admit a finite subcover hence $[0,1]$ is not compact for the discrete topology.
It works the other way around: suppose $X$ is compact for $\Omega_2$. Let $(U_i)_{i\in I}$ be a cover of $X$ with opens from $\Omega_1$. All $U_i$'s are opens of $\Omega_2$, hence you can get a finite subcover as per the compactness of $X$, hence $X$ is still compact under $\Omega_1$.
Answer: If $(U_i)$ is an open cover of $(X,\Omega_1)$, then it's also an open cover of $(X,\Omega_2)$, hence admits a finite subcover.
Comment: Your answer is opposite to the comment above.
Comment: No, this answer is exactly the same as the comment by @azarel. See my answer for details.

compact set under two topological


Como usar Url.Action em um Helper Razor?

Question: Em um projeto ASP.NET MVC5, criei um Helper dentro da pasta App_Code, porém, ao utilizar a função Url.Action() no meu Helper ocorre o seguinte erro de compilação:

CS0103: The name 'Url' does not exist in the current context

Meu código:
@helper testeHelper()
{
    teste
}

Answer: Dentro do Helper não temos acesso aos Helpers padrões, para utilizá-los é necessário passar como parâmetro.
O código do Helper, fica assim:
@using System.Web.Mvc
@helper testeHelper(UrlHelper Url)
{
    teste
}

E na sua View faz assim para chamar o Helper:
@MeusHelpers.testeHelper(Url);


Erro no Modulo Django

Question: Sempre que tento executar, estou recebendo o seguinte erro descrito abaixo. Já pesquisei uma solução, mas não consigo fazer que funcione.

Exception Type:    ValueError
      Exception Value:
      ModelForm has no model class specified.
      Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/models.py in init, line 275
      Python Executable:  /usr/bin/python
      Python Version: 2.7.6

views.py
@login_required(login_url='/login/')
def cad_professor(request):
    context = {}
    if request.method == 'POST':
        form = ProfessorForm(request.POST)
        if form.is_valid():
            form.save()
            context['success'] = True
    else:
        form = ProfessorForm()
    context['form'] = form
    template_name = 'envelope/cad_professor.html'
    return render(request,template_name , context)

forms.py
from django import forms
from .models import Professor

class ProfessorForm(forms.ModelForm):

    class meta:
        model = Professor

Comment: o código está formatado exatamente como o seu?
Comment: Desculpas, consertei agr esta sim
Answer: @TheuzC,
o seu meta na verdade é Meta.
Tente isso ai:
class ProfessorForm(forms.ModelForm):

    class Meta:
        model = Professor

Answer: Verdade, consegui da seguinte forma
class Meta:
    model = Professor
    fields = '__all__'      << Django estava pedido

e models tinha uma declaração pra o banco errado, então quando ia acessar ele não existia e dava erro por não encontrar

Erro no Modulo Django


How to restrict a page to a group of people?

Question: I am trying to figure out how I can lock down a page (part of my site) to a list of users that I have in another MySQL DB.
Ideally I would like to call the DB and see if the user has access each time they login. Is there any modules that would do this? Or has anyone done anything similar before.
Answer: You can add the secondary database to Drupal by following this tutorial: https://www.drupal.org/node/18429
I would probably run a hook_node_view so that it's called before rendering the node and adding your custom logic there.


Need SQL Query for accessing different serial numbers present in a table

Question: I have a table containing "ID" column.
Different numeric ids are present in this column from 1000 to 9999.
(1000, 1001.....,5000,5001....,8000,8001....,9000....9999).
Now I need a "generic" query which will give me distinct starting id series number present in this column.
for example, desired output
1000,
5000,
8000,
9000

If in future 7000 series is added in the ID column then output of the same query should include 7000 also in list like
1000,5000,7000,8000,9000

Comment: Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results.
Comment: No not like this. Generic for data
Answer: Another way to do it if your series start with every thousand
SELECT id
  FROM table1
 WHERE id % 1000 = 0

Here is SQLFiddle demo

Now here is a generic way which treats every "island" in id values (a sequence of values where next = prev + 1) as a series. This way a series can start and stop with any value
SELECT t1.id
  FROM table1 t1 LEFT JOIN table1 t2
    ON t1.id = t2.id + 1
 WHERE t2.id IS NULL

Here is SQLFiddle demo
Comment: Thanks peterm. It even better   :)
Answer: try this and its for 2 zeros..
select * from table where id like '%000' or id like '%00';

Comment: I would have thought that an ID Column was not a String
Comment: @user2310289 i tried it and its worked
Comment: @user2310289: the solution is relying on implicit data type conversion and the fact that SQL Server and MySQL (the two DBMS tagged in the question) are pretty forgiving when it comes to datatype checking. The query would fail on DBMS with a more strict data type check (e.g. Postgres).
Comment: Ah, I am a postgres guy.  Good to know it works.
Comment: Wouldn't this fail, if a new series starts with say 7500?
Comment: @Raj i feel you need only 000 after number as above you mention thats y i give this answer..i try to figure out it
Comment: @Raj: it would not fail for `7500`. But `75000` would (incorrectly) be returned. Peterm's answer is the correct one (and it's much more "generic")
Comment: @Raj i am edited answer...now its depends your condition...its 2 zero or 3zero or etc...
Comment: Thanks Anshul Parashar. It has solved my problem. I couldn't imagine it would be so simple.
Answer: Try This
SELECT min(id) from tablename group by SUBSTRING(id, 1, 1)


why $w(B^*AB)\leq \|B\|^2w(A)?$

Question: Let $E$ be a complex Hilbert space, $\mathcal{L}(E)$ be the algebra of all bounded linear operators on $E$. If $S\in \mathcal{L}(E)$, the numerical radius of $S$ is defined us
$$w(ََS) = \sup_{\|u\|= 1}|\langle Su, u\rangle |.$$

For $A,B\in \mathcal{L}(E)$, why
  $$w(B^*AB)\leq \|B\|^2w(A)?$$

Thank you!
Answer: For each $u$ with norm $1$, we have
$$|\langle B^*ABu,u\rangle|=|\langle ABu,Bu\rangle| = \|Bu\|^2\,\left| \left\langle A(\frac{Bu}{||Bu||}), \frac{Bu}{||Bu||}\right\rangle \right| \leq ||B||^2 \,w(A)$$
Taking the supremum over all such $u$ with norm $1$ gives us $w(B^*AB) \leq  ||B||^2 w(A)$ as required
Answer: You can estimate
$$
w(B^\ast AB) = \sup_{\|u\| = 1} |\langle B^\ast A B u, u\rangle| =
\sup_{\|u\| = 1} |\langle A B u, Bu\rangle| \le
\sup_{\|v\| \le \|B\|} |\langle A v, v\rangle| =
\sup_{\|v\| \le 1} \|B\|^2 |\langle A v, v\rangle| \, .
$$

why $w(B^*AB)\leq \|B\|^2w(A)?$


Prove that if $0<a<b$, then $a<\sqrt{ab}<\dfrac{a+b}{2}<b$

Question: Prove that if $0<a<b$, then
$a<\sqrt{ab}<\dfrac{a+b}{2}<b.$
I have seen that the inequality $\sqrt{ab}\leq (a+b)/2$ is verified for all $a,b\geq 0$.
Comment: If you know the middle inequality, then the other two inequalities come from the assumption $0 (a+b)/2$.
Answer:
Proof without words. Imagine that the red segment is length $a$, and the blue segment is length $b$. See if you can find the lengths of the other segments.
Comment: This is beautifull. You should use different colors for $\sqrt{a \cdot b}$, though.
Answer: This are $3$ inequalities, and $1$ is already solved. $2$ to go, lets solve them by equivalence transformations:
The first one ($a < \sqrt{ab}$):
\begin{align}
a &< \sqrt{ab} \\
a^2 &< ab \\
a &< b
\end{align}
The last one ($\dfrac{a+b}{2} < b$):
\begin{align}
\dfrac{a+b}{2} &< b \\
a + b &< 2 \cdot b \\
a &< b
\end{align}
Comment: Something bothers me about the order you're proving things. You should never start with what you want to prove.
Comment: @Hubble he mentioned that he would solve them by equivalence relations, it is easy for OP to start with $a < b$ and work his way up to the wanted inequality... sometimes starting with what you want to prove is the best way to find out how to prove it
Comment: He said equivalence transformations, not relations... In this simple case I have to disagree that starting with what you want is the best route, but to each his own I guess.
Answer: Note that
$$a\lt b\implies\sqrt a\lt\sqrt b\implies \color{Red}{a\lt\sqrt{ab}}$$ and $$a\lt b\implies a+b\lt 2b\implies \color{Red}{\dfrac{a+b}{2}\lt b}.$$
Also expanding $$(\sqrt a-\sqrt b)^2\gt 0$$ yeild us $$\color{Red}{\sqrt {ab}\lt\dfrac{a+b}{2}}.$$ Now combine all of them.
Answer: Hint:
As all numbers are positive, you can square the consequent, and you must establish
$$a^2<ab<\left(\frac{a+b}2\right)^2<b^2$$
or, subtracting $ab$,
$$a(a-b)<0<\left(\frac{a-b}2\right)^2<b(b-a).$$


An aproximation of the lambertw function for a complex number

Question: Here is my problem,
 I used the fact that $W(x)=\ln(x)-\ln(W(x))$, replacing $W(x)$ by $\ln(x)-\ln(... $ a lot amount of times and it seems to works for simple $x$ but when I try with, for example, $\ln(-2)/2$ or $i*pi/2+\ln(2)/2$ ,as you like, it doesn't work anymore.
To help you understand the situation I'm in I try to solve $a^b=b^a$ for $a<0$ which means solving $\ln(a)/a=\ln(b)/b$ and as you know $W(-\ln(b)/b)=-\ln(b)$.
 I can get the result with matlab but most of the time I can't use  my computer so I use a Texas Instrument Ti 82 Calculator, I programmed it to calculate real (from $-1/e$ to $+\infty$) Lambert $W$ values and now I try to do it with complex values so i need an algorithmic way to do it.
Comment: Wow... could you put some paragraph breaks in there? :)
Answer: Kennedy,
I've developped in VBA (Excel) a macro which handles the W-Function both in real and imaginary axis. The results for the real part are 100% accurate. As for the imaginary part, I couldn't test it yet, due to the lack in internet of a reliable W-Function calculator for complex numbers. I hope it helps.
Credits: http://www.vbforums.com/showthread.php?683003-Lambert-W-function-for-Excel-work-on-real-and-complex-number
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Const e As Double = 2.71828182845905
Sub Main()
Dim number(1) As Double, result() As Double
number(0) = 88 'real value
number(1) = 1 'imaginary value
result = LambertWc(number)
End Sub
Public Function setComplex(X As Double, y As Double) As Double()
Dim arr(1) As Double
arr(0) = X
arr(1) = y
setComplex = arr
End Function
Public Function ImgSum(ByRef Z1() As Double, Z2() As Double) As Double()
Dim K(1) As Double
K(0) = Z1(0) + Z2(0)
K(1) = Z1(1) + Z2(1)
ImgSum = K
End Function
Public Function ImgSub(ByRef Z1() As Double, ByRef Z2() As Double) As Double()
Dim K(1) As Double
K(0) = Z1(0) - Z2(0)
K(1) = Z1(1) - Z2(1)
ImgSub = K
End Function
Public Function ImgProduct(ByRef Z1() As Double, ByRef Z2() As Double) As Double()
Dim K(1) As Double
K(0) = Z1(0) * Z2(0) - Z1(1) * Z2(1)
K(1) = Z1(0) * Z2(1) - Z1(1) * Z2(0)
ImgProduct = K
End Function
Public Function ImgDiv(ByRef Z1() As Double, ByRef Z2() As Double) As Double()
Dim K(1) As Double
K(0) = (Z1(0) * Z2(0) + Z1(1) * Z2(1)) / (Z2(0) ^ 2 + Z2(1) ^ 2)
K(1) = (Z1(1) * Z2(0) - Z1(0) * Z2(1)) / (Z2(0) ^ 2 + Z2(1) ^ 2)
ImgDiv = K
End Function
Public Function ImgExponential(ByRef Z() As Double) As Double()
Dim K(1) As Double
t = -(Atn(Z(1) / Z(0)))
K(0) = (e ^ t) * Cos(Log(((Z(1) ^ 2) + (Z(0) ^ 2))) / 2)
K(1) = (e ^ t) * Sin(Log((Z(1) ^ 2 + Z(0) ^ 2)) / 2)
ImgExponential = K
End Function
Public Function ImgSqrt(ByRef Z() As Double) As Double()
Dim K(1) As Double, r As Double, t As Double
r = Sqr(Z(0) ^ 2 + Z(1) ^ 2)
t = Atn(Z(1) / Z(0))
K(0) = Sqr(r) * Cos(t / 2)
K(1) = Sqr(r) * Sin(t / 2)
ImgSqrt = K
End Function
Public Function ImgLog(ByRef Z() As Double) As Double()
Dim K(1) As Double, r As Double, t As Double
r = Sqr(Z(0) ^ 2 + Z(1) ^ 2)
t = Atn(Z(1) / Z(0))
K(0) = Log(r)
K(1) = t
ImgLog = K
End Function
Public Function LambertWc(ByRef W() As Double) As Double()
Dim Z() As Double, X() As Double, Z1() As Double, Z2() As Double, Z3() As Double, Q1() As Double
If W(0) = 0 And W(1) = 0 Then
    Z(0) = 0
    Z(1) = 0
Else
    ' complex parameter
<code>' approx initial value = sqtr(2*(1+e*x))-1
X = W
Z = ImgProduct(X, ImgExponential(setComplex(1, 0)))
Z = ImgProduct(setComplex(2, 0), ImgSum(setComplex(1, 0), Z))

If Z(0) = 0 And Z(1) = 0 Then

        Z = setComplex(-1, 0)

Else

        Z = ImgSub(ImgSqrt(Z), setComplex(1, 0))

        For i = 1 To 100
         Z1 = ImgSub(Z, ImgLog(ImgDiv(X, Z)))
         Z1 = ImgSub(setComplex(0, 0), Z1)

         Z2 = ImgProduct(setComplex(2, 0), ImgDiv(Z1, setComplex(3, 0)))
         Z2 = ImgSum(setComplex(1, 0), ImgSum(Z, Z2))
         Z2 = ImgProduct(ImgSum(Z, setComplex(1, 0)), Z2)
         Q1 = ImgProduct(setComplex(2, 0), Z2)

         Z2 = ImgSub(Q1, ImgProduct(setComplex(2, 0), Z1))
         Z2 = ImgDiv(ImgSub(Q1, Z1), Z2)

         Z3 = ImgDiv(Z1, ImgSum(setComplex(1, 0), Z))

         Z2 = ImgSum(setComplex(1, 0), ImgProduct(Z3, Z2))
         Z1 = ImgProduct(Z, Z2)

              If Z(0) = Z1(0) And Z(1) = Z1(1) Then
              Exit For
              Else
              Z(0) = Z1(0): Z(1) = Z1(1)
              End If

           Next
End If

End If
</code>
Final:
LambertWc = Z
End Function
Answer: since no one seemed to be able to help i kept searching and found an answer, using the infinite tower of complex number's propriety :  $z^{z^{z^{z^{.^{.^{.^{}}}}}}}=W(-ln(x))/(-ln(x))$.
So with that i can found $W_{0}(x)$ but i have no clue for how to find the complex $W_{-1}(x)$


sam local invoke, will it actually upload to s3?

Question: I've made tons of search but couldn't find an answer. I got this lambda function which basically uploads file to s3 and I got a test s3 bucket. I run the function via sam local invoke... everything seems to be working fine no error messages nothing but I dont see this file on s3 bucket. When running the function locally it actually doesn't upload it to s3? I would be happy if you confirm this.
Thanks.
Comment: Using the same credentials that the lambda  can you upload the file to s3 with the CLI?
Answer: Yes, if a function puts an object into an S3 bucket, it will do you it, when it is triggered by "sam local invoke".
I would suggest checking the credentials, bucket names/paths, waiting for the response from the PutObject event