Controlar o evendo do botão voltar do navegador

Question: Estou utilizando a função em jQuery onbeforeunload mas ela está sendo ativada pelo voltar do navegador (Back Button).
Gostaria de saber como controlar o evento voltar do navegador, já tentei várias possíveis soluções mas nenhuma funcionou.
Meu objetivo é anular a ação do onbeforeunload quando o botão voltar do navegador for ativado, para que a mensagem não apareça.
var botao_voltar == MANEIRA DE CAPTURAR O EVENTO;

if (botao_voltar == false)
{
    onbeforeunload = function()
    {
        return 'MENSAGEM PARA O USUÁRIO';
    }
}

Comment: `window.history.back();` ?
Comment: Podes explicar a funcionalidade que queres ter usando o `onbeforeunload `? vai ser difícil separar esses eventos.
Comment: @Sergio fiz um exemplo do Script, na verdade eu quero anular o botão voltar do onbeforeunload
Answer: Vou dar uma solução que tambem envolve alguns outros problemas que venho sofrido com meu cliente e, que muita gente tem dito que eh impossível contornar.
Bom, segue o código comentado, onde ele permite apenas que a mensagem de saída da pagina seja exibida  quando ocorre o click no botão reload, ou quando o cliente vai para uma nova pagina. Por exemplo digitando um novo endereco na barra de URL..
MAS, se ele apertar F5, ou CTRL+R, ou BackSpace, ou ainda dar click no botão Back do navegador ele executa aquela ação, mas não exibe a mensagem de alerta de saída da pagina.
no caso na nossa empresa, ele atende:
       // para o botao voltar do navegador

    detectedBrowser= Qual_Eh_o_Seu_Browser?;

            if(detectedBrowser==InternetExplorer){history.pushState( "nohb", null, "URL_Corretaaaaa" );}
            else    {history.pushState( "nohb", null, "" );}

            window.onpopstate = function(event) {               // JS version
        //  $(window).on( "popstate", function(event){          // Jquery version
                console.log('MESSAGE  213 = ' + flag_beforeunload )
                if( !event.state ){                             // JS version
        //      if( !event.originalEvent.state ){               // Jquery version

                        // para desabilitar o botao BACK do navegador, descomente as linhas abaixo:
                        //  history.pushState( "nohb", null, "" );
                        //  return;

                        // para tratar o evento UnBeforeUnload voce tem as linhas abaixo..  modifique conforme sua necessidade... neste exemplo ele so volta uam pagina, sem pop up.
                            flag_beforeunload=false;
                         window.history.back();

                }
            };

//
//escutando o teclado
//

    document.onkeydown = KeyCheck;
    function KeyCheck(e) {
        var key = (window.event) ? event.keyCode : e.keyCode;
        if(key==116) {flag_beforeunload=false;}
        if(key==8) {flag_beforeunload=false;}
        if (e.keyCode == 82 && e.ctrlKey) {flag_beforeunload=false;}
        if(e.keyCode == 91) {flag_beforeunload=false;}      // safari
        if (e.keyCode == 82) {flag_beforeunload=false;}     // safari

        document.getElementById("container").innerHTML = "key = "+key + " - " + flag_beforeunload;
    }

//
// o evento UnBeforeUnload
//
        window.onbeforeunload = function(e){
            var msg = 'Deseja mesmo sair?';
            e = e || window.event;

            if(e)
                if (flag_beforeunload == true) {
                    return msg;
                }
        }

Por favor use com cuidado, lembre-se que eh um exemplo....
então esta longe de ser perfeito!! deve ser adequado as suas necessidades
obrigado!
Ele funciona bem no chrome, Jah no firefox, iexplorer e safari ainda estou vendo maneiras de funcionar.
ps: tambem coloquei no fidle, mas nesta pagina não esta funcionando completamente.. por favor faca local para testes...


Confusing billing on Google Cloud Platform

Question: I have a Google Compute Instance service, first time using it, and I noticed that the billing was a bit too much.
After doing some research, Google is an on-demand service, which means I pay for what I use, but that still doesn't make any sense. Trying to crunch the numbers, it makes sense that I also have to pay for the egress, but the numbers don't add up properly. It's been about six days since I opened the n1-standard-4, and that comes out as 97 dollars a month, but I've been charged 30 dollars since opening it up (egress not included).
So basically I'm being charged 10 days worth of their service when it's only been six days. And the network egress is also not innocent either.
I'm trying to figure out what all the numbers mean, and also what the "Estimated charges" on the dashboard means. Is there some kind of hidden stat behind everything that I just didn't read about?
edit: full billing report
Comment: Hard to say without your billing report, but I'd wager something like disk/snapshot storage.
Comment: On what date did you open the instance? This bill seems to be for 8 days and 4 hours of usage.
Comment: I'm voting to close this question as off-topic because we are not Google Cloud Billing Department.
Answer: An n1-standard-4 instance in Montreal is $0.2092 per hour (see here). Your usage is for 196 hours (eight days, four hours). That gives an expected usage charge of $41.
Ignoring the ingress/egress and your sustained usage discount, you have two billing items left, $27.32 for the 4 cores and $13.73 for the 15 GiB of RAM. $27.32 plus $13.73 is $41.05, which is right on target.


Three lines are given. Find three points on these lines, one point on each line, that are vertices of an equilateral triangle

Question:
Three lines are given. Find three points on these lines, one point on each line, that are vertices of an equilateral triangle

Well if I consider a point on one line my goal would be to construct the other two points. If the lines are intersecting all at one point perpendicular to each other. Could I then use a circle to construct the other points? I'm a little unsure how to visualize this problem. Any hints would be appreciated.
Comment: Cosider cases. One case is all lines intersect at a point. Second case all lines are parallel. Last case the lines form the sides of a triangle and an equilateral triangle can be inscribed in it.
Comment: ... (continuation of @Somos) ...as is established in (https://math.stackexchange.com/questions/186432/equilateral-triangle-inscribed-in-a-triangle)
Comment: I forgot another case with two parallel lines cut by a transversal line.
Answer: Let the three lines be $r,s,t$. Let $A\in r$.

Rotate $s$ by $60^\circ$ counter-clockwise around $A$ to get $s'$;
Define $B$ as $s'\cap t$;
Define $C$ as the intersection between the perpendicular bisector of $AB$ and $s$.

$ABC$ is equilateral. Can you see why?


Floating Action Button does not raise OnClick event

Question: I have the Following layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/rlMap">
    <org.mapsforge.map.android.view.MapView
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"/>
    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/windArrow"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_gravity="top|right|end"
        android:src="@drawable/arrow"
        android:layout_alignStart="@+id/fab" />
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right|end"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/settings"
        android:clickable="true"/>
</RelativeLayout>

And the following code in the OnCreate method:
...
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG,"FAB Setting Clicked");
            Intent i = new Intent(getApplicationContext(), AppPreferences.class);
            startActivity(i);
        }
    });
...

But when I press the button nothing happens, The intent does not run, and the log is not written.
The button animation is working and every time I press the button the following log message appears :

D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN

So there seems to be some reaction.
What am I doing wrong?
Comment: Where are you setting the click listener? Inside an `Activity` or `Fragment`? Can you verify the listener is being set to the button? You can debug or print a log before/after `fab.setOnClickListener`
Comment: You can add a click event inside the xml e.g -- (android:onClick="runThis") -- and then in the Activity add -- (public void runThis(View v) { .....  }) .Try this way and see if it works
Comment: @Tasos it worked! My question is why?
Comment: The listener is being set inside a class which eventually derives from Activity. The listener is being set, I checked using a Log debug of fab.hasOnClickListeners() before and after.
Comment: I have no idea. maybe its where you placed your listener. Try inside the onCreate -- if you do have it inside onCreate try outside
Comment: Facing the same problem, setting the OnClickListener in the OnCreateView method of the MainActivityFragment.
Answer: Try this:
fab.bringToFront();

Should help.
Answer: The solution suggested by @Tasos worked:
add a click event inside the xml e.g
android:onClick="runThis"

and then in the Activity add
public void runThis(View v) { ..... }

Comment: Same problem here, I'm also interested in why it is not working.
Answer: I experienced the same problem when I failed to return the View object, but instead made another call to infalter.inflate like this:
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
/* setup onClick handler */
return inflater.inflate(R.layout.fragment_main, container, false);

The fix was replacing the return with
return rootView;

Answer: I actually found the following solution to deal with lost clicks
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    @Override
        public void onClick(View v) {
            Log.v(LOG_HEADER,"onClick");
        }
}

public class SearchFragment extends Fragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        LinearLayout ll = (LinearLayout )inflater.inflate(R.layout.fragment_search, container, false);
        ll.setOnClickListener((MainActivity)getActivity());
        return ll;
    }
}


How do I get block relationships for a content type?

Question: As part of a migration from drupal 7 to drupal 8, I currently have a rather original node display method that I'm trying to reproduce to Drupal 8, but without success.
Currently on Drupal 7, this method is filled by a custom preprocess that I try to remove in favor of views / entity reference.
Here is the procedure:
I have a node type that contains tags (field_tags), with for example the vocabulary 'news' from the 'Users terms' term. And basic content (title, body...).
I would like, via an already existing block having a field tags and value 'news', recover all the nodes with the tag 'news'.
Recap of entities I have tried:
Node:
- title
- body
- field_tags / value: 'news' (reference to "User terms")
Views name 'flow':
- display: content
- contextual filter: 'Content: Has taxonomy term ID' > 'Display all results for the specified field'
& Content: Nid
- relationsips: nothing, because I can't add a entity reference to a block
Block name 'block flow' :
- title
- field_tags / value: 'news' (reference to "User terms")
I would like when I create a block type 'block flow' with 'news' tags, get all node type that containing the 'news' tag.
I can't get it working because the views relationships don't allow me to reference the field 'field_tags' from my block (only content or taxonomy available).
We have a theme preprocess who can do that but I would like to know if there is a workaround ou any contrib module doing that.
Why I don't create a block from the view? Because in our process, we don't give access to the views of our contributors.
Answer: Finally, I got this working by creating a simple view "custom block".
Then, I created 3 relations, one for my node content, one for my content tags and last one for block tags
After that, we just need a contextual filter : Content: Has taxonomy term ID' > 'Display all results for the specified field
And that's all.


Element Modulo P expressible as Norm

Question: Let $p$ be a prime and $a\in(\mathbb{Z}/p\mathbb{Z})^*$. Can someone help me show that every $c\in \mathbb{Z}/p\mathbb{Z}$ is expressible in the form $x^2+ay^2$ for some $x,y\in \mathbb{Z}/p\mathbb{Z}$? I'm not entirely sure where to start, but could examining the ring $\mathbb{Z}[\sqrt{-a}]$ modded out by $p$ be useful? Thanks in advance.
Answer: Hint. Define the sets $S_1=\{c-x^2:x\in\mathbb Z/p\mathbb Z\}$ and $S_2=\{ay^2:y\in \mathbb Z/p\mathbb Z\}$, count the number of elements in each set and deduce $S_1\cap S_2\neq\emptyset$.

Element Modulo P expressible as Norm


Is there a documented maximum number of users you can have connected to an Office 365 user mailbox?

Question: We have a user mailbox on Office 365 that we share out to a department at our company with around 20 users. We've had some problems with the mailbox regularly updating for some users.
Utilizing a Shared Mailbox is not an option due to the size and required functionality of the mailbox (sending out emails via TLS through O365).
We're being told by our Vendor of Record that provides support (as a middleman) for Office 365 that you cannot have that many users connected to a user mailbox with Office 365 but I cannot locate any documentation to support such a claim.
Thanks in advance for any assistance.
Comment: Are the users connecting to the mailbox with the credentials for that mailbox, or are they using their own credentials and "Full Access"" rights?
Comment: They are using their own credentials and full access rights.
Comment: i am logged case with MS , will post the update shortly
Answer: I received the following feedback from Microsoft with regards to throttling in place for Office 365:

The throttling limit for attribute "RCAMaxConcurrency", which defines the number of concurrent connections allowed from Outlook, is set to 40 which translates to roughly to roughly 14 max conncections from Outlook 2007/2010/2013 clients to the mailbox.

However, Microsoft also recommended a workaround for this would be to use a Shared mailbox which would get around this problem as Shared mailboxes are not handled the same as User mailboxes on Office 365.
Hope this helps somebody else in the future!
Answer: It's not a hard limit of endpoints or users, it's about throttling policy settings. Each endpoint, whether Outlook (MAPI), or mobile (EWS typically), will use a number of connections. That number may be 1, or it may be higher. Each connection will do certain things like connect to AD, or search, or send mail, etc. When you hit a throttling limit for a type of behavior over a type of connection, future connections will be throttled.
(User vs Shared mailboxes will make no difference to O365. It's still a mailbox.)
Comment: Is this a setting that can be controlled within Office 365?
Comment: You should ask your vendor for help. This isn't something that's exposed to administrators, you'll have to work with MS for this. And it would be a good idea to formulate what actual problem you're having, because you haven't actually stated a technical problem in your question.
Comment: You're right, I should have included that in my question. The mailbox stops updating for several users for extended periods of time.


Layout da página controlada por javascript utilizando REST para o conteúdo dinâmico

Question: Estava pensando em um padrão diferente para desenvolver minha aplicação via browser. Como se trata de um ERP, preciso de uma interface rápida que não precise fazer download do HTML do servidor a todo momento para imprimir na tela do usuário o layout. A solução seria fazer toda a interface em javascript, puxando o conteúdo dinâmico via PHP REST com JSON. O servidor só seria responsável em imprimir um JSON para retornar apenas variáveis primitivas, como textos, inteiros, boolean e arrays.
Dúvidas:
1. Isso é um design pattern aceitável e profissional ou é gambiarra?
2. Existe algum framework javascript que me poupe trabalho na parte do cliente(javascript) para essa finalidade?
3. Quais pros e contras de utilizar esse design pattern?
Comment: Sim, é aceitável e está em alta. Se chama SinglePage Application ou SPA.

Existem diversos frameworks como KnockOutJs, EmberJs, AngularJs, BackboneJs que fazer o controle do DOM e a manutenção de regras MVW (Model View Whatever)
Comment: Sim, conteudo estatico seria em HTML. O Javascript só seria responsavel por fazer as requisições no servidor para pegar as informações em JSON e fazer o controle do DOM como disseste. Ficou mais fácil pesquisar agora sabendo que isso se chama SPA e com suas sugestões de frameworks.

Quanto ao javascript desabilitado, é um mal que vou ter que combater, forçar os usuários a habilitar. Na verdade, nem me preocupo com isso, já que será uma aplicação comercial/empresarial com usuários específicos e todos seriam treinados para utilizar e obviamente não iriam desabilitar o javascript.
Comment: Neste caso sim, é vantagem, como é um ERP, não há a necessidade de se preocupar com SEO, que é um problema quando se fala de requisições Ajax, o que também existe técnicas para contornar...
Comment: @GustavoPiucco não sei se já começou a fazer mas recomendo uma olhada no nodejs para fazer o backend. Tem uma performance e escalabilidade ótima, e a curva de aprendizado não é tão grande para quem já conhece de JavaScript
Comment: Ainda não comecei. Estou ciente do NodeJS, só que como estou pensando a longo prazo, como o NodeJS aparentemente saiu do forno agora, não sei qual será o futuro do desenvolvimento do mesmo, me sinto mais seguro desenvolvendo em PHP, talvez eu esteja errado.
Comment: É, para um ERP fica bom. MAS... tem que haver um compromisso muito sério com o padrão adotado. No momento em que se começar a entregar HTML dentro de um JSON abandone o barco :D
Comment: @GustavoPiucco para nós brasileiros tem pouco tempo, mas o node já tem mais de 2 anos e está sendo abraçado por inúmeras empresas de grande porte. Como você mesmo disse, como é a longo prazo, uma tecnologia que já está despontando hoje pode ser uma boa escolha.
Comment: @GustavoPiucco Faltou esclarecer algo na minha resposta? Pode adicionar um comentário que eu tentarei complementar
Comment: Não entendo qual tipo de melhoria poderia ser aproveitada, criando todo o layout em javascript, acho que para conteúdo estático, usar apenas html, garante muito mais a exibição da página, pois se o usuário estiver com javascript desabilitado, todo seu site, não será nem visualizado.
Comment: Ou angularJs, daquela pequena empresa...
Answer: MVC ou MVP ou MVVM
(Model-View-Controller / Model-View-Presenter / Model-View-ViewModel)
(A escolha depende do que se adequa melhor a você e ao que quer fazer)
Desta forma você divide as regras da aplicação em camadas.
No Model, você pode criar todas as entidades e regras de negócio principais em um WebService em qualquer linguagem ou plataforma e, a partir dele, disponibilizar o dados e interagir com sua página Web, sem existir um vínculo real entre ambos. Apenas um contrato da interface pública do Model para o FronEnd.
Vantagens da divisão em camadas
Dividir sua aplicação separando a View do código você tem diversas vantagens:

Redução do tráfego de rede
Redução da carga do servidor de aplicação
Navegação mais dinâmica e fluída
Independência entre as equipes de Front-End e Back-End que só precisam estabelecer as funções e assinaturas dos métodos que serão expostos

Frameworks
Dentre estes frameworks posso citar:
KnockOutJs

É um framework Model View ViewModel que fornece Two-Way binding entre o DOM e o ViewModel em javascript
Faz com que o DOM se atualize quando houver atualização na ViewModel e atualiza a ViewModel automaticamente quando ocorrer alteração no DOM
Tenho algumas coisas atrasadas aqui, assim que terminar complemento mais a resposta com os outros frameworks e exemplos
EmberJS

Ember.js é um framework Javascript para desenvolvimento client-side de páginas web baseado na arquitetura MVC. Permite aos criar SPA (Single Page Aplications) de forma scalável, incorporando diversos recursos além de templates auto-atualizáveis baseada no Handlebars.js
AngularJs
O AngularJs é um framework MVW (Model View Whatever) que permite que você utilize (to be continued...)

BackBoneJs


Configuration form and submission handler

Question: I am using the following code for Drupal 6.
 foreach (variable_get('cleanupeditform_formkeys', 0) as $key => $value ) {
    $form['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key] = array(
      '#type' => 'checkbox',
      '#title' => t('Hide ') . $value,
      '#default_value' => variable_get(CLEANUPEDITFORM_HIDEPREFIX . $key , 1),
    );
  }

I need to convert this code to Drupal 8.
In buildForm() I generate the form. I need to save the checkboxes values, and I am using the following code.
public function submitForm(array &$form, FormStateInterface $form_state) {
     foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: 0) as $key => $value ) {
       parent::submitForm($form,$form_state);
       $this->config('cleanupeditform.admin_settings')
         ->set('element', $form_state['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key])
         ->set('element', $form_state['cleanupedit_allow'][CLEANUPEDITFORM_ALLOWPREFIX . $key])
         ->save();
     }
     parent::submitForm($form, $form_state);
  }

Please help me to find out a solution.
Answer: There are the following errors in that code:

You call parent::submitForm($form, $form_state) inside the foreach() loop, when it should be called once, outside the loop
You keep setting element, which means you are only saving a single value
Your code is still accessing the FormStateInterface object as an array, as it was done in Drupal 7

I cannot comment about the \Drupal::state()->get('cleanupeditform_formkeys') part, except that I would probably inject the service as dependency, but I would rather use the following code.
public function submitForm(array &$form, FormStateInterface $form_state) {
  foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: []) as $key => $value ) {
    $this->config('cleanupeditform.admin_settings')
      ->set(CLEANUPEDITFORM_HIDEPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_HIDEPREFIX . $key))
      ->set(CLEANUPEDITFORM_ALLOWPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_ALLOWPREFIX . $key))
      ->save();
  }
  parent::submitForm($form, $form_state);
}


Custom preprocess_function does not fetch translated value of the content type

Question:
Drupal 7.34 core
Using custom theme from Themebrain TB Sirate
Multilingual setup works properly
Content type has both English and Russian values

English Language mode: When open/viewing a node, page-title display content type that is "Article" (English)

Russian Language mode: When open/viewing a node, page-title display content type that is "Article" (still English, must be Russian)

Question how to display Russian value of content type.
Here code from preprocess_funcion.inc of the custom theme
<code>/**
 * @file
 * Override of theme_preprocess_...
 */

function tb_sirate_preprocess_html(&$vars) {
  $current_skin = theme_get_setting('skin');
  if (isset($_COOKIE['nucleus_skin'])) {
    $current_skin = $_COOKIE['nucleus_skin'];
  }
  $vars['classes_array'][] = !empty($current_skin) ? (" " . $current_skin . "-skin") : "";
}

/**
 * Override or insert variables into the page template.
 *
 * @param array $vars
 *   An array of variables to pass to the theme template.
 */
function tb_sirate_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    if ($vars['node']->type != 'page') {
      $result = db_select('node_type', NULL, array('fetch' => PDO::FETCH_ASSOC))
        ->fields('node_type', array('name'))
        ->condition('type', $vars['node']->type)
        ->execute();
      foreach ($result as $item) {
        $vars['title'] = $item['name'];
      }
    }
  }
}

/**
 * Override or insert variables into the node template.
 *
 * @param array $vars
 *   An array of variables to pass to the theme template.
 */
function tb_sirate_preprocess_node(&$vars) {
  $vars['page'] = ($vars['type'] == 'page') ? TRUE : FALSE;
}

It seems to me that problem is here

    function tb_sirate_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    if ($vars['node']->type != 'page') {
      $result = db_select('node_type', NULL, array('fetch' => PDO::FETCH_ASSOC))
        ->fields('node_type', array('name'))
        ->condition('type', $vars['node']->type)
        ->execute();
      foreach ($result as $item) {
        $vars['title'] = $item['name'];
      }
    }
  }
}
</code>
What can I do to pull Russian value of the content type from DB?
Thanks in advance for any help!
Answer: You can confirm this by looking under the "Overview" tab of the translation interface:

If the percentage in the "Node types" for your second language is ("Norwegian Bokmål" in the image above) is 0%, the translated strings for the Node types has not been imported into the translation interface.  This means that even after you enable that language, the fallback English strings will be used.
However, it should now be possible to add these translation by hand.  Navigate to the translate tab of the translation interface, and limit search to Node types.

The strikethrough over the string with the two letters in the Languages column means that the translation is missing.  Click "edit" to add the missing translation.
This exact procedure fixed it for me as can be seen from the "Overview" tab below.  The percentage for "Node types" for "Norwegian Bokmål" in now 100%.
Comment: I can confirm that node type is translated properly. It reads Russian part appropriately. The issue still persists :-(
Answer: Here is the solution. I am glad to have it resolved
http://www.themebrain.com/question/nodes-page-title-does-not-pick-translated-value


Simulating Time-Dependent Covariate and Applying coxph Function to Estimate Association Parameters

Question: Let $T$ denote a failure time random variable drawn from a proportional hazards model with a time-invariant covariate $X\sim U(2, 7)$ and a time-varying covariate $Z(t) = kt$ for $k > 0$. Assuming the baseline hazard function is Exponentially distributed with parameter $\lambda = 1$, I can generate $200$ observations of right-censored failure time data with covariates from this model using the R code:
library(survival)
# Set proportional hazards model parameters
gamma=c(0.15,0.05)
k = 5
# Generate failure/censoring times and covariate data
failure=c(); censor=c()
obs=c(); ind=c()
time_invariant=c(); time_variant=c()

## Survival Data Simulation
for (i in 1:200){
    temp.Z=runif(1, 2, 7)
    temp.U= runif(1,0,1)

    temp.T=(1/(gamma[2]*k))*log(1+(-(log(temp.U)*gamma[2]*k)/(exp(gamma[1]*temp.Z))))

    temp.C = rexp(1, 0.5)
    temp.obs = min(temp.T,temp.C)

    ## Append empty list
    failure = append(failure, temp.T); censor = append(censor,temp.C)
    obs = append(obs,temp.obs); ind = append(ind, 1*(temp.T==temp.obs))
    time_invariant = append(time_invariant,temp.Z)
    time_variant = append(time_variant, k*temp.obs)
}

After generating the simulated data, I applied the coxph function treating the variable time_invariant as a time-invariant covariate and I estimate the gamma[1] parameter correctly.
mod = coxph(Surv(obs, ind) ~ time_invariant)
summary(mod)

I want to include the time-varying covariate time_variant into the coxph function to obtain an estimate of gamma[2]. How do I code the variable $Z(t)$ so that I can include it as a time-dependent covariate in the coxph function?
Comment: Are you familiar with the [vignette](https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf) on time-dependence in survival models? See Section 5 on "Predictable time-dependent covariates," which seems to be what you need for a time-varying covariate like your Z(t).
Comment: I have tried using the tt code but the estimates do not match with the simulation parameters. My question is how to setup the code to include a time-varying covariate of the form $Z(t) = kt$. The code I used was

 mod = coxph(Surv(obs, ind)~time_invariant + tt(time_variant), tt = function(x, t, ...) {time_variant <- x*t})

summary(mod)

The estimates that were determined were:  4.442e-02 (time_invariant) and -1.887e+01 (time_variant)
Comment: Have you tried expanding the data set yourself to use the counting process format `Surv(startTime, stopTime, event)` instead of relying on the `tt()` function? As discussed in the vignette, that also allows for more extensive post-processing of the model fit.
Comment: I have tried to include longitudinal measurements for the time-dependent covariate and included them in the "start", "stop", "event" format but the coxph functions runs into numerical errors. I have essentially the same problem as [link](https://stats.stackexchange.com/questions/313292/cox-survival-data-with-time-varying-continuous-variable-and-time-fixed-covariate?noredirect=1&lq=1) but the question of how to include the $Z(t)$ function into the coxph function was not resolved.
Comment: If $Z(t)$ is deterministic, i.e. does not change for different observations, then it's just part  of the baseline hazard. Same as a constant covariate  is just part of the intercept in a OLS
Answer: First of, the baseline hazard is not really distributed, but an arbitrary function from time to $[0, \infty)$. A Cox-Model with one time invariant covariable $x_1$ and a time variant $x_2$ can be setup with a hazard function like this:
$$
\lambda(t, x_1, x_2) = \lambda_0(t) \cdot \exp(\gamma_1x_1 + \gamma_2f(t, x_2))
$$
$\lambda_0(t)$ being the baseline hazard. From here you could find the inverse CDF of the failure times for the case specific values of $x_{1/2}$ and then use that to sample failure times efficiently or just use your CPU and simulate with tiny time-steps $\Delta$ and with probability of failure $\Delta\lambda(t, x_1, x_2)$. I have made a few choices in my model to demonstrate the algorithm better, the big one being $f(t, x_2) = \sin(2\pi t)\cdot x_2$
library(parallel)
library(survival)

gamma <- c(0.25, 0.5) # i want them a bit larger
base_hazard <- function(t){1}
loc_lambda <- function(t, x1, x2){
  base_hazard(t) * exp(gamma[1]*x1 + gamma[2] * sin(t*pi*2) * x2)
}

step_size <- 1/10^5 # very small 0.01 would be perfectly sufficient
sim_case <- function(x1, x2){
  failure <- FALSE
  t <- 0
  while(!failure){
    t <- t + step_size
    lambda_t <- loc_lambda(t, x1, x2)*step_size
    failure <- sample(c(FALSE, TRUE), size = 1, prob = c(1-lambda_t, lambda_t))
  }
  return(t)
}
sim_case(2, 3)

# setup data, n = 200 is too small for checking the algorithm
n <- 2000

dat <- data.frame(x1 = runif(n), x2 = runif(n))

# simulate with all but 2 of your CPU cores. takes about 1 minute on my machine(AMD Ryzen 5 3600)
start_time <- Sys.time()
print(start_time)
failure_times <- mcmapply(1:n, mc.cores = detectCores() - 2, FUN = function(i){
  sim_case(dat[i, "x1"], dat[i, "x2"])
})
print(Sys.time() - start_time)

censor_times <- rexp(n, 2)
dat$failure <- failure_times < censor_times
dat$time <- pmin(failure_times, censor_times)
summary(dat)
# follow the vignette https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf
vfit3 <- coxph(Surv(time, failure) ~ x1 + tt(x2),
               data=dat,
               tt = function(x, t, ...) x * sin(t*pi*2))

summary(vfit3)

We recover the parameter values of $0.25, 0.5$ reasonably well:
Call:
coxph(formula = Surv(time, failure) ~ x1 + tt(x2), data = dat,
    tt = function(x, t, ...) x * sin(t * pi * 2))

  n= 2000, number of events= 779

         coef exp(coef) se(coef)     z Pr(>|z|)
x1     0.1576    1.1707   0.1237 1.274  0.20271
tt(x2) 0.4785    1.6137   0.1808 2.646  0.00814 **

Now your question seems to imply, that you don't actually have a time variant covariate, but instead a feature that increases the hazard equally for all cases. This would be part of the baseline hazard and Cox-models explicitly try to avoid modeling the baseline hazard. I would point you towards Discrete-Time Survival, where the baseline hazard is model and can be tested:
https://www.rensvandeschoot.com/tutorials/discrete-time-survival/


Solving for trigonometric identities

Question:
Solve
$$\tan^{-1}\left(\frac{1-x}{1+x}\right)=\frac12\tan^{-1}(x)$$

I used the formula
$$2\tan^{-1}(x)=\tan^{-1}\frac{2(x)}{1-x^2}$$
and got the final answer as
$$\tan^{-1}\left(\frac{1-x}{1+x}\right)=\frac12\tan^{-1}\left(\frac{1-x^2}{2(x)}\right)$$
which is not right.
Answer: Let $\theta = \tan^{-1}\left(\dfrac{1-x}{1+x}\right) \to \tan \theta = \dfrac{1-x}{1+x} \to 2\theta = \tan^{-1}x \to x = \tan(2\theta) = \dfrac{2\tan \theta}{1-\tan^2(\theta)} = \dfrac{2\left(\dfrac{1-x}{1+x}\right)}{1-\left(\dfrac{1-x}{1+x}\right)^2}$. Can you continue?
Comment: k thx , let me try
Answer: $$\arctan \frac{1-x}{1+x}=\frac12\arctan x\implies \arctan\tan(\pi/4-\arctan(x))=\frac12\arctan x$$
So:
$$\pi/4=\frac32\arctan x\implies \arctan x=\frac{\pi}{6}\implies x=\tan(\pi/6)=1/\sqrt3$$
Comment: $$\arctan\left[\tan\left(\dfrac\pi4-\arctan x\right)\right]=\dfrac\pi4-\arctan x$$   $$\iff-\dfrac\pi2\le\dfrac\pi4-\arctan x\le\dfrac\pi2\iff\dfrac\pi2\ge\arctan x-\dfrac\pi4\ge-\dfrac\pi2$$  $$\iff\dfrac{3\pi}4\ge\arctan x\ge-\dfrac\pi4\iff x\ge-1$$
Comment: @labbhattacharjee can't get you.
Answer: Using the tangent addition formula,
$$ \tan^{-1} a + \tan^{-1}b = \tan^{-1} \frac{a+b}{1-ab}$$
let $a = 1$ and $b = -x$, so
$$ \frac{\pi}{4} - \tan^{-1} x = \tan^{-1} \frac{1-x}{1+x} = \frac{1}{2}\tan^{-1} x$$
So then $ \frac{\pi}{6} = \tan^{-1} x$ and $x = 1/\sqrt 3$.
Comment: The correct  formula has been mentioned here(http://math.stackexchange.com/questions/523625/showing-arctan-frac23-frac12-arctan-frac125) in my answer
Comment: Thanks for sharing info :)
Answer: Like my answer here,
$$2\tan^{-1}\frac{1-x}{1+x}=\tan^{-1}\dfrac{2\cdot\dfrac{1-x}{1+x}}{1-\left(\dfrac{1-x}{1+x}\right)^2}$$ if $\left(\dfrac{1-x}{1+x}\right)^2<1\iff\left(\dfrac{1-x}{1+x}\right)^2-1<0\iff-\dfrac{4x}{(1+x)^2}<0\iff x>0$
In that case, $$\tan^{-1}x=\tan^{-1}\dfrac{2\cdot\dfrac{1-x}{1+x}}{1-\left(\dfrac{1-x}{1+x}\right)^2}=\tan^{-1}\dfrac{1-x^2}{2x}$$
$$\iff x=\dfrac{1-x^2}{2x}\iff x^2=\dfrac13$$
But we need $x>0$
Comment: Thx a lot :) It helped
Comment: @MohitBhasi, What if $x<0$?

Solving for trigonometric identities


List 2 fields of a content type and group them based on one of them with views

Question: I have on coupon content type with 2 fields. One is named "Campaign Owner" and the other one "Campaign Name". One owner might have several coupons generated by the site for a campaign. So the owner will have for example 20 coupons with the same campaign name. I want to create a list of campaign names and group them with campaign owner. So the list should be something like this:
JACK(Owner Name)

Camp1
Camp2
Camp3

JOE (Owner Name)

camp4
camp5
camp6

I've tried to create this with views but what I get is not what I'm looking for. Here is it:
JACK

Camp1
Camp1
Camp1
Camp2
Camp2
Camp2

JOE

Camp4
Camp4
Camp4
Camp5
Camp5
Camp5

As you can see. It lists all the similar campaign names. But kneed to get rid of the
similar items.
How can I do such a thing?
Comment: Go to advance Query settings in view and check Distinct may gives correct result.
Comment: @KrishnaMohan No it doesn't work. They are not the same cause each row belongs to a published content with different NID. So they might be similar for us but they are not for the views.
Answer: The answer is "views distinct" module which checks the values of each row and then removes/aggregates the similar ones.


Exclude all files from folder for plato metric

Question: I'm deploy my webapp at a windows maschine (non POSIX command line) and I'm generating JS metric with Plato.
My Question is how can I exclude all files from a given folder that contains subfolders via regular expressions with plato.js.
I tried this command for excluding all minified JS Libs:
<code>$ plato -x "^js[a-zA-Z0-9-.\/]*.?js" -r -d report src/app/
</code>
All JS files of src/app/js/**/*.js are not excluded.
I test my regex with rubular: http://rubular.com/r/zbTsv1nIWY (fix underscore issue is optional)
Can somebody help me please?
Answer: Remember to escape (.) because you want to match it literally.
i dunno why have you left out the <code>_</code> (underscore) but an optional solution can be something like this :
<code>^js\/(.*)\.js$
</code>
folder name starting with js and file name ending with .js
and as you are saying another solution can be to just include the _
<code>^js[a-zA-Z0-9-\.\/_]*.?js
</code>
demo here : http://rubular.com/r/DPqnxtDB6E
Comment: Thank you for your answer. The regex looks correct and handy. I have the feeling that plato itself has a problem. So, I'm debugging plato.


Change layout of EditText on state "selected"

Question: I am trying to obtain a EditText changing it's colors and layout when the user clicks on it to type something, and I do that with a custom drawable, but the attributes android:state_enabled="true" android:state_focused="true"> don't work at all, meaning that they don't get called.
EditText:
 <EditText android:id="@+id/field_user_info" android:hint="Nome e Cognome"
        android:layout_marginTop="8dp" android:layout_marginBottom="8dp"
        android:padding="8dp" android:maxLines="1"
        android:background="@drawable/custom_account_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@color/textHint"/>

custom_account_edittext drawable:
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">

            <solid android:color="@color/account_grey_300" />
            <stroke android:width="0.8dip"
                android:color="@color/account_grey_400"/>
            <corners android:radius="2dip" />
        </shape>
    </item>
    <item android:state_enabled="true"  android:state_focused="true">
        <shape android:shape="rectangle">

            <solid android:color="@color/white" />
            <stroke android:width="1dip"
                android:color="@color/cardview_blu_color600"/>
            <corners android:radius="2dip" />
        </shape>
    </item>
</selector>

My problem is that I always visualize the default layout (the first item).
Why do the items <item android:state_enabled="true"  android:state_focused="true"> don't get activated at all?
How can I customize my TextView states?
Answer: Try this
<item android:state_enabled="true" android:state_focused="true">

EDIT:
Try this and check if the background color is changed when clicked on edittext
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item
        android:state_pressed="true"
        android:drawable="#f07c01"
        />
    <item
    android:state_enabled="true" android:state_focused="true"
        android:drawable="#c099cc00"
        />
    <item
        android:drawable="#0d91a8"
        />
</selector>

Comment: thanks I've changed it to `` but it doesn't work...
Comment: I don't know how but now it's working. It turns out that either you use the attribute `android:drawable="@color/white"` or the `` tag. Only one of them is going to work. But I don't understand how my code is now different from what I have originally done!
First trial: http://pastie.org/private/lvbmk3mbci8lwkznlrfvg

Last edit: http://pastie.org/private/lfs4uphkels0fyvgffolg
Comment: I've tried again and the order of the two changes the result! why is that?
Comment: Yes, if the item with `state_focused` and `state_enabled` is the first item, then it works, otherwise, it doesn't....It also work if there is another item containing `state_pressed` in the beginning, but it seems as if the default item must be in the end


How do I express an class literal for an Array in Java?

Question: For an ordinary class, I can write String.class.
But how do I do this for an array class, including array of primitives?
I can of course  do  as follows, whether for arrays of primitives or of objects.
(new byte[0]).getClass()
and
(new String[0]).getClass()
But is there a more direct way?
Comment: `String[].class`, `int[].class`
Comment: You may find [this](https://stackoverflow.com/questions/7011067/retrieving-array-class-name) and [this](https://stackoverflow.com/questions/13392160/about-java-get-string-class-from-string-class-what-if-string-class-is) interesting.
Answer: The correct way is using the .class.
Examples:
int[].class
Long[].class

These will do exactly what you need.


Inserting multiple data into database

Question: I am learning to use SQL Server 2008 R2, and I'm a little stuck at the INSERT option. I want to insert multiple data at once and I'm using this :
INSERT INTO Members (column1, column2, column3, column4, column5)

VALUES ('value1', 'value2', 'value3', 'value4', 'value5'),

       ('value1', 'value2', 'value3', 'value4', 'value5'),

       ('value1', 'value2', 'value3', 'value4', 'value5')

which ofc works. But let's say I have like a 1000 records that I want to insert (from another file, for e.g. Excel), how can I do that ? Any reference to where I can learn this ?
Comment: Have you read the documentation on [bulk importing data](http://msdn.microsoft.com/en-us/library/ms175937(v=sql.105).aspx)? `BULK INSERT`, `bcp.exe` and SSIS are all common solutions, depending on your requirements and preferences. There is a lot of information in the documentation and online about all of them.
Answer: Use SELECT statement to insert multiple data like:
INSERT INTO Members (column1, column2, column3, column4, column5)
SELECT 'value1', 'value2', 'value3', 'value4', 'value5'
UNION
SELECT 'value1', 'value2', 'value3', 'value4', 'value5'
UNION
SELECT 'value1', 'value2', 'value3', 'value4', 'value5'

or
INSERT INTO Members (column1, column2, column3, column4, column5)
SELECT Column1, Column2, Column3, Column4, Column5 FROM Table1

Answer: You can simply run a Export Wizard on the database. Just follow the below steps.
Step 1: Right Click on the Database
Step 2: Select Task
Step 3: Select Export Data
Step 4: Enter Data Source details   ( here you will select your Excel file )

Select Excel File as DataSource
And give the Excel file path

Step 5: Enter Destination details  ( your table name  )
Step 6: Select the tables you want to recreate.
Thats it.
Answer:
you may save your data file to CSV format file, eg C:\myData.csv
Execute the statement " LOAD DATA INFILE 'C:/myData.csv' INTO TABLE Members"

Hope this can help you:)
Answer: If you want insert values from an excel file, use the import wizard of sql server, it's the easiest. In sql server, right-click your database, point to Tasks, and then click Import Data or Export data.
(look http://msdn.microsoft.com/en-us/library/ms140052.aspx for more explaination)
Answer: From the documentation:

The maximum number of rows that can be constructed by inserting rows
  directly in the VALUES list is 1000. Error 10738 is returned if the
  number of rows exceeds 1000 in that case. To insert more than 1000
  rows, use one of the following methods:

Create multiple INSERT statements
Use a derived table
Bulk import the data by using the bcp utility or the BULK INSERT    statement

If you want to use the bcp utility this is a nice answer of how it is used : SQL Server Management Studio 2012 - Export/Import data from/to table

Inserting multiple data into database


Are complex numbers and $(x,y)$ coordinates two sides of the same coin?

Question: I'm learning that imaginary numbers are just a way of representing a rotation. So, are imaginary numbers and multiple variable numbers $(x,y,z,...)$ just two different tools for representing numbers in multiple dimensions? Or are imaginary numbers still part of the same tool where $(x,y)$ represent points on a plane, and I'm misunderstanding their utility?
So it doesn't make sense to talk about calculus with complex numbers, since calculus is a tool to deal with functions of multiple variables?
Comment: I actually like this question, I've been asking it to my self many times. However I will let the intelligent people answer :)
Comment: [This question](http://math.stackexchange.com/questions/444475/whats-the-difference-between-mathbbr2-and-the-complex-plane) may be of interest.
Comment: $(a,b)+(c,d)=(a+c,b+d)$ is in a sense natural, but $(a,b)\times (c,d)=(ac-bd,ad+bc)$ is a specific property of complex numbers
Answer:
calculus is a tool to deal with functions of multiple variables

You probably mean "multivariate calculus", because ordinary calculus deals with single variables just fine.

There are several valid ways of looking at the complex numbers. One of the ways is to se $\mathbb C$ (the set of all complex numbers) as a vector space over $\mathbb R$. In that case, yes, you can look at $\mathbb C$ the same way as $\mathbb R^2$.
But this view misses two important points, one "positive" one not:

Plus : $\mathbb C$ is much more than just $\mathbb R^2$. Because you can multiply and divide complex numbers in a particular way, the complex numbers form what is called a field, making them very useful for all sorts of things. Furthermore, in complex numbers, you can define a complex derivative of a function similar to that in the real numbers, but having much nicer properties (see holomorphic functions). This, along with some other nice properties, is the reason that there is an entire subfield of analysis entirely devoted to functions of complex variables (complex analysis) So, you could say that $\mathbb C$ is a very rich version of $\mathbb R^2$.
Minus: This is only true for $2$. You cannot "enrich" $\mathbb R^3$ (this is a very complicated mathematical result called the Frobenius theorem) in a similar way, and you can only partially do it with $\mathbb R^4$ (see quaternions).
Comment: Great answer, thank you. That's exactly what I was looking for.


For which $p, q$ exists $C > 0$ with $||f||_p \leq C ||f||_q$ for all $f \in C([0,1])$?

Question: I want to find out for which $p, q$ exists $C > 0$ with $||f||_p \leq C ||f||_q$ for all $f \in C([0,1]), p \in \mathbb{R}_{\geq 1} \cup \{\infty\}$. I first let $p,q \geq 1$ and I looked at the case where $q > p$.
I defined $\tilde{f} := |f|^p$ and $\tilde{p} := \frac{q}{p}$, $f \in C([0,1])$ of course. Also, I let $g(x) = 1$ and applied Hölder's inequality:
$$||\tilde{f} \cdot g||_1 \leq ||\tilde{f}||_\tilde{p} \cdot ||g||_\tilde{q}$$
where of course $||g||_\tilde{q} = 1$.
$$\implies \int_0^1 |f|^p \mathrm dx \leq \left ( \int_0^1 |f|^q \mathrm dx \right )^\frac{p}{q} \iff ||f||_p \leq ||f||_q \cdot C \;\; \forall C \geq 1$$
So my solution is, that for $q > p \geq 1$, there always exists $C > 0$ such that the inequality holds good. Now, before I look at $p > q$, I wanted to know whether my solution is correct. It doesn't seem to be complete to me, as there might also exist $C \in (0,1)$ such that the inequality holds good. Am I wrong? If not, how can I find out for which $p$ and $q$ there exists a $C \in (0,1)$?
Thanks in advance for any answers...
Answer: You have proved what you set out to: if $q > p \ge 1$ there exists $C > 0$ (namely, $C=1$) such that $||f||_p \le C ||f||_q$ for all $f \in C([0,1])$.
Note you are not trying to prove that $||f||_p \le C ||f||_q$ for all $C > 0$.  This is easily seen to be false.
You might ask whether this result is sharp; whether there exists a number $0 < C < 1$ which could work.  To find out, consider $f=1$.
Comment: Thanks a lot for this answer. I indeed haven't considered the case $f=1$.
Answer: Your argument seems to be correct. It shows that indeed $\Vert f\Vert_{p} \leq \Vert f\Vert_{q}$ for $1 \leq p \leq q \lt \infty$.
Instead of using Hölder's inequality, you could also argue with Jensen's inequality (which is often used in the proofs of Hölder's inequality) as follows: For $p \leq q$ the function $\varphi(x) = x^{q/p}$ is convex, hence $\left(\int |f|^p \right)^{q/p} = \varphi\left(\int |f|^p\right) \leq \int \varphi(|f|^p) = \int |f|^{q}$ and extracting $q$th roots on both sides gives the desired $\Vert f \Vert_{p} \leq \Vert f \Vert_{q}$ for $p \leq q \lt \infty$. The case $q = \infty$ needs to be dealt with separately in this argument and I leave this to you.
To see that $C = 1$ is the best possible constant simply take $f$ to be the constant function $f = 1$, which has $\Vert f \Vert_{p} = 1$ for all $p$, so there can't be a constant $C \lt 1$.
Comment: You say my argument shows the inequality for $1 \leq p \leq q < \infty$. But in my question, I also allow $p = \infty$. What exactly changes in that case?
Comment: @Huy: The case $q = \infty$ does not work as written because you'd integrate $|f|^{\infty}$. The easiest way to remedy this is to replace $f$ by $g = f/\Vert f\Vert_{\infty}$ (assuming $f \neq 0$ of course). Then observe that $\Vert g\Vert_{p} \leq 1$ and use that the $p$-norm is homogeneous, so $\Vert f\Vert_{p} \leq \Vert f\Vert_{\infty}$ by multiplying the last inequality by $\Vert f\Vert_{\infty}$.


how pagination work with sorting and search function

Question: I am facing problem in pagination, searching and sorting function.
It function well if dint combine all with pagination. Once I sorting, the result did not change at every page which mean only will change in current page. For example, now i am at page 2 ,then i sorting,the result in page 2 have change due to what I sort by.However, the other page did not change , they all still by default.May I know what is going wrong. appreciate with your help.
<?php

include('db_connection.php');

$sql = "SELECT COUNT(*) FROM product";

$r = mysql_fetch_array(mysql_query($sql));
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 2;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if

// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$sOrder = "ORDER BY  product_id  ASC ";

if(isset($_POST["submit"]))
{
    $sort = $_POST["sort"];
        if($sort == "latest")
        {
            $sOrder = "ORDER BY date_update DESC ";
        }
        else if ($sort == "lp")
        {
            $sOrder =  "ORDER BY  pro_price ASC";
        }
        else if ($sort == "hp")
        {
           $sOrder = "ORDER BY  pro_price DESC" ;
        }

        else if ($sort == "AZ")
        {
             $sOrder =  "ORDER BY pro_name ASC";
        }

        else if ($sort == "ZA")
        {
             $sOrder =  "ORDER BY pro_name DESC";
        }

        else
        {
             $sOrder = " ";
        }

if ( isset($_POST['sSearch']) && $_POST['sSearch'] != "" )
{
    $search=mysql_real_escape_string( $_POST['sSearch'] );
    $sWhere = " where pro_name LIKE '%".mysql_real_escape_string(           $_POST['sSearch'] )."%' " ;
    }
else{
    $sWhere = " ";
}

$currentpage = 1;
}
?>

<form method = "POST">
 Sort by
 <select name ="sort">
 <option value="all" checked>All</option>
 <option value="latest">Latest item</option>
<option value="lp">Lowest Price first</option>
<option value="hp">Highest Price first</option>
<option value="AZ">Alphabets A-Z</option>
<option value="ZA">Alphabets Z-A</option>
</select>

<input type="text" name="sSearch" />
<input type="submit" name="submit" value="submit">
</form>
<?php

// get the info from the db
$sql = "SELECT * FROM product $sWhere $sOrder LIMIT $offset, $rowsperpage";
$result = mysql_query($sql) ;
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
$pid = $list['product_id'];
?>

<a href="proDetails.php?pid=<?php echo $pid ?>" class="product-image">
<img src="<?php echo "product/".$list['pro_photo']; ?>" style="max-height:140px;max-    width:140px" />
<?php echo "
".htmlspecialchars($list['pro_name']); ?>

<?php echo "
 RM ".$list['pro_price']; ?>

<form name = "btn" method = "POST" action="" >
<input type="hidden" name="product_id" value="<?php echo $pid ?>"/>
<input type="number" name="qty" min="1" max="30" value="1" size="30" />

<input type="submit" name="add" value="Add to Cart" class="add-to-cart" />

</form>

<?php
    }

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " << ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " < ";
} // end if

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
  // if we're on current page...
  if ($x == $currentpage) {
     // 'highlight' it but don't make a link
     echo " [$x] ";
  // if not current page...
  } else {
     // make it a link
     echo " $x ";
  } // end else
} // end if
} // end for

// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " > ";
// echo forward link for lastpage
echo " >> ";
} // end if
/****** end build pagination links ******/
?>

Comment: First search and sort, then paginate. Otherwise it happens what happens to you. And there is no reason to use `$_SERVER['PHP_SELF']` in your script, instead just use `<a href='?current...`. And don't forget to pass sort and search parameters per get parameters as well, otherwise they are lost (you're missing that, doing search and sort first, then pagination and forgetting about search and sort).
Answer: In the first line you are retrieving ALL database records count. Therefore your $numrows and then $totalpages is always wrong and equal to rows retrieved for only sorting without any search.
To do real counting you should 1st build the search query.
EXAMPLE:
$querypart = ' from table where ...... order by ....';
$countQuery = 'select count(*) '.$querypart;
$query = 'select * '.$querypart;

Now if you execute the $countQuery you will get row count for given search and sort. and for executing $query you will get the rows.
of course you should add ad the end of $query .= ' limit '.($page*$onPage).','.$onPage'; so you will retrieve only required page of rows instead of everyone.
Comment: Your meaning is replace $sql = "SELECT COUNT(*) FROM product "; to
$sql = "SELECT COUNT(*) FROM product $sWhere $sOrder"; ,rite?? i hv try but it didn't work. I think may be is something wrong at if(isset($_POST["submit"])).
Comment: Also the pagination query should be not at the beggning but when you already know what to search for.
As for the links for next/prev page - you should add to them search query and sort order. As when you create them they just tells the page but without search restrains at all.


"document" pode ser acessado em arquivo Javascript separado do HTML?

Question: tenho um HTML com um arquivo Javascript vinculado. No Javascript eu tento acessar um elemento desse HTML através de document.getElementById("meuId") e está retornando Null.
Isso deveria acontecer?
No Javascript:
const formCadNot = document.getElementById("cadastrar-noticia")

No HTML:

...

 <form class="formulario" id="cadastrar-noticia" action="cadastraNoticia">
...

Obs: o caminho do script em "src" está correto. Dentro da pasta onde meu HTML está tem uma pasta "js" co o arquivo cadastrarNoticia.js
Comment: depende, onde tentou fazer isso? já havia carregado o documento html? tentou colocar o script no final do arquivo html?
Comment: @LucasPletsch Utilize o evento `window.onload` para executar o código após o carregamento da página.
Comment: isso acontece pq o documento ainda não foi carregado e já tentou acessar um elemento que ainda não estava do `document`. Coloque seu código dentro de um bloco que execute quando o documento estiver todo carregado, assim por exemplo: `document.addEventListener("DOMContentLoaded", function(){   seu código aqui });`
Comment: leia mais aqui: https://developer.mozilla.org/pt-BR/docs/Web/Events/DOMContentLoaded
se quiser, posso postar uma resposta comentando, mas acredito que deva ter algo assim já aqui
Comment: Eu carreguei o script já no head do html. Ses eu coloco o script direto no HTML ele funciona. Mas eu quero ele num arquivo separado. Vai ficar muito script no index.html
Comment: O valor de `formCadNot` será `NULL` ... pois o script foi disparado antes do elemento ser renderizado, só mudando o comportamento quando usado o atributo `defer=""` na tag `SCRIPT`. Pode-se usar o `window.onload`, ou `DOMContentLoaded` (este é semelhante ao defer pois não espera as imagens e nem outros recursos externos, apenas o documento), linkei no topo da sua pergunta tudo o que precisa saber sobre isto.
Comment: @RicardoPontual a tua dica resolveu melhor meu problema. Se quiser postar como solução, eu marco ela como solucionado daí.
Answer: O problema é que você está carregando o seu script antes de carregar o elemento com o seu id. Sendo assim, no script você tentar obter um elemento que não existe.
A solução para este problema é importar o script abaixo do elemento ou então, criar uma função para ser chamada pelo evento onload quando a página for carregada.
Veja o exemplo abaixo:

function setColor() {
    const div = document.getElementById("myDiv");
    div.style.color = "#f00";
    div.innerText = "Texto colorido com o Javascript.";
}

        Texto não colorido.


How to trace queries to oauth2 server with Spring Security?

Question: How I can enable logs to see actual http queries between my Spring Boot app verifying the tokens and the oauth2 server?
spring:
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuer-uri: https://myhost/idm-services/auth/realms/myrealm
        registration:
          keycloak:
            client-id: myclientid

logging:
  level:
    org:
      springframework:
        web:
          filter:
            CommonsRequestLoggingFilter: DEBUG
        security:
            oauth2: TRACE

I have this enabled, but I don't see any actual logs to oauth2.
    @Override
    protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .anyRequest().authenticated().and()
.oauth2Login().userInfoEndpoint().oidcUserService(this.oidcUserService());
    }

@Bean
public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
    final OidcUserService delegate = new OidcUserService();

    return (userRequest) -> {
        OidcUser oidcUser = delegate.loadUser(userRequest);
        log.debug("User "+oidcUser.toString());
        log.debug("UserInfo "+oidcUser.getUserInfo().toString());
        log.debug("UserClaims "+oidcUser.getClaims().toString());
        log.debug("UserToken "+oidcUser.getIdToken().toString());
        final Map<String, Object> claims = oidcUser.getClaims();
        final JSONArray groups = (JSONArray) claims.get("org_access");

        final Set<GrantedAuthority> mappedAuthorities = groups.stream()
                .map(role -> new SimpleGrantedAuthority(""+role))
                .collect(Collectors.toSet());

        return new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
    };
}

there is the security configuration. I'd like to debug the token info transformation in oidcUserService, but the debug lines are not hit during the debug.
Comment: Have you tried enabling `DEBUG` or `TRACE` logs on the package `org.springframework.security.oauth2`
Comment: also log the webclient package
Comment: yes, that's on my logging settings now
Comment: @Toerktumlare how to enable that logging, what packages?
Comment: you check the api and the package says right there at the top https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html
Answer: No way to trace in org.springframework.security.oauth2.server.resource.authentication
There are just no logging entries there. The only known stuff is to put all logging to trace, then you will see for example HttpConnection calls to ouath servers, that let you clarify what is going on. It is impossible to trace the tokens and data transmitted, so on the stage where you have no option to debug through the remote port, you have no option to understand what was the problem.


How to test an extra small sample is from discrete distribution?

Question: My sample size is less than 7. The discrete distribution has 5 values, skewed, bell-shaped. How to test that the sample is from this distribution?
Comment: You can formulate the exact distribution based on all potential permutations and assigning them a probability based on your arbitrary PMF. See [my prior question](http://stats.stackexchange.com/a/74647/1036) for an example. In my paper with 7 bins (for days of the week) there is actually reasonable power for several plausible alternative hypotheses (i.e. limiting the probability to a few of the bins).
Comment: With such small sample size - with consequent low power against general alternatives - you will do better to focus on restricting the alternatives as far as possible. Are there particular alternatives you care most about detecting? (It's best to consider such issues before seeing the actual sample values.)
Comment: You will most likely have *very* little power. Can you say more about your data, the distribution in question, and the manner of deviation from the distribution that you care about detecting?
Comment: The distribution PMF is [0.03 0.12 0.6 0.2 0.05] for values [1:5]. I just want to see whether the sample is from this distribution. E.g. what is probability that a sample [3 3 3] is from this distribution.
Comment: @Glen_b, the alternative would be that my sample is nor from the theoretical distribution. My application is for performance assessment. I'm rating a group of students, and want to show that the ratings are consistent with a suggested distribution.
Comment: @Aksakal - you need to be more specific about the alternative process to calculate its power. For instance, if you want to distinguish between `[0.03 0.12 0.6 0.2 0.05]` and `[0.03 0.12 0.61 0.19 0.05]` you will need a large sample, and it would be a silly test for only three observations (in which the power will be about equal to the Type I error rate - what I consider a silly test). For the potential alternative of each bin having equal probability, `[0.2 0.2 0.2 0.2 0.2]` the power with only 3 observations is not too bad at `0.5` as I show in my answer.
Comment: @AndyW, my sample size is very small, less than 10. The theoretical distribution is given.
Answer: In my paper I linked to previously I provided a link to SPSS code to accomplish this, but I took some time to write up some functions in R to accomplish the same task for illustration. (The only external library needed is partitions.)
So here are a few functions to calculate the permutations (which are IMO the hardest part), then calculate the exact probability of each permutation, and then calculate the null distribution for the $\chi^2$ statistic.
#functions used in ExactProb
#Minimalist chi square, default equal probability for each bin
chiStat <- function(v,p=rep(1/length(v),length(v))){sum(((v - sum(v)*p)^2)/(sum(v)*p))}
#multinomial prob based on set of probabilities, defaults to equal probabilities
exactMult <- function(v,p=rep(1/length(v),length(v))){
    n <- factorial(sum(v))
    d <- prod(factorial(v))
    p <- prod(p^v)
    return( (n/d)*p )
}

#This generates all the permutations given n number of balls in m bins and
#then calculates the exact probability according to the multinomial
#distribution and the CDF of the chi-square statistic
exactProb <- function(n,m,p=rep(1/m,m)){
  library(partitions)
  AllDat <- t(compositions(n,m))
  ExactProb <- apply(AllDat,1,exactMult,p=p)
  chiStat <- function(v,p){sum(((v - sum(v)*p)^2)/(sum(v)*p))}
  Chi <- apply(AllDat,1,chiStat,p=p)
  #order according to chi-stat
  MyData <- data.frame(as.matrix(AllDat),ExactProb, Chi)[order(Chi),]
  MyData$cumprob <- cumsum(MyData$ExactProb)
  return(MyData)
}

#My wrapping all up in a global function to return items in list
#given the initial data
SmallSampChi <- function(d,p=rep(1/length(d),length(d))){
  n <- sum(d)
  m <- length(d)
  cdf <- exactProb(n=n,m=m,p=p)  #generate exact probability
  chiSamp <- chiStat(d,p)        #Chi stat for sample
  #p-value to the right of the test statistic
  pvalue <- sum(cdf[cdf[,'Chi'] >= chiSamp,'ExactProb'])
  #return object
  t <- list(cdf,p,d,chiSamp,pvalue)
  names(t) <- c("CDF","probabilities","data","Chi-Square Statistic","p-value")
  return(t)
}

So given your data in N balls in M bins format, we can use the SmallSampChi function to return the permutations and the p-value for your particular data set and the null probabilities listed.
#now with an example dataset, three events all on the third day
d <- c(0,0,3,0,0)              #format N observations in M bins, 3 in third bin
p <- c(0.03,0.12,0.6,0.2,0.05) #arbitrary PMF in comments
t <- SmallSampChi(d=d,p=p)

Here the exact probability of obtaining three values for the third bin is simply 0.6^3 = 0.216 - not a particularly rare occurrence, but for a general testing procedure this calculates the right tailed p-value for the $\chi^2$ statistic. (There is basically no power for small sample sizes to see if the left tail is too close to what you would expect.)
There actually are quite a few different combinations that would allow one to reject the null at an alpha level of .05, as can be seen by plotting the CDF of the exact null distribution.
plot(t$CDF$Chi,t$CDF$cumprob,type='s',xlab='Chi-Square value',ylab='Exact CDF')
abline(v=t$'Chi-Square Statistic',col='#FF000099')

We can subsequently look at the potential permutations in which one could reject the null given your arbitrary PMF. (Ignore the numbers on the left, they are just the initial row names of the permutations before sorting.)
a <- .05
t$CDF[t$CDF[,'cumprob'] > (1-a),1:5]
#   X1 X2 X3 X4 X5
#6   1  1  1  0  0
#20  0  0  0  3  0
#12  1  1  0  1  0
#17  1  0  0  2  0
#23  0  2  0  0  1
#24  1  0  1  0  1
#27  1  0  0  1  1
#22  1  1  0  0  1
#3   1  2  0  0  0
#4   0  3  0  0  0
#33  0  0  1  0  2
#34  0  0  0  1  2
#32  0  1  0  0  2
#31  1  0  0  0  2
#5   2  0  1  0  0
#11  2  0  0  1  0
#2   2  1  0  0  0
#21  2  0  0  0  1
#35  0  0  0  0  3
#1   3  0  0  0  0

Mine and Glen_b's comments are not in contradiction - the power of this test will depend on how wrong your arbitrary PMF is. You will have more power especially if the bins in which you assign a small probability to, bins 1, 2 and 5, end up having a large probability or if bin 3 actually has a much smaller probability.
To calculate the power, simply calculate the exact probability for your alternative process, and then see add up the probability of drawing those samples under the null process that reject the null. Here is an example if the bins actually have equal probability for your example:
p_alt <- rep(1/5,5)
t$CDF$AltProb <- apply(as.matrix(t$CDF[,1:length(p_alt)]),1,exactMult,p=p_alt)
sum(t$CDF[t$CDF[,'cumprob'] > (1-a),'AltProb']) #power of alt
#[1] 0.536

I wouldn't consider 0.536 too shabby with only three observations. It will take more experimentation though to see whether combining bins is a better approach.
Comment: Does this work asymptotically? If my sample is (3,12,60,20,5) - what would be p-value in your approach?
Comment: This is the exact distribution, so it works for all sample sizes and does not rely on asymptotic properties. It would be possible to construct the exact distribution in the `(3,12,60,20,5)` case (it generates just shy of 4.6 million permutations) but is probably unnecessary. The exact CDF for the $\chi^2$ distribution is stochastic dominant over the asymptotic one, so using the asymptotic distribution only increases Type 2 errors, and those errors grow smaller with larger sample sizes.
Comment: The $\chi^2$ value in your `(3,12,60,20,5)` case would be equal to $0$ (as the observed equals the expected in each bin), so the right tailed p-value would be $1$. (With that large of sample you can test the left tailed part of the distribution if you cared to.)
Comment: Actually not quite exactly 1, as the probability of obtaining that particular outcome is `0.0005153454`, so it would be technically just under 1 for the exact distribution.
Comment: +1 Combining bins is of course a particular subset of my suggestion of restricting the alternatives... which the OP refused point blank to consider. Sometimes you end up stuck with a less palatable restriction of the alternatives than the ones you could freely choose.


Google maps won't load - Android

Question: The current error i'm getting is: Error using newLatLngBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions.
I'm going to assume I'm getting this error because the layout has not been loaded yet, how can I rectify this issue within my code?
    import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private LatLngBounds AUSTRALIA = new LatLngBounds(
            new LatLng(-44, 113), new LatLng(-10, 154));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     *

     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     *

     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     *

     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(AUSTRALIA, 0));
    }

}

The line: mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(AUSTRALIA, 0)); in the SetUpMap(); Method. Is causing this issue by the way, and as I'm trying to use google's API V2 documentation do I need to use a callback on Google maps after the map has loaded or a separate method to initialise after a certain time period?
Comment: Please check this question : [moveCamera with CameraUpdateFactory.newLatLngBounds crashes][1]

  [1]: http://stackoverflow.com/questions/13692579/movecamera-with-cameraupdatefactory-newlatlngbounds-crashes
Answer: Looks like your map is not ready.
You can use MapLoadedCallBack;
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
  @Override
  public void onMapLoaded() {
      map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 30));
  }
});

and also you can you a prier event to this that is.
 map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition arg0) {
        map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 30));
  }
});

Comment: Okay so where would I change MapLoadedCallBack within my Activity? I tried implementing both solutions but I keep on getting weird errors. For example where does map.SetOnMapLoadedCallback above the method go? Or does that stay in the same spot just above onMapLoaded method?
Comment: I stays in the same spot it just gives callback that is invoked when this map has finished rendering.

Google maps won't load - Android


Can someone explain induced homomorphism to me in the context of simplicial homology?

Question: I have two simplicial complexes A and B, and A is a subcomplex of B. We know that there is an inclusion map from A to B, and I understand how to get the simplicial homology groups of each individual complex, but I am interested in the image of induced homorphism between the homology groups. Can someone explain to me what this is and how to compute it?
Thanks!
Answer: An element $\alpha\in H_*(A)$ of a homology group of $A$ is an equivalence class of linear combinations of simplices of $A$ —pick a representative of that class and call it $a$. Now $a$ is a linear combination of simplices of $A$, and since $A$ is a subcomplex of $B$, we can just as well see $a$ as a linear combination of simplices of $B$. In fact, viewed in this way it is a cycle, and therefore it represents an element $\beta\in H_*(B)$. It is not difficult to see that this element depends only on $\alpha$ and not on the particular representative $a$ we picked, so in this way we get a function $H_*(A)\to H_*(B)$ which maps each $\alpha$ to the corresponding $\beta$. This is the induced map, and this description makes it clear how to compute it (in principle).
Now, given an actual simplicial complex $A$, it is very rare that we compute $H_*(A)$ by actually writing its elements as homology classes of cycles: we do all sort of elaborate tricks, starting from the various long exact sequences to the more elaborate spectral sequences to invoking all sort of weird structure, to avoid as much as possible doing that. So in an actual concrete situation it is rare that we know actual representatives of homology classes. If that is the case, then of course the above description of the induced map is not going to be of any help in computing it! Each such situation has to be handled in a special way, depending on how the homology groups were determined, what information exactly is available, and so on.


Limit of Ratio Test Is $0$ (Convergence or Divergence?)

Question: I have to check to see if the sum of the series of the function $\frac{x^n}{n!}$ converges or diverges.
I decided to use the ratio test where I took the limit as $n$ approaches infinity of the ratio between a term ($a_n$) and its previous term ($a_{n-1})$. The limit I get is $0$. I know that if the limit approaches a value less than $1$, then I can say that the series converges. But here although $0 < 1$, I'm not sure if approaching a ratio of $0$ between terms will prove the function converges.
Answer: You have shown that the limit of the ratio is $0$ for any $x$, so we can say that the function converges for all $x$ by the ratio test. (This is the exponential function.)


Solaris x86: Non working keys on keyboard (<, >, #, |)

Question: I have a new installation of Solaris 10 10/09 on x86 hardware. The attached keyboard has a normal German layout. The system is configured accordingly by 'kbd -s'.
The generic keys (letter, number, umlaut) work fine. Unfortunately some keys like <, >,  |  or  # do not. They produce no output on the text console at all.
I tried PS/2 and USB keyboards. I cannot test it under X11 as it is currently not working.
Answer: Have you tried to edit /boot/solaris/bootenv.rc ?
Change the keyboard line to "setprop keyboard-layout 'German'".


read -e removes the whole line

Question: I'm using Bash for my script with read command to input last name and first name. Last name and first name descriptions are on the same line in the output. Now having a -e parameter in read can perform delete with backspace key, however, all characters along this line will be removed when performing the delete. Is there any way to prevent this?
#!/bin/bash
clear
tput cup 0 25
echo -n "First Name: JOHN"
tput cup 0 0
echo -n "Last Name: " $lastname
read -e -n10 lastname

Comment: It's not clear what you are asking. If you want to read two values from a single line, use two variables: `read -r firstname lastname` (where `-r` is basically always a good idea unless you specifically require the odd logacy behavior around backslashes).
Comment: I avoid using -r parameter because it cannot limit the characters you input. In my case I use -n10 to do that to limit to 10 characters only. Now, given the First Name: JOHN as displayed in the console as output along with Last Name: $lastname on the same line, the First Name: JOHN will be removed when performing $lastname backspace delete.
Comment: Which features of [Readline](https://www.gnu.org/software/bash/manual/html_node/Command-Line-Editing.html) do you utilize here?
Comment: @Armali I did not set anything with Readline command-line editing which I believe it is using the default, Emacs like editor but after reading I've tried adding set -o vi in the script but still the same outcome.
Comment: Is it possible to start editing the line within the declared number of characters? Let say -n10 and backspace will start at 10nth character moving to left until 1st and not the whole single-line?
Answer:
Is it possible to start editing the line within the declared number of characters?

read -e does this if you add the option -i, provided that the current variable value's length is within the declared number of characters; e. g.:
read -ei"$lastname" -n10 lastname

Let say -n10 and backspace will start at 10nth character moving to left until 1st and not the whole single-line?

The cursor already does not move back beyond its position at the beginning of input in all cases I see presently.
But as the behavior can depend on e. g. shell version and terminal capabilities, you might prefer something like
newname=`dialog --max-input 10 \
                --inputbox "First Name: JOHN\nLast Name: " 0 0 "$lastname" \
         2>&1 >/dev/tty` && lastname="$newname"; clear

Comment: Thank you @Armali for your response however as tried, the outcome is just the same as ``read -n10 lastname``.
Comment: As additional info, I'm using bash-4.4.19-12.el8.aarch64 in CentOS 8.
Comment: Does _the outcome is just the same_ mean that even with `-ei"$lastname"` the cursor is not positioned after the current `$lastname`'s last character?

read -e removes the whole line


Python ssh user validation

Question: 4:15 PM (3 minutes ago)
Hello,
Im wondering if there is a way without using send_pexpect to validate a host. I have hundreds of IPs where i need to validate if my tacacs username is valid and if not then to expect  a comment. The issue im running is that im unable to validate the expect was due to my credentials or the host is not up.
i=0
while i

<code>    try:
            conn = SSH2(verify_fingerprint = False)
            conn.connect(allips)
            conn.login(usuario)
            adding = allips, "goods"
            print adding
            lista_buena.append(allips)
            #time.sleep(1)

    except:

            adding2 = allips,"NOT GOOD"
            print adding2
            lista_mala.append(adding2)
    i += 1
</code>
Thanks,
Answer: There's a great answer posted by silvado
The code referenced is very similar to what you're trying to do. They give a great example using the paramiko.SSHClient library.
https://stackoverflow.com/questions/14236346/elegant-way-to-test-ssh-availability
If that doesn't work, there's also the option to use subprocess + OpenSSH:
https://gist.github.com/bortzmeyer/1284249
You may wish to adjust timers and except handling to improve performance. Serial code like this is great if you're only doing a few hundred nodes but when you get up in the 10K or higher I'd recommend using parallel-ssh.
Just my $.02 (^_^) Good luck!
Comment: Alternatively you can do the following:

       try:
                conn = Telnet(logfile = logfiles, verify_fingerprint = False)
                conn.connect(allips)
                try:
                        conn.login(usuario)
                        print "SUCCESS: " + allips
                except:
                        print "Not Priviledge: " , allips
Answer: Alternatively you can use:
<code>    try:
            conn = Telnet(logfile = logfiles, verify_fingerprint = False)
            conn.connect(allips)
            try:
                    conn.login(usuario)
                    print "SUCCESS: " + allips
                    filename.write('SUCCESS  ' + allips)
                    filename.write("\n")
                    filename.write("************ \n")
                    time.sleep(2)
            except:
                    print "Not Priviledge: " , allips
                    filename.write('Not Priviledge  ' + allips)
                    filename.write(" \n")
                    filename.write("************ \n")
    except:
            #print allips + "NO HOST"
            print "Not Enabled: ", allips
            filename.write('Not Priviledge  ' + allips)
            filename.write(" \n")
            filename.write("************ \n")
            filename.close()
            time.sleep(2)
</code>

Python ssh user validation


How to store user information

Question: I want to know that when we sign up for social networks, how and where does the network store the data and how does it compare the information each time we log in.
Please answer!
Comment: You are going to have to read a lot about computer security in order to know how login procedure is taking place in a widely use website. Hint: The actual user's password is not stored anywhere in the server.
Answer: Most widely used web-sites (that require log-in) use some variation of Secure Remote Password Protocol (SRP) in order to authenticate a user.
Basic answer:
The passwords themselves are kept nowhere on the server. Instead a salt and some number that was generated from the password and salt is kept. This number is actually the "secret password". But the user cannot send it directly, otherwise some attacks (like man in the middle) can occur, instead - there is a routine including various communication steps that allows the server to authenticate the user and the user to authenticate the server without ever revealing the real password.
Detailed explanation:
On account creation:

The user chooses a password (pwd), and a salt (denote s) is also
randomly generated.
The user then calculates H(d,pwd) - where H is a predefined hash
function.
Then v = g^x mod p is calculated, where p is some prime number.
The user sends to the server the values v and s - and they are
stored in the password file. The 'secret' in here is the v
password, the salt (s) is there to prevent dictionary attacks
on the system if the passwords file was exposed.

On authentication (login):

The user sends the server the user name.
The server replies with the salt
The user is then generating using some random number a the value: A=(v^x)^a, and sends it to the server. (v is the number calculated and sent to the server based on the password during account creation).
The server is calculating B=v+g^b (where b is some random number), and sends it to the user along with u, which is some random number.
The user is then calculating S=(B-v)^(a+ux), K=H(S), M1=H(A,B,K), and sends M1 to the server.
The server then verifies M1, and sends the user M2 = H(A,M1,K).
The user then verifies the value of M2, and effectively ensures he is indeed speaking with M2.

During the entire process - the password (or v) is never explicitly sent over the web.

The non "secret" data can be stored in various ways, depending on the nature of the social network and the users' behavior. A common way to do it is using relational data base, such as SQL.

How to store user information


Continuous dependence on initial conditions: why $\|y(t)-z(t)\|\leq\delta+L\int_{t_0}^{t}\|y(x)-z(x)\|dx$?

Question:
Let $D\subset[a,b]\times\mathbb{R}^n$ open, $f:D\rightarrow\mathbb{R^n}$ continuous and locally lipschitz-continuous w.r.t $y$ and let $(t_0,y_0)\in D$.
  If the solution of
$y'(t)=f(t,y(t)),\hspace{1cm}   y(t_0)=y_0\in\mathbb{R}^n$
f.a $t\in [a,b]$ exists, then f.a $\varepsilon>0$ there is >$\delta=\delta(\varepsilon)>0$, such that:
$(i)$ If $\|y_0-z_0\|<\delta$ then there exists also the solution of
$z'(t)=f(t,z(t)),\hspace{1cm}z(t_0)=z_0\in\mathbb{R}^n$
  for $t\in[a,b]$

Proof
Since $D$ is open there exists $\bar{\delta}>0$ and a compact set $K=\{(t,z(t)):t\in[a,b],\|y(t)-z(t)\|\leq\bar{\delta}\}\subset D$. f is lipschitz continuous w.r.t $y$ on $K$ with lipschitz constant $L$. Let $\delta<\bar{\delta}$ and $\|y_0-z_0\|<\delta$. Then for all $t_0,t\in [a,b]$ it holds that
$\|y(t)-z(t)\|\leq\delta+L\int_{t_0}^{t}\|y(x)-z(x)\|dx$?
But why? I can't really see where the integral is comming from.
Comment: You mean ${\cal D}\supset [a,b]\times \Bbb R^n$ as open superset, else finding solutions on $[a,b]$ with no regard to any restrictions to $\cal D$ makes no sense.
Answer: $y(t)-z(t)=y(t_0)-z(t_0)+\int_{t_0}^{t} (y'(s)-z'(s))\, ds$ so $\|y(t)-z(t)\|\leq \|y(t_0)-z(t_0)\|+\int_{t_0}^{t} \|(f(s,y(s))-f(s,z(s)))\|\, ds$. Now apply Lipschitz condition.


Randomly choose between numbers that yields a specific amount of binary 1's

Question: I want to randomly choose between any decimal numbers that - when converted to binary numbers - will produce the same amount of binary 1's within a total of 16 bits. It doesn't matter which bits that are 1's as long as i can randomly choose from all of the variations.
For example, if i wanted the result to be one 1, and 15 0's within the 16 bits, i would have to randomly pick any of the numbers: 1, 2, 4, 8, 16 et c.
Therefore, i'd need some help figuring out a function that allows me to:

first input a specified sum of 1's: n
then determine which decimal values that produces any variation of n 1's within the 16 bits.
and lastly, randomly choose from any of these numbers.

Any input would be appreciated!
Answer: The algorithm to use depends on (a) the capabilities of your software platform; (b) how many such random draws you need; (c) how large the number of digits $n$ is; and (d) how large the number of possible results $\binom{n}{k}$ (where $k$ is the number of ones) is.
Most statistical work is done with 32 or 64 signed integer and/or double-precision IEEE floating point numbers, so I will assume that of (a).  Here is a set of solutions illustrated with working R code.  To be specific, they all draw uniformly, independently, and randomly from the set $\mathcal{B}(n,k)$ of integers which, when represented in binary, have up to $n$ digits of which exactly $k$ are ones.

You need a single random integer.  Take a sample $i_1, i_2, \ldots, i_k$ without replacement from the set of places $0,1,\ldots, n-1$ and return $2^{i_1} + 2^{i_2} + \cdots + 2^{i_k}.$
rchoose <- function(n, k) sum(2^sample(0:(n-1), k))

This algorithm has $O(n)$ time and storage requirements.
You need a large number $N$ of random integers where $n$ and $k$ are small.  "Small" means both (1) your system accurately represents all integers through $2^{n}-1$ and (2) you have enough speed and RAM to compute and store all the elements of $\mathcal{B}(n,k).$
The solution is to generate an array representing all elements of $\mathcal{B}(n,k)$ and then (rapidly) draw randomly from this array:
rchoose.many <- function(N, n, k) {
  b <- colSums(2^combn(0:(n-1), k))
  sample(b, N, replace=TRUE)
}

This algorithm requires $O(n \binom{n}{k})$ time to initialize plus $O(N)$ additional time to run.  Its storage requirements are $O(n \binom{n}{k})$ (but could be reduced to $O(\binom{n}{k})$ by accumulating the values in a loop during initialization).
You need a large number of random integers where $n$ and $k$ are not small.  You're still limited by the need to represent $n$-digit binary integers in your system.  About the best you can do is to loop $N$ times over the single-draw solution (1):
rchoose.many.large <- function(N, n, k) {
  replicate(N, rchoose(n, k))
}

This takes $O(Nn)$ time and $O(n)$ storage.

Comparing the asymptotic requirements provides a criterion for selecting the appropriate solution in any situation.
Examples
These timings (on one modest workstation) provide some indication of the possibilities.
system.time(x <- rchoose.many(1, 33, 7))   # 8 sec.
system.time(x <- rchoose.many(1e5, 33, 7)) # 8 sec.
system.time(x <- rchoose.many(1, 33, 16))  # (Not run: would take about 35 min.)

system.time(x <- rchoose.many.large(1e5, 33, 7))  # 0.8 sec.
system.time(x <- rchoose.many.large(1e5, 33, 16)) # 0.9 sec.

Here's a histogram of one largish sample (of a million draws) showing the distribution for $n=10,k=4.$  The bins have to be wider than $1$, for otherwise the counts will be either $0$ or close to a constant (because the distribution is uniform on $\mathcal{B}(10,4)$).  I chose a width of $4:$
library(ggplot2)
ggplot(data.frame(x=rchoose.many(1e6, 10, 4)), aes(x)) + geom_histogram(binwidth=4)


typed client setup in Startup.cs, cannot get info in injected service

Question: I have a demo Azure function and setup the typed client as follow:
But I can't get base address in injected httpclient instance. Any advice? Thanks
            builder.Services.AddSingleton<IMyService, MyService>();//Comment out this line will make it work
            builder.Services.AddHttpClient<IMyService, MyService>(client =>
            {
                client.BaseAddress = new Uri("https://api.github.com/");
            });

        }

    public class MyService : IMyService
    {
        private readonly HttpClient httpClient;

        public MyService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public async Task LogMsg()
        {
            Console.WriteLine(httpClient.BaseAddress);
        }

Updates:
Remove the AddSignleton line will work...
See link in comment
Comment: Duplicated with https://stackoverflow.com/questions/66165401/typed-http-client-in-azure-function-not-registering-properly?rq=1
Answer:
can't get the base address in injected httpclient instance

Try to remove the AddSingleton<MyServicehttp>() Registration in Configuration Portion.
public class Startup : FunctionsStartup
   {
       public override void Configure(IFunctionsHostBuilder builder)
       {
           builder.Services.AddScoped<MyService>();
           builder.Services.AddScoped<Customlog>();
           //Removed AddSingleton in service registration
              //builder.Services.AddSingleton<MyServiceshttp>()
              builder.Services.AddHttpClient<MyServicehttp>(client =>
           {
               // this code never runs
               client.BaseAddress = new Uri("https://api.github.com/");
           });
       }
   }

If you want to use the singleton, try to inject HttpClientFactory inside your Service instance like (MyServiceshttp).
Refer here


How Print individual fields in a view row by row

Question: I have so much fields in a content like "title", "field_image", "field_description", and i use a view for create a block and put it on my front page...
I will make a slider with a jquery plugin (jssor slider), i need use the structure of jssor slider. then in my view, i use "views-view-fields--[name_machine]--block.html.twig" for print individual fields. but the file "views-view-fields..." print for each content, run all code on this file,and i need to put the initial containers of this plugin only once, and the code of the images several times.
I try to put the initial containers of the plugin in the "page.html.twig" but when i print the block with the "views-view-fields..." inside
he puts a lot of code and many labels and containers that I do not need and the plugin stops working. let me show the files.
my page.html.twig
          {# Header #}
      {% if page.banner_front %}

        {% block banner_front %}
            {{ page.banner_front }}
        {% endblock %}

then my views-view-fields--banner--block.html.twig:

                        {% if fields.title.content %}
                            {{ fields.title.content }}
                        {% endif %}

                        {% if fields.banner_description.content %}
                            {{ fields.banner_description.content }}
                        {% endif %}

                    {% if fields.field_url.content %}

Ver más

                    {% endif %}

to work correctly, the label
 must be left of the label
, but when the region is printed the system prints many labels and containers that damage the structure of the slider.
On Drupal 7 i used inside of the foreach the code of the images, and outside the inicial structure, and works well but now, i dont know how to this.
Thanks a lot.
Comment: `the "views-view-fields..." inside he puts a lot of code and many labels and containers that I do not need` to remove this markup [follow my answer here](https://drupal.stackexchange.com/questions/207740/is-there-a-more-performant-alternative-than-overriding-template-files/207741#207741)
Comment: if you work with `Format:Unformatted list` try to override the `views-view-unformatted.html.twig` you will have the ability to add class to parent or inside each row
Comment: so glad that help.
Comment: I have poste it as answer if someone need it in the future.
Answer: If you work with Format:Unformatted list try to override the views-view-unformatted.html.twig, you will have the ability to add class to parent or inside each row.


ubuntu ssh banner

Question: I'm running Ubuntu x64 server 10.04 on a virtual slice and want to get rid of the lines in bold (and the blank line) below:

$ ssh user@server
Linux jm 220.127.116.11-rscloud #26 SMP Mon May 17 12:35:34 UTC 2010 x86_64 GNU/Linux
Ubuntu 10.04 LTS

Welcome to Ubuntu!
 * Documentation:  https://help.ubuntu.com/
Last login: Mon Oct 11 04:42:07 2010 from xx.xx.xx.xx
$
Answer: Remove or comment the following line in your <code>/etc/pam.d/sshd</code>:
<code># Print the message of the day upon successful login.
session    optional     pam_motd.so
</code>

ubuntu ssh banner


Rational numbers closed under field and/or vectorspace?

Question: The rational numbers $\mathbb Q = \{a/b | a, b \in \mathbb Z, b \neq 0\}$ where $\mathbb Z$ is a set of integers
is a Field.
But in my textbook notes
The set $\mathbb Q$ of all rational numbers is not a vector space reason: not closed under scalar multiplication.
Is there no scalar multiplication in fields?
Comment: Well $\Bbb Q$ is definitely a vector space over $\Bbb Q$. But it is not a vector space over $\Bbb R$. The question "Is $\Bbb Q$ a vector space?" is kind of meaningless without specifying a base field.
Answer: The scalar multiplication of a vector space $V$ over a field $k$ is a map
$$k\times V\to V$$
satisfying certain axioms. For example, if you have a field $k$, it comes with a multiplication map
$$k\times k\to k,$$
so every field can be viewed as vector space over itself. (Exercise: Check all the axioms!) In particular, $\mathbb Q$ is a vector space over  $\mathbb Q$. Your textbook probably means that $\mathbb{Q}$ is not a vector space over $\mathbb R$. This is correct, because that would require a scalar multiplication of the form
$$\mathbb R \times \mathbb Q \to
\mathbb
Q.$$
But this cannot be the usual multiplication: If you multiply $\pi$ and $1$, you get $\pi$, which lies outside of $\mathbb Q$. This is what your textbook means when it says that $\mathbb Q$ is not closed under scalar multiplication (with scalars from $\mathbb R$). Now you could try to be clever and find a scalar multiplication which is not the usual multiplication, but it still cannot work: Vector spaces over $\mathbb R$ are either $0$ or uncountable (Exercise: Proof this!), but $\mathbb Q$ is countable.