How much smaller is the set of ratios than the set of ordered pairs?

Question: For integers $a, b$ with $0 < a < N$ and $0 < b < N$ for some integer $N$, let $\{(a, b)\}$ be the set of all their ordered pairs and let $\{\frac{a}{b}\}$ be the set of all their ratios.
Clearly, $|\{\frac{a}{b}\}| < |\{(a, b)\}|$ (the number of possible ratios is smaller than the number of possible ordered pairs), since for example $\frac{2}{1} = \frac{4}{2}$ but $(2, 1) \neq (4, 2)$.
My question is: how much smaller is $|\{\frac{a}{b}\}|$ than $|\{(a, b)\}|$, as $N \to \infty$?

Here's my approach so far: for any given $b$, we can determine how many $a$s get "eliminated." For example, if $b=2$, then $a=2, 4, 6, \ldots$ are all eliminated (because $\frac{2}{2}=\frac{1}{1}, \frac{4}{2}=\frac{2}{1}, \frac{6}{2}=\frac{3}{1}, \ldots$). So when $b=2$, $|\{\frac{a}{b}\}| = (1 - \frac{1}{2}) |\{(a, b)\}|$. The first few such ratios $r$ are:
$b = 1 \implies r = 1$
$b = 2 \implies r = \frac{1}{2}$
$b = 3 \implies r = \frac{1}{3}$
$b = 4 \implies r = \frac{1}{2}$
$b = 5 \implies r = \frac{1}{5}$
$b = 6 \implies r = \frac{1}{2} + \frac{1}{3} - \left(\frac{1}{2}\right) \left(\frac{1}{3}\right) = \frac{2}{3}$
$b = 7 \implies r = \frac{1}{7}$
In other words, we find the prime factors $p_1, p_2, \ldots$ of $b$ and that reduces $|\{\frac{a}{b}\}|$ by $\frac{1}{p_1} + \frac{1}{p_2} + \ldots - \left(\frac{1}{p_1}\right) \left(\frac{1}{p_2}\right) - \ldots$
So, we want to know the average $r$ for all $b$ (as $b \to \infty$). Does this help us?
Comment: @XanderHenderson: Note that the two sets he compared are both finite because of the upper bound $N$, so they do not have the same cardinality. He is essentially asking for the asymptotic density because he lets $N$ go to infinity.
Comment: This is equivalent to asking how many pairs are coprime. See https://en.wikipedia.org/wiki/Coprime_integers#Probabilities
Comment: @XanderHenderson The first paragraph does state the set the OP considers in their definitions.
Comment: @JaapScherphuis Exactly right, you read my mind! Is there a more clear way I could write this in the question?
Comment: Oi... I missed the upper bound.  Oops.
Answer: I will use inclusive bounds, so $1 \leq a, b \leq n$.
$|\{\frac{a}{b}\}|$ is the number of coprime pairs $1 \leq a, b \leq n$. This is OEIS sequence A018805. For large $n$ it's noted that we have $\text{A018805(n)} \approx \dfrac{6}{\pi^2} n^2$.
$|\{a, b\}|$ is the number of pairs $1 \leq a, b \leq n$. This is simply $n^2$.
So their asymptotic density is the fraction of these two, giving simply $\dfrac{6}{\pi^2} \approx 0.60793$.
Comment: @jamaicanworm There's a sequence for (nearly) anything on the OEIS :) The proof stems from the Riemann zeta function, a fairly concise explanation can be found on the Wikipedia page Chappers linked earlier: https://en.wikipedia.org/wiki/Coprime_integers#Probabilities.
Comment: Amazing! Is this sequence significant / used in other applications? Who proved that $A018805(n) \to \frac{6}{\pi^2}n^2$?


Validating Dynamic forms

Question: <code>jQuery(document).ready(function(){
$("#submitButton").click(function () {
    if ( $("#formToSubmit").validationEngine('validate') == true) {
    $("#formToSubmit").submit();
    }
});
</code>
I am using the Validation Engine plugin for jQuery to validate forms on my site. I have a form that can get more text fields with the click of a button (js). The problem is once those fields are added they are not validated when content is typed and the user moves onto the next field, but after the user clicks submit. I want to know id there is a way to work around this and make the check dynamic again (checks as you fill it). above is the code for the init. please give me an idea on how to make it work.
Answer: Check if the dynamiclly created fields have different ID attributes.
Comment: The dynamically created fields are text fields and are created with the form (which has the id attribute that is bentioned in the above code). Each field created has a different id. also, as i mentioned, when the submit button is clicked, the form is the validated and those fields are checked and if they are not filled the form is not submitted and the messages popup beside the fields. the problem is i want it to check dynamically instead of just when it is submitted. Any Ideas?
Comment: maybe checking the docs at: https://github.com/posabsolute/jQuery-Validation-Engine can help... good luck!

Validating Dynamic forms


Awk adding constant values

Question: I have data in the text file like val1,val2 with multiple lines
and I want to change it to 1,val1,val2,0,0,1
I tried with print statement in awk(solaris) to add constants by it didn't work.
What is the correct way to do it ?

(From the comments) This is what I tried
awk -F, '{print "%s","1,"$1","$2"0,0,1"}' test.txt

Comment: Can you show what you tried? Maybe you were nearly there.
Comment: There are multiple awk version on Solaris. Unfortunately the default one is /usr/bin/awk and that is old, broken awk which must never be used so that will be causing you problems if you are trying to use it. Use /usr/xpg4/bin/awk or nawk instead on Solaris (or, even better, install gawk).
Comment: awk -F, '{print "%s","1,"$1","$2"0,0,1"}' test.txt
Comment: @TejasJoshi Try removing `"%s",`
Comment: please edit your question to include your sample code. Otherwise we'll get a long discussion running in comments of information that should be in the main body of the question. Good luck.
Answer: Based on the command you posted, a little change makes it:
$ awk -F, 'BEGIN{OFS=FS} {print 1,$1,$2,0,0,1}' file
1,val1,val2,0,0,1

OR using printf (I prefer print):
$ awk -F, '{printf "1,%s,%s,0,0,1", $1, $2}' file
1,val1,val2,0,0,1

Answer: To prepend every line with the constant 1 and append with 0,0,1 simply do:
$ awk '{print 1,$0,0,0,1}' OFS=, file
1,val1,val2,0,0,1

A idiomatic way would be:
$ awk '$0="1,"$0",0,0,1"' file
1,val1,val2,0,0,1

Answer: Using sed:
sed 's/.*/1,&,0,0,1/' inputfile

Example:
$ echo val1,val2 | sed 's/.*/1,&,0,0,1/'
1,val1,val2,0,0,1

Awk adding constant values


Flutter Keyboard makes widgets hide

Question: I have the problem that when I open the keyboard it hides the widgets behind it (screen is not resizing).
I saw some solutions in differents threads but none worked with me!
tried the following:

using the option of resizeToAvoidBottomInset: true inside the scafold.
using singlechildscroll view.
using EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom).

The detailed code is below, please note that class Background() is to do some shading on the background, will also put its code in different code box.
main code:
      Scaffold(
  resizeToAvoidBottomInset: true,
  key: _scaffoldkey,
  backgroundColor: Colors.transparent,
  body: Container(
    padding:
        EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
    child: Stack(
      alignment: Alignment.topCenter,
      children: <Widget>[
        const Background(),
        Column(
          children: [
            Container(
              alignment: Alignment.topCenter,
              padding: EdgeInsets.fromLTRB(0, 200.h, 0, 0),
              child: Text(
                "HELPER",
                style: GoogleFonts.lato(
                  fontStyle: FontStyle.normal,
                  color: Color.fromARGB(255, 245, 91, 165),
                  fontSize: 30.sp,
                  fontWeight: FontWeight.w700,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                softWrap: false,
              ),
            ),
            Expanded(
              child: Container(
                  alignment: Alignment.topCenter,
                  child: loading
                      ? const Center(
                          child: CircularProgressIndicator(),
                        )
                      : currentstate ==
                              MobVerificationState.SHOW_MOBILE_FORM_STATE
                          ? getMobileFormWidget(context)
                          : getOtpFormWidget(context)),
            ),
          ],
        ),
      ],
    ),
  ),
);

the problem is with getMobileFormWidget(context) and getOtpFormWidget(context))
they are different states, each is column which contains some widgets inside.
the background class code:
       return ShaderMask(
  shaderCallback: (bounds) => const LinearGradient(
    colors: [
      Color.fromARGB(255, 248, 247, 247),
      Color.fromARGB(255, 245, 91, 165),
    ],
    begin: Alignment.centerLeft,
    end: Alignment.bottomCenter,
  ).createShader(bounds),
   child: Container(
    color: Colors.white,
  ),
);

Answer: You should use resizeToAvoidBottomInset: false, and the screen will be automatically elevated to the keyboard border, example:
Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.transparent,
        body: Container(
          padding:
              EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
          child: Stack(
            alignment: Alignment.topCenter,
            children: <Widget>[
              ShaderMask(
        shaderCallback: (bounds) => const LinearGradient(
          colors: [
            Color.fromARGB(255, 248, 247, 247),
            Color.fromARGB(255, 245, 91, 165),
          ],
          begin: Alignment.centerLeft,
          end: Alignment.bottomCenter,
        ).createShader(bounds),
        child: Container(
          color: Colors.white,
        ),
      ),
        Column(
          children: [
            Container(
              alignment: Alignment.topCenter,
              //padding: EdgeInsets.fromLTRB(0, 200, 0, 0),
              child: Text(
                "HELPER",

                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                softWrap: false,
              ),
            ),
            Expanded(
              child: Container(
                  alignment: Alignment.topCenter,
                  child:
                      ListView.builder(
                        itemCount: 10,
                        itemBuilder: (build, index){
                        return TextField();
                      }))
            ),
          ],
        ),
      ],
    ),
  ),
);

I used a random listView to clarify, instead of the getMobileFormWidget and getOtpFormWidget that you didn't provide with your code.
Comment: hi Abdallah, thanks but I used this too, no affect at all, also tried to make the top level widget is the stack, containing the background and scalffold (where everything is inside it), also no affect.
Comment: @SherifSaidElahl did you try the code i posted? keyboard is pushing the page up as you want.
Comment: I tried it too with the same problem in my side. btw I was using the same code "exactly" on the same device, but in a different project, and it was working totally fine. took it copy paste and it is not working!
Comment: This might me an emulator issue, try a physical device to see if it persists
Comment: i am on real device, running both applications together, with the same exact code, one is wokring and one isn't! .. thanks anyway :)
Answer: after two days of trials nothing worked except the code below, I adapted it to my code.
 import 'dart:ui';
 import 'package:flutter/material.dart';

 class KeyboardPaddingTest extends StatefulWidget {
 const KeyboardPaddingTest({Key? key}) : super(key: key);

 @override
 _KeyboardPaddingTestState createState() => _KeyboardPaddingTestState();
  }

 class _KeyboardPaddingTestState extends State<KeyboardPaddingTest> {
 EdgeInsets _viewInsets = EdgeInsets.zero;
 SingletonFlutterWindow? window;
 final _textFieldController = TextEditingController();

 @override
 void initState() {
 super.initState();
 window = WidgetsBinding.instance?.window;
 window?.onMetricsChanged = () {
  setState(() {
    final window = this.window;
    if (window != null) {
      _viewInsets = EdgeInsets.fromWindowPadding(
        window.viewInsets,
        window.devicePixelRatio,
      ).add(EdgeInsets.fromWindowPadding(
        window.padding,
        window.devicePixelRatio,
      )) as EdgeInsets;
    }
    });
    };
    }

  @override
  Widget build(BuildContext context) {
  return Container(
  width: double.infinity,
  height: double.infinity,
  color: Colors.greenAccent[100],
  alignment: Alignment.bottomCenter,
  child: Padding(
    padding: EdgeInsets.only(bottom: _viewInsets.bottom),
    child: Column(
      children: [
        Expanded(
          child: Center(
            child: Container(
              width: 200.0,
              color: Colors.lightBlueAccent[100],
              child: TextField(
                controller: _textFieldController,
                decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: 'Tap to show keyboard',
                ),
              ),
            ),
          ),
        ),
        const Text(
          'Testing Keyboard',
          style: TextStyle(
            fontSize: 24.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
      ),
      ),
      );
      }
      }

Flutter Keyboard makes widgets hide


Converter Número em Reais

Question: Estou querendo desenvolver um Simulador exemplo: de 1 real à 99 reais ele multiplica por x10 e acima de 100 reais ele multiplica por x11.
Queria saber como converte os número do campo1 para reais quando digitar?
Código:

<form name="form">

 Simulador de Cash's

<input name="campo1" type="text" value="" class="soma">

<input name="campo2" value="22" readonly>

<input name="campo4" readonly>

<input type="button" onclick="soma()" value="CALCULAR">
</form>

Comment: Depende, qual seria o valor monetário do `campo1`?
Answer: Sugiro um plugin jQuery chamado maskMoney (baixe aqui). Ele adiciona máscara de moedas no campo que você especificar.
Para usá-lo, carregue na sua página com:

E chame o plugin com o script:
$(function(){
 $("input").maskMoney({symbol:'R$ ',
showSymbol:false, thousands:'.', decimal:',', symbolStay: true});
 });

Um bom tutorial de como usar o plugin.
Fiddle para teste.
Comment: Obrigado <3 Me Ajudou muito Deus te Abençoe
Answer: deu certo aqui o link mais quando eu vou multiplicar ta dando NaN porque :?

<form name="form">
<input name="campo1" id="demo4">

<input name="campo2" value="22" id="demo3">

<input name="campo4" readonly>

<input type="button" onclick="soma()" value="Soma os Valores">
</form>

ai o código testa em sua máquina pra você ver

Converter Número em Reais


How to average/aggregate the result off a SQL query?

Question: I have a table with many rows each belonging to different users.
I first want to select all rows the belong to one user and then on each row add the average for that a certain column but can't make it work.
I'm would like the result to display the average on each row for the user but it's currently just displaying the value for that particular row.
Example :
CREATE TABLE test
(
    id INT,
    FOO INT,
    BAR INT,
    X INT,
    user_id INT
);

INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (1, 1, 2, 3, 1);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (2, 3, 2, 1, 1);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (3, 6, 6, 6, 1);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (4, 100, 100, 100, 1);

INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (4, 3000, 3000, 3000, 2);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (4, 400, 400, 400, 2);

And the query I'm trying to run:
SELECT
    id, foo, bar, x,
    AVG(foo) AS "avg_foo",
    AVG(bar) AS "avg_bar",
    AVG(x) AS "avg_x"
FROM
    test
WHERE
    user_id = 1
GROUP BY
    id, foo, bar, x;

But I'm just getting the same number that is in the "foo" column for the row as the result for avg_foo where instead I'm trying to get the average of all the "foo" rows displayed on each rows (the would be the same number every time).
Currently I'm getting this result :
| id  | foo | bar | x   | avg_foo                | avg_bar              | avg_x                  |
| --- | --- | --- | --- | ---------------------- | -------------------- | ---------------------- |
| 1   | 1   | 2   | 3   | 1.00000000000000000000 | 2.0000000000000000   | 3.0000000000000000     |
| 2   | 3   | 2   | 1   | 3.0000000000000000     | 2.0000000000000000   | 1.00000000000000000000 |
| 3   | 6   | 6   | 6   | 6.0000000000000000     | 6.0000000000000000   | 6.0000000000000000     |
| 4   | 100 | 100 | 100 | 100.0000000000000000   | 100.0000000000000000 | 100.0000000000000000   |

Whereas I'm expecting:
| id  | foo | bar | x   | avg_foo                | avg_bar              | avg_x                  |
| --- | --- | --- | --- | ---------------------- | -------------------- | ---------------------- |
| 1   | 1   | 2   | 3   | 27.5      | 27.5    | 27.5      |
| 2   | 3   | 2   | 1   | 27.5      | 27.5    | 27.5      |
| 3   | 6   | 6   | 6   | 27.5      | 27.5    | 27.5      |
| 4   | 100 | 100 | 100 | 27.5      | 27.5    | 27.5      |

---

I've made a fiddle
https://www.db-fiddle.com/f/5tGQkqEnqB8et75eJ7NNWt/0
Answer: Use window functions:
SELECT id, foo, bar, x,
       avg(foo) over (partition by user_id) as "avg_foo",
       avg(bar) over (partition by user_id) as "avg_bar",
       avg(x) over (partition by user_id) as "avg_x"
FROM test
WHERE user_id = 1

Comment: thanks. Do you know why the result is returned as a string and not a int / float ?
Comment: @manueser . . . `avg()` cannot return a string value.  Something else would be causing you to think it is a string.
Answer: You seem to want window functions:
select t.*,
    avg(foo) over() as avg_foo,
    avg(bar) over() as avg_bar,
    avg(x)   over() as avg_x
from test t
where user_id = 1


Dúvida em c (listas encadeadas e vetor)

Question: Como posso fazer para criar um vetor em que cada posição é um ponteiro para uma lista encadeada ?
Por exemplo:
typedef struct info Info
struct info {
 int num;
 Info* prox;
};

E depois quero criar um vetor, e fazer algo do tipo, mas com alocação dinâmica do tamanho:
Por exemplo:
v[0] = colocarnum(lista, 10);

Comment: `Info* vetor[10];` ou `vetor = (Info *) malloc(10 * sizeof(Info *));`
Comment: Uma lista ligada é diferente de um vector qual o objectivo do vector final?
Comment: A ideia é que cada índice da lista tenha um ponteiro que leva a uma lista ligada contendo informações.
Answer: Com uma lista ligada os valores são percorridos através dos campos prox.
typedef struct info {
    int num;
    struct info *prox;
} Info;

int main(void) {
    Info *info1, *info2;
    info1 = (Info *) malloc(sizeof(Info));
    info2 = (Info *) malloc(sizeof(Info));

    info1->num = 1;
    info2->num = 2;
    info1->prox = info2;

    printf("Valor 1 -> %d\n", info1->num);
    printf("Valor 2 -> %d\n", info1->prox->num);

    free(info2);
    free(info1);

    return 0;
}

Caso tenha um vector de ponteiros para Info irá ter uma lista de listas.
Answer: De acordo com o IME-SP, um lista encadeada significa:

Listas encadeadas. Uma lista encadeada é uma representação de uma sequência de objetos, todos do mesmo tipo, na memória RAM (= random access memory) do computador. Cada elemento da sequência é armazenado em uma célula da lista: o primeiro elemento na primeira célula, o segundo na segunda, e assim por diante. (https://www.ime.usp.br/~pf/algoritmos/aulas/lista.html)

em C, podemos criar uma lista simplesmente encadeada definindo uma estrutura LISTA que irá conter os dados da lista e um ponteiro do tipo struct para o proximo elemento da lista.

(Duvidas sobre ponteiros, acesse o link:
O que são ponteiros?

No seu caso, como trata-se de uma lista simplesmente encadeada, a lista irá apontar apenas para frente, ou seja para o proximo elemento. Mas poderiamos fazer uma lista que possuisse ponteiros que apontassem tanto para o proximo quanto para o anterior. Vamos dar uma olha no codigo de implementacao abaixo para entender melhor:
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
/* Definicao da estrutura lista que tera o apelido do "no" */
typedef struct lista {
    int vetorDeNumeros[10];
    struct lista *prox;
} no;

void inserir(int x, no *p) {
    /* Inserir um elemento a lista */
}

void excluir(no *p) {
    /* Excluir um elemento a lista */
}

void busca (int x, no *le) {
    /* Buscar um elemento a lista */
}

void imprimir(no *le) {
    /* imprimir um elemento a lista */
}

int main (void) {
    /* Criando um vetor dinamico  da lista */
    int tamLista;
    int tamVetores;
    no* vetorDinamico;
    printf("Quantas listas seu vetor irá possuir? R: ");
    scanf("%d",&tamLista);
    getchar();
    /* Alocando dinamicamente o tamanho do vetor lista*/
        vetorDinamico = (no *) malloc(tamLista * sizeof(no));
    /* Alocando dinamicamente o tamanho dos vetores de numeros dentro de lista do vetor dinamico*/
            for (int i = 0; i<tamLista; i++) {
                printf("Quantas posicoes terá o vetor da sua lista numero %d? R: ",i);
                scanf("%d",&tamVetores);
                vetorDinamico[i].vetorDeNumeros[tamVetores] = (long) malloc(tamVetores * sizeof(long));
            }
/* adicionando numeros dentro de uma lista dentro de um vetorDinamico */
vetorDinamico[0].vetorDeNumeros[0] = 1;
/* Teste de impressao de um vetor de inteiro dentro de um vetor dinamico de lista chamado no */
printf("O Numero armazenado na posicao 0 do vetor 0 da estrutura é: %d",vetorDinamico[0].vetorDeNumeros[0]);

    return 0;
}

O Codigo nada mais faz que:

criar uma estrutura LISTA com o nome de NO com um vetor de numeros dentro dela;
criar um vetor dinamico da estrutura lista e alocar a memoria do vetor dinamicamente;
criar um vetor de numeros dentro de cada lista atribuida ao vetor dinamico de lista e alocar a memoria destes vetores dinamicamente
imprimir um numero teste.

Espero que tenha esclarecido sua duvida.

Dúvida em c (listas encadeadas e vetor)


How do I get my HP servers to email me when a drive fails?

Question: Ideally, with as simple of install as possible and without requiring rebooting the servers. Mostly for DL380 G5's if it helps.
Comment: Shame they're not G7s, or you could use HP Insight Manager.
Comment: Are your servers running Windows or Linux?
Comment: What operating systems are you running on these servers?
Comment: They're all 2003 or 2008 both vanilla and R2. I played with SIM but it wasn't able to talk to my G5's.
Comment: SIM should still be compatible with G5 ProLiants. Did you have the agents installed when you tried before?
Answer: This depends slightly on the operating systems you're running on the servers, but in general, it is possible to obtain alerts from HP ProLiant servers and Smart Array RAID controllers.
The full driver and software support listing for your DL380 G5 systems is listed here.
SNMP and a monitoring solution is the best approach... But you can augment that with some of HP's tools. HP offers the HP Systems Insight Manager, which is available for download and also comes with the servers. This is ideal for collections of servers. If you're looking for one-off alerts without building a management or monitoring infrastructure, you can simply install the HP Management Agents (aka ProLiant Support Pack).
For standalone Linux systems, I'll have the agents send traps via email. I'll usually configure the support pack with defaults or a custom bundle, then edit /opt/hp/hp-snmp-agents/cma.conf and change the trapemail line to point to the recipient address:
########################################################################
# trapemail is used for configuring email command(s) which will be
# executed whenever a SNMP trap is generated.
# Multiple trapemail lines are allowed.
# Note: any command that reads standard input can be used. For example:
#             trapemail /usr/bin/logger
#       will log trap messages into system log (/var/log/messages).
########################################################################
trapemail /bin/mail -s 'HP Insight Management Agents Trap Alarm' email@example.com

If you're running Linux and don't want to install the full HP management suite, you can develop a script around the cciss_vol_status utility to query controller/disk status. Also see: Installing HP Agents on OpenFiler
Comment: any elegant way to test an alert for a RAID array failure, other than pulling a drive out of the slot?  I've got a couple `ProLiant DL360 G7` servers, and HP SIM set up for monitoring.
Comment: Not that I know of. The Insight agents definitely work. If you can see the array status via the hpacucli utility and you know you're receiving alerts in HP SIM, I think it's fair to assume things will work.
Answer: Check out HP Insight Manager
https://www.hpe.com/us/en/product-catalog/detail/pip.489496.html#
I believe it should work with your Servers.
Answer: I used the lightweight program that @ewwite mentioned in his answer:  cciss_vol_status
If you follow the accompanying INSTALL instructions, the script is placed in /usr/local/bin/cciss_vol_status.
Here is a wrapper script I use to grep the output of cciss_vol_status, and send an email if any array has a status of FAILED.
#!/bin/bash
#
# Check status of RAID volumes on HP Smart Array controllers.  Send an email
# alert if any volumes have a FAILED status.
#
status=`/usr/local/bin/cciss_vol_status /dev/sd*`

# email lock file
lockfile=/tmp/raid.check.hp.smartarray.lock
# how often to send an email (minutes)
_notification_freq=59
_host=`hostname`
# To: email
_toemail=root

# create email lock file
[ ! -f ${lockfile} ] && /bin/touch ${lockfile}

if echo $status | grep -q FAILED
then
    # make sure we haven't sent a notification in the last X minutes
    if test `find ${lockfile} -mmin +${_notification_freq}`
    then
        echo -e "${status}" | /bin/mail -s "System Alert! RAID failure on ${_host}" ${_toemail}

        # update lock file mod time
        /bin/touch ${lockfile}
    fi
fi

Call the above script in cron.  I run the check every two minutes:
*/2 * * * * /usr/local/bin/raid.check.hp.smartarray.sh

We do use HP System Insight Manager to check if our HP's are up and running, but nothing beyond that.  I found the Linux agent to be overkill for us, since we have other monitoring solutions in place, so this script above serves its specific purpose well.
UPDATE
Just a troubleshooting tip in case you run into this.  This script proved helpful this morning when I got an email about a failed array with:

Cache dirty limit reached

The device went read-only and was not visible in /proc/partitions.  I rebooted the server and saw these messages on boot:

Logical drive(s) disabled due to possible data loss.
  Select "F1" to continue with logical drive(s) disabled
  Select "F2" to accept data loss and to re-enable logical drive(s)

I selected F2 and the RAID was fine and mounted on boot.
Answer: install smartmontools. Mails you BEFORE a drive fails.
Comment: ~30% of the time.  SMART is *not* a silver bullet.


Where is this hidden computer name coming from?

Question: Environment:
I am baking Amazon Machine Images with SQL Reporting Services (SSRS) installed. The Windows Server 2016 machine is joined to the domain and its computer name is changed AFTER install.
Problem:
When I open SSRS Configuration Manager it shows the correct computer name:

However, if I set the Service Account it shows the original AWS Computer Name:

Troubleshooting:
1) I looked everywhere in the Registry. Its not there! EC2AMAZ-DPNS3JK is not there!
2) I took a Process Monitor trace opening SSRS Config Manager and confirmed its using the expected registry key:

3) I thought it might be kept in the SSRS database (master, msdb, temp, etc) and searched all tables. The only reference to it is with some upgrade history:

4) I searched the disk drive just encase it was in a Hosts file or something and no results.
Question:
Where is this value EC2AMAZ-DPNS3JK coming from?
Is it hidden in some Registry Application Hive or something?
Pulling my hair out on this one and would appreciate suggestions. Thanks.
Update:
The comments were right so I changed the SQL Instance name. However, changing the SQL Instance name still doesn't fix it!!
Comment: You're asking about the service instance name not the computer name. Those are two different things. Check here: https://sqldbpool.com/2008/09/03/how-to-change-sql-server-instance-name/
Comment: The right way to do this is to use a sysprepped image. Barring that, you need to rename your SQL instance(s) after renaming the computer. - https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ami-create-standard.html - https://aws.amazon.com/premiumsupport/knowledge-center/sysprep-create-install-ec2-windows-amis/
Comment: Glad to help...
Comment: Regarding your edit, have you tried rebooting the server after making the change?
Answer: The right way to do this is to use a sysprepped image. Barring that, you need to rename your SQL instance(s) after renaming the computer.
https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ami-create-standard.html
https://aws.amazon.com/premiumsupport/knowledge-center/sysprep-create-install-ec2-windows-amis/
Answer: I had to call MS support and with their help we worked it out, solution on Stackoverflow:
https://stackoverflow.com/q/55998961/495455
Comment: What's it doing there?
Comment: @MichaelHampton it renames the SSRS instance using the rsconfig.exe utility, quite difficult to find and I got notified > 1000 views...


React - How can I fire an Event listener just once?

Question: Let's say I have a button that only fires just once then the listener is removed.
I've done this with vanilla Javascript
const element = document.querySelector('#MyElement');
element.addEventListener('click', handleClick, {once: true});

I don't know how can I access this property with React synthetic events since this is putted directly in the component
<button id="MyElement" onClick={handleClick}>Click me!</button>

Thanks
Answer: You can use useRef to do the same. Demo link is here
import React, { useEffect, useRef } from "react";

export default function App() {
  const ref = useRef();

  useEffect(() => {
    if (ref.current) {
      ref.current.addEventListener("click", () => console.log('Clicked only once'), { once: true });
    }
  }, []);

  return (

      <button ref={ref}>Click on me (Once)</button>

  );
}

Answer: const [avoidExtraCall, setAvoidExtraCall] = useState(false);

const handleClick = () => {
  if(!avoidExtraCall){
    //Do what you want here then
    setAvoidExtraCall(true);
    //This if statement will only be executed once
  }
}

return (
  <button id="MyElement" onClick={handleClick}>
    Click me!
  </button>
);

Answer: You can use a variable in state, probably a boolean for this
function App {
  const [buttonClicked, setButtonClicked] = useState(false);

  const handleClick = () => {
    setButtonClicked(true);
    // continue with the function
  }

  return <button onClick = {
    buttonClicked ? () => {} : handleClick
  } > Click < /button>

}

Or you could just return from the handleClick
function App {
  const [buttonClicked, setButtonClicked] = useState(false);

  const handleClick = () => {
    if(buttonClicked){
      return; //simply return
    }
    setButtonClicked(true);
    // continue with the function
  }

  return <button onClick={handleClick}> Click </button>

}

I would prefer the second option.
Answer: Flip the state once the element has triggered its event :
handleClick() {
    this.setState({
        hasTriggered: true
    })
}

render() {
    return (

            {
                !this.state.hasTriggered ?
                <MyElement onClick={this.handleClick.bind(this)} /> : null
            }

    )
}


Game theory Centipede game

Question: Players $A$ and $B$ alternately had the opportunity to claim or pass a growing pile of dimes (maximum of 10) placed on the table.
Suppose rules of game were changed so that
Two rounds of game are played with the same two players $A$ and $B$. In
the first round, $A$ may not keep more than five dimes, and $B$ may not keep
more than nine. Find the rollback equilibrium strategies for each player.
My question is
I am not understanding this statement In the first round, $A$ may not keep more than five dimes, and $B$ may not keep more than nine. In original game as shown below, whosever ($A$ or $B$) turn is take entire amount or pass it. But here it is stated that $A$ may not keep more than five dimes and $B$ may not keep more than nine, than where does remaining amount in growing pile goes?
I am assuming rounds here mean the same game (entire upto amount $100$) is played multiple times?
In original centipede game will stop at very first step; that is player $A$ choose to take $10$ dime. Does playing same game two times build confidence among players and game will not stop at very first step?

Answer: In odd rounds, when $A$ has the right to claim, he collects up to five dimes and the rest stays in the pile (to be collected by $B$).
Similarly, in even rounds, $B$ has the right to claim but she collects up to nine dimensions (and leaves the rest to $A$).

Game theory Centipede game


How can I change the Type GUI Element from TextView to HTMLView

Question: I have a code, that is a website and I need to write an App, that shows just this page.
But the problem is that my code didn't see the Hyperlinks because I need to change from TextView to HTMLView.
this is the code:
<code>    public class BlackBoardClient {
    private static final String BLACK_BOARD_URL = "https://zpa.cs.hm.edu/public/notice_board/";
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy");

    public static List<BlackBoardEntry> getBlackBoardEntries() throws IOException  {
        List<BlackBoardEntry> entries = new ArrayList<>();
        Document doc = Jsoup.connect(BLACK_BOARD_URL).get();
        Element newsTable = doc.getElementById("content").selectFirst("table");
        Iterable<Element> rows = newsTable.selectFirst("tbody").children();

        for (Element row : rows) {
            Iterator<Element> columns = row.children().iterator();
            String author = columns.next().text();
            String title = columns.next().text();
            String content = columns.next().text();
            LocalDate validFrom = LocalDate.parse(columns.next().text(), FORMATTER);
            LocalDate validUntil = LocalDate.parse(columns.next().text(), FORMATTER);
            BlackBoardEntry entry = new BlackBoardEntry(author, title, content, validFrom, validUntil);
            entries.add(entry);
        }

        return entries;
    }
}
</code>
It shows like this: enter image description here
<code> public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView dataList = findViewById(R.id.dataList);

        dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BlackBoardEntry entry = (BlackBoardEntry) parent.getItemAtPosition(position);
                String content = entry.getContent();
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View popupView = inflater.inflate(R.layout.content_popup, null, false);
                ((TextView) popupView.findViewById(R.id.contentView)).setText(content);

                PopupWindow popup = new PopupWindow(popupView, 500, 1000, true);
                popup.showAtLocation(parent, Gravity.CENTER, 0, 0);

                }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<BlackBoardEntry> entries = BlackBoardClient.getBlackBoardEntries();
                    BlackBoardAdapter adapter = new BlackBoardAdapter(entries, getApplicationContext());
                    dataList.post(new Runnable() {
                        @Override
                        public void run() {
                            dataList.setAdapter(adapter);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
</code>
Answer: For just showing Web-Content from an existing URL, I would recommend to implement an Android WebView.
Your current popup-View is defined as Android TextView:
<code>((TextView) popupView.findViewById(R.id.contentView)).setText(content);
</code>
Change this to a WebView (in the xml "Design-/Layout-View" Tool)
For an example look at Android Developer Docs https://developer.android.com/guide/webapps/webview
It is straigt forward to use, you can invoke JS if necessary.
Dont forget to change your manifest-file for permissions.
<code><manifest ... >
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>
</code>


shell sort inverso java

Question: pessoal estou com uma duvida, como fazer shell sort inverso decrescente.
private static void shellsort(int v[], int n) {
    int i, j, aux, h = 1;
    do
        h = 3 * h + 1;
    while (h < n);
    do {
        h /= 3;
        for (i = h; i < n; i++) {
            aux = v[i];
            j = i - h;
            while (j >= 0 && aux < v[j]) {
                v[j + h] = v[j];
                j -= h;
            }
            v[j + h] = aux;
        }
    } while (h > 1);
}

Comment: Olá, o que tem de errado com o exemplo que aí tens ?
Comment: no exemplo ele faz em ordem crescente, e eu gostaria na ordem decrescente =(                                                                                Vetor[995]= 99486
Vetor[996]= 99492
Vetor[997]= 99583
Vetor[998]= 99701
Vetor[999]= 99765
Comment: Para mudar de crescente para decrescente basta mudar a condicao `aux < v[j]` para `aux > v[j]`
Answer: Boa noite, para mudar de crescente para decrescente no seu código, basta alterar a condição aux < v[j] para aux > v[j]
por exemplo:
private static void shellsort(int v[], int n, boolean crescente) {
    int i, j, aux, h = 1;
    do
        h = 3 * h + 1;
    while (h < n);
    do {
        h /= 3;
        for (i = h; i < n; i++) {
            aux = v[i];
            j = i - h;
            if (crescente) {
                while (j >= 0 && aux < v[j]) {
                    v[j + h] = v[j];
                    j -= h;
                }
            } else {
                while (j >= 0 && aux > v[j]) {
                    v[j + h] = v[j];
                    j -= h;
                }
            }
            v[j + h] = aux;
        }
    } while (h > 1);
}

shell sort inverso java


Why does linking a gpu freeze QEMU in Ubuntu

Question: I am running a Ubuntu on a workstation with 2 GTX 1070 and I5 7400 CPU, I have QEMU installed and I have an old windows 10 vm I tried to link the GPU by adding the PCI link hardware in virt-manager GUI, and restored windows vm (from a saved state) it detects a PCI hardware but does not install any drivers, I powered the VM completely then tried to run it again but I got this error
  File "/usr/share/virt-manager/virtManager/object/libvirtobject.py", line 57, in newfn
    ret = fn(self, *args, **kwargs)
  File "/usr/share/virt-manager/virtManager/object/domain.py", line 1384, in startup
    self._backend.create()
  File "/usr/lib/python3/dist-packages/libvirt.py", line 1353, in create
    raise libvirtError('virDomainCreate() failed')
libvirt.libvirtError: unsupported configuration: host doesn't support passthrough of host PCI devices

so I check if VT is enable and it is, since
sudo rdmsr 0x3A returns a 5
next step I did was to check kvm-ok and I got
 INFO: /dev/kvm exists
 KVM acceleration can be used

everything seems okay so far so I used
virt-host-validate and realized IOMMU is not enabled so I did the following, edited
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" to GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_iommu=on" followed by update-grub
now IOMMU is enabled since virt-host-validate outputs
  QEMU: Checking if IOMMU is enabled by kernel                               : PASS

now when I try to run the same vm without the pci link it works fine but adding the pci link causes the libvirtd to timeout and freeze
авг 28 00:45:22 WORKSTATION systemd[1]: libvirtd.service: Unit process 1814 (dnsmasq) remains running after unit stopped.
авг 28 00:45:22 WORKSTATION systemd[1]: libvirtd.service: Unit process 1815 (dnsmasq) remains running after unit stopped.
авг 28 00:45:22 WORKSTATION systemd[1]: libvirtd.service: Unit process 4018 (libvirtd) remains running after unit stopped.
авг 28 00:45:22 WORKSTATION systemd[1]: Failed to start Virtualization daemon.

The output pf dmesg
[32729.791574] [drm:nv_drm_master_set [nvidia_drm]] *ERROR* [nvidia-drm] [GPU ID 0x00000500] Failed to grab modeset ownership
[32729.792216] [drm:nv_drm_master_set [nvidia_drm]] *ERROR* [nvidia-drm] [GPU ID 0x00000900] Failed to grab modeset ownership

am I missing something, do I need to enable any extra features or maybe disable any?
Comment: Have you excluded the other GPU from your Linux driver? The Linux GPU driver must not manage the GPU you want to pass-through. Please add `dmesg` output right after boot so we can see the status.
Comment: @TeroKilkanen please check the updated question
Comment: This is only part of `dmesg` output, please add the full output after system boot.
Comment: @TeroKilkanen please check the output in the pastebin [link](https://pastebin.com/raw/yU53b3v2)
Answer: From the dmesg output it is visible that the Linux kernel loads drivers for both cards.
In order to free the device for your VM, you need to unbind the driver from it. https://www.iram.fr/~blanchet/ethercat/unbind_manually_pci_device.html tells how to unbind the driver from a device.
First, find PCI slots and actual drivers:
lspci -Dk

The output might look like:
0000:01:06.0 Ethernet controller: Intel Corporation 8255xER/82551IT Fast

Ethernet Controller (rev 10)
Kernel driver in use: e100
0000:01:07.0 Ethernet controller: Intel Corporation 8255xER/82551IT Fast
Ethernet Controller (rev 10)
Kernel driver in use: e100
You need to find the NVidia entries there. You might need to guess which device is the one you are using.
You need to note the PCI ID (0000:01:07.0) and driver name (e100) for your GPU.
Then you can issue
echo -n "<pci id>" > /sys/bus/pci/drivers/<driver>/unbind

You need to replace <pci_id> and <driver> with the values you got from lspci output. This will unbind the NVidia driver from the specified device, freeing it up for PCI passthrough.
Comment: That is the most likely blocker here. I cannot definitely say it is the only reason.
Comment: so I only have to unbind the gpu and i am good to go?
Comment: So i used the command `echo " | sudo tee /sys/bus/pci/drivers/nvidia/unbind"` but this never returns to the terminal and the only option is to reboot the system even using `kill ` does not help I already asked a question [here](https://unix.stackexchange.com/questions/715246/how-to-unbind-a-gpu-sys-bus-pci?noredirect=1#comment1355276_715246) but thought i would mention it here


break text (new lines) for every value

Question: How can I break text into my textarea in Angular 2?
I got compontent which shows some details.

Details

        <form action="" class="form-horizontal" *ngIf=alias>

                Mail:

{{alias.name + '(at)' + alias.domain}}

                Recipients:

                    <textarea class="form-control" row="4" col="50"> {{ alias.recipients }}
</textarea>

                    <button type="submit" class="btn btn-outline-info" (click)="goBack()">Cancel</button>

        </form>

I tried add
 in textarea but doesn't works.
I want to get something like this:
Output:

alias.recipient1
alias.recipient2
alias.recipient3

Instead alias.recipient1, alias.recipient2, alias.recipient3 (Now i have this)
Answer: In your app logic (controller or whatever you are using), you must separate them (assuming they are currently separated by comma-space):
alias.recipients = alias.recipients.split(', ').join('\n\n');

break text (new lines) for every value


Proving two determinants are equal

Question: Using determinant properties (without expanding), prove that
$$ \begin{vmatrix}yz & z^2 & y^2 \\ z^2 & xz & x^2 \\ y^2 & x^2 & xy \end{vmatrix} =
xyz\begin{vmatrix}x & z & y \\ z & y & x \\ y & x &z\end{vmatrix}$$
I'm completely lost and I don't know what to try. Any hints?
Thanks in advance.
Comment: Do you know how to find the determinant of a 3x3 matrix?
Comment: then calculate the determinate of you 3by3 matrices?
Comment: Then just calculate both determinants and simplify both sides.
Comment: I only know how to calculate the value of a 3x3 determinant.
Comment: I forgot to mention that you're not allowed to expand it.
Answer: Start from
$$\begin{vmatrix}x & z & y \\ z & y & x \\ y & x &z\end{vmatrix}.$$
Multiply the colums by $y, x, \frac{xy}z$; multiply the rows by $\frac{z}{x},\frac z y, 1$. You have now multiplied the determinant with $xyz$.
Edit: More symmetric: multiply the colums $yz, zx, xy$; multiply the rows by $\frac1x,\frac1y, \frac1z$.
Comment: Ingenious. Any tip on how you discovered that this sequence of operations would work?
Comment: @MarcvanLeeuwen Actually the above argument proves it for the 'universal' ring $\Bbb Z[x,y,z]$ by considering its fraction field where $x,y,z$ are invertible and then, because the it is just a polynomial, it holds in any ring $R$ for any variables $a,b,c$ by using the evaluation morphism $\Bbb Z[x,y,z] \mapsto R: f(x,y,z)\mapsto \bar f(a,b,c)$.
Comment: This uses that $x,y,z$ must each be invertible, which is against the spirit of determinants. More precisely makes the proof invalid over general commutative rings. And in any case it obliges you to do some special cases.
Comment: @Henning If you guess $y$ and $z/x$ then there is at most one possibility for the other options. There is further freedom because you can multiply all rows by the same number and divide all colums by the same number so there is really only one degree of freedom.
Comment: @Myself: Yes I know. But (just to be obnoxious) how do you prove the determinant is a polynomial in the matrix entries without using expansion?
Comment: @MarcvanLeeuwen I guess that depends on how you wish to define the determinant... Some people define it as a polynomial (and then you must prove the multilinear properties). Others as the unique multilinear map with some properties, or the induced map ${\wedge^n} V\to {\wedge^n} V : x\mapsto \mathrm{det}(\alpha)x$ etc. But inevitably at some point someone, like an author of a text on linear algebra, has to do a bit of work to tie everything together :-)
Answer: HINT: Sarrus' scheme gives it immediately.
Comment: http://en.wikipedia.org/wiki/Rule_of_Sarrus

Proving two determinants are equal


Problema com HABTM no Cakephp 2.x

Question: Estou tendo problemas durante a pesquisa do meu método view, onde tenho a seguinte pesquisa:
public function view($id = null) {
    if (!$this->Setor->exists($id)) {
        throw new NotFoundException(__('Parâmetro inválido!'));
    }

    $options = array('conditions' => array('Setor.' . $this->Setor->primaryKey => $id));
    $this->set('setor', $this->Setor->find('first', $options));
}

Tenho o resultado no debug:
array(
(int) 0 => array(
    'Setor' => array(
        'id' => (int) 1,
        'nome' => 'Diretoria de Modernização Administrativa',
        'secretaria_id' => (int) 2
    ),
    'Secretaria' => array(
        'id' => (int) 2,
        'codigo' => '00004210',
        'nome' => 'Secretaria de Estado de Planejamento'
    ),
    'Veiculo' => array()
)

O problema é que nada está sendo listado em Veículo, mas sei que existe os dados relacionados. Quando efetuo a pesquisa do Veiculo, ele me retorna os Setores relacionados. Mas não o contrário.
A minha model de Setor está definida da seguinte forma:
public $belongsTo = array(
    'Secretaria' => array(
        'className' => 'Secretaria',
        'foreignKey' => 'secretaria_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Status' => array(
        'className' => 'Status',
        'foreignKey' => 'status_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

public $hasAndBelongsToMany = array(
    'Veiculo' => array(
        'className' => 'Veiculo',
        'joinTable' => 'setores_veiculos',
        'foreignKey' => 'setor_id',
        'associationForeignKey' => 'veiculo_id',
        'unique' => 'keepExisting',
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
    )
);

A model de Veículo:
public $belongsTo = array(
    'TipoVeiculo' => array(
        'className' => 'TipoVeiculo',
        'foreignKey' => 'tipo_veiculo_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Status' => array(
        'className' => 'Status',
        'foreignKey' => 'status_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

public $hasMany = array(
    'Device' => array(
        'className' => 'Device',
        'foreignKey' => 'veiculo_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

public $hasAndBelongsToMany = array(
    'Setor' => array(
        'className' => 'Setor',
        'joinTable' => 'setores_veiculos',
        'foreignKey' => 'veiculo_id',
        'associationForeignKey' => 'setor_id',
        'unique' => 'keepExisting',
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
    ),
    'Condutor' => array(
        'className' => 'Condutor',
        'joinTable' => 'condutores_veiculos',
        'foreignKey' => 'veiculo_id',
        'associationForeignKey' => 'condutor_id',
        'unique' => 'keepExisting',
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
    )
);

Mesmo usando o Contain, não é retornado as relações com os Veículos.
Alguma sugestão?
Comment: Você certificou de que a propriedade `recursive` do model `Setor` está com valor 1?
Comment: Sim, já alterei o valor para 1, mas mesmo assim os veículos não são listados.  Pode ser um problema de convenção? Ou na tradução da model para o português?
Comment: Para isso, seu arquivo `bootstrap.php` precisa ser configurado por causa da mudança de singular para plural de nomes como setor, condutor e etc. Veja aqui: http://book.cakephp.org/2.0/en/development/configuration.html#inflection-configuration
Answer: Tente adicionar na linha acima do find este trecho de código:
$this->Setor->bindModel( array('hasMany' => array('Veiculo') ) );

Answer: Lá no seu controller eu vi você usar isso:
$options = array('conditions' => array('Setor.' . $this->Setor->primaryKey => $id));

Chame apenas assim:
$options = array('conditions' => array('Setor.veiculo_id' => $id));

Ou seja lá qual for o campo, mas você está chamando o índice do array como argumento de condição no find.
Prefira usar array('Model.campo' => 'Valor');
Comment: Olá, obrigado pela resposta. Mesmo assim não funcionou. Eu gostaria de obter os veículos relacionados no momento em que eu estou visualizando os dados dos setores. O estranho é que quando eu faço a mesma coisa pelo Veículo, os setores são retornados. O código está seguindo a mesma lógica. Isso realmente é um problema pra mim. Att.

Problema com HABTM no Cakephp 2.x


Como configurar o PickaDate do Materialize corretamente?

Question: Eu configurei o pickadate do Materialize numa página só que ele está ficando em inglês e quando eu saio e volto pra aba que tem o pickadate ele abre sem eu clicar no campo.
Inseri o materialize.min.css no cabeçalho e o jquery-2.1.1.min.js e materialize.min.js no fim da página.
Còdigo HTML:

  <input name="dataIni" type="text" class="dataIniFim">
  Data Inicial

  <input name="dataFim" type="text" class="dataIniFim">
  Data Final

Depois da importação dos arquivos `javascript no fim da página inseri esse código:
$('.dataIniFim').pickadate({
  selectMonths: true, // Creates a dropdown to control month
  selectYears: 15, // Creates a dropdown of 15 years to control year
  dateFormat: 'dd/MM/yy',
});

Código para teste: https://jsfiddle.net/Ly52g027/
Comment: Percebi que esse comportamento de abrir o datepicker automaticamente ao sair e voltar na aba acontece mesmo no site do materializecss
Comment: Consegues criar um jsFiddle ou montar o código na pergunta que reproduza o problema? Estás a usar algum router?
Comment: Criei o [Fiddle](https://jsfiddle.net/Ly52g027/).
Quando o foco tá no campo e eu saio e volto ele abre o `pickdate` automaticamente. Está em inglês e ignorando o padrão de formato que informei.
Answer: Em relação a idioma do datepicker, é somente sobrescrever as definições de inicialização. O fato de abrir automaticamente encontrei uma solução customizando o método close tirando o foco do campo:

$('.dataIniFim').pickadate({
  selectMonths: true,
  selectYears: 15,
  // Título dos botões de navegação
  labelMonthNext: 'Próximo Mês',
  labelMonthPrev: 'Mês Anterior',
  // Título dos seletores de mês e ano
  labelMonthSelect: 'Selecione o Mês',
  labelYearSelect: 'Selecione o Ano',
  // Meses e dias da semana
  monthsFull: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
  monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
  weekdaysFull: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
  weekdaysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
  // Letras da semana
  weekdaysLetter: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'],
  //Botões
  today: 'Hoje',
  clear: 'Limpar',
  close: 'Fechar',
  // Formato da data que aparece no input
  format: 'dd/mm/yyyy',
  onClose: function() {
    $(document.activeElement).blur()
  }
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />

  <form class="col s12">

        <input name="dataIni" type="text" class="dataIniFim">
        Data Inicial

        <input name="dataFim" type="text" class="dataIniFim">
        Data Final

  </form>

Caso queira que o datepicker feche com apenas 1 clique, pode adicionar também o seguinte trecho:
onSet: function( arg ){
    if ( 'select' in arg ){ //prevent closing on selecting month/year
        this.close();
    }
}

Comment: Funcionou perfeitamente. Eu não tinha colocado o `$(document).ready(function() {` talvez seja por isso que não estivesse funcionando a formatação da data.
Comment: @WendelRodrigues, na vdd não, pois o snippet já executa os códigos quando o `DOM` está carregado, eu coloquei por força do hábito mesmo rs
Comment: O problema foram os pontos que apontei na resposta mesmo


Auto Scroll a div without moving the whole page with velocity.js

Question: I would like to make an auto scroll across within a div but my codes scroll the whole page. How could I do so that it only scrolls in the div?
Codes:

    div class="logo">

    .
    .
    .

CSS:
.banner{
    position: absolute;
    width: 100%;
    height: 50px;
    margin-top: 5px;
    margin-bottom: 5px;
}

.logo{
    background-image: url(image.png) center no-repeat;
}

#container{
    width: 1800px;
    height: 1050px;
    position: absolute;
}

In JQuery:
var scrollWidth = $("#container").width();
var scrollHeight = $("#container").height();
$("#container").velocity("scroll", {
    axis: "x",
    duration: 10000,
    offset: scrollWidth
})
.velocity("scroll", {
    axis: "y",
    duration: 10000,
    offset: scrollHeight
});

The codes I have provided above will scroll together with the .banner, but I want to fixed the position when auto scroll the #container div. I'm using velocity.js to make the auto scroll.
Answer: If you are scrolling inside #container you must provide container property on your velocity animation, check Julian Shapiro demo
Another solution could be set banner's position to fixed instead of absolute


Where to include javascript instances in drupal

Question: I've added my.js using js injector module and updated .info file.
Where do I have to create those instances?
Sorry, I'm new with technology.
Answer: To Add any js file to your Drupal site , a good way is to create a custom module and add your js file there.Following points may help you.

Create one custom module of yours. Useful Link. https://www.drupal.org/developing/modules/7
In your module , create one folder name js.
Add your js file here.You can copy paste your js file also here.
Now in yourmodule file the following code to tell drupal about your js file.
function YOURMODULENAME_init(){

 drupal_add_js(drupal_get_path('module', 'YOURMODULENAME') . '/js/yourjs.js');

}

At the end enable your custom module.You are ready to go.


When is the canonical model of a curve nonsingular

Question: Let $O$ be a Dedekind domain with fraction field $K$. Let $C$ be a smooth projective geometrically connected curve of genus $g>1$ over $K$.
Let $p:X \to \mathrm{Spec} \ O $ be the canonical model of $X$. Assuming that $C$ has semi-stable reduction over $O$,  we have that $p$ is a stable curve.
When is $X$ regular?
One possible answer would be when the minimal regular model and the canonical model coincide.
But when does this happen? When there aren't any curves to be contracted on the minimal regular model. But I have a feeling this actually never happens...Why?
Answer: The minimal regular model coincides with the canonical one if and only if there is no vertical irreducible curve $C$ such that $C$ is smooth, rational, of self-intersection $C^2=-2$. When the minimal regular model is semi-stable, the condition $C^2=-2$ is equivalent to $C$ meets the other irreducible components at exactly two points (rational over the field of definition of $C$) or one point (quadratic over the field of definition of $C$).
In the other direction, given the stable model $X$, at any singular point $x$ of a close fiber $X_s$, the local ring $O_{X,x}$ is rather simple. Suppose $x$ is rational over $k(s)$, then
$$\widehat{O}_{X,x}\simeq \widehat{O}_{S,s}[[u,v]]/(uv-t^e), $$
where $t$ is a uniformizing element of the DVR $O_{S,s}$. Then $x$ is a regular point of $X$ if and only if $e=1$. Regular points of $X_s$ are regular in $X$.
Comment: Thanks for this. I'm still wondering though. Does it happen a lot that a semi-stable regular model is stable? So as you mention this means that the semi-stable regular model does not contain a vertical irreducible curve C such that C is smooth, rational and of self-intersection $C^2=-2$. I have a feeling that such a curve actually exists "almost always". Is my feeling right or wrong here?
Comment: @Fozad: the problem is how do you qualify "almost always" ? If you have a singular stable model, then you can construct a regular stable model (with a different generic fiber) whose close fiber is isomorphic to the given one. The converse holds true also. In fact, in some sense, regular stable model is the generic situation (in some moduli space, they correspond to sections over the base scheme which cut transversally the boundary).


Resque caching active record call

Question: I have a simple resque job that accepts a model id, fetches it, and then calls a method on the fetched item.
class CupcakeWorker
  @queue = :cupcake_queue
  def self.perform(cupcake_id)
    @cupcake = Cupcake.find(cupcake_id)
    @cupcake.bake
  end
end

I queue it from a controller action using the 'enqueue' method
def bake
  Resque.enqueue(CupcakeWorker, params[:cupcake_id])
  render :json => 'Baking...'
end

The job queues and executes correctly.  However if I modify the record's data in the database and proceded to queue the job again the operation doesn't execute using the new values.
I can only get it to fetch the new values if I restart the resque worker process.  Is resque caching the object?  Is there a way to ensure it refetches from the database every time the worker is called?
Answer: This answer is a little crude, but could work. You could call reload on the ActiveRecord model before doing any processing. This forces ActiveRecord to update the data.
The worker would then look like this:
class CupcakeWorker
  @queue = :cupcake_queue
  def self.perform(cupcake_id)
    @cupcake = Cupcake.find(cupcake_id).reload
    @cupcake.bake
  end
end

I'm afraid I don't know why Resque might be doing this, however. Try Sidekiq and see if you get better results.

Resque caching active record call


Route53 NS record not showing up

Question: I have this setup where I'm using a droplet to resolve some DNS requests so it acts as a nameserver for a subdomain: check.farm.test.com
The server works ok and receives traffic so, somehow, the NS record seems to be effective. The problem is that I cannot query it in dig or any other tool.
Here's my setup:
test.com.           NS      ns-312.awsdns-43.com.
check.test.com.     NS      ns.test.com
ns.test.com.        A       18.104.22.1682

My custom DNS server is sitting at 184.108.40.2062 and receives traffic when anything.check.test.com is accessed but dig check.test.com NS shows nothing. With +trace I get connection timed out; no servers could be reached. The G-suite toolbox dig tool shows:
opcode QUERY
rcode SERVFAIL
flags QR RD RA
;QUESTION
check.dnsleak.dnsadblock.com. IN NS
;ANSWER
;AUTHORITY
;ADDITIONAL```

Comment: Your droplet is answering queries, but it is not responding that the answer is authoritative for some reason (assuming the hostname in the G-suite toolbox dialog is the real one).  DNS problems are usually pretty easy to diagnose if you do not obfuscate the data.  If you do, you'll likely not get much help without including a ton of server side detail (like log messages, packet traces) if you don't include that information.  Without it, one can only guess.
Comment: I hope check.test.com is subdomain with its's own SOA record and not just a record within test.com.
Comment: Nope. I just added a NS type record following this guide: https://github.com/nhdms/dns-leak-server#step-2---add-a-and-ns-record-to-dns-management
Answer: The delegation NS and glue A records look to be ok:
;; AUTHORITY SECTION:
check.dnsleak.dnsadblock.com. 300 IN    NS      ns.dnsleak.dnsadblock.com.

;; ADDITIONAL SECTION:
ns.dnsleak.dnsadblock.com. 300  IN      A       18.104.22.168

Your custom DNS server (no small undertaking!), however, is not responding to queries properly.
Do not expect it to work in any reliable fashion until it responds in a standards compliant manner, and at least serves the minimal data that must exist in any zone (in addition to whatever data you actually want).
Bare minimum zone: SOA + NS at the zone apex.
Look at this response for example:
$ dig @220.127.116.11 check.dnsleak.dnsadblock.com NS +norec

; <<>> DiG 9.11.14-RedHat-9.11.14-2.fc31 <<>> @22.214.171.124 check.dnsleak.dnsadblock.com NS +norec
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19163
;; flags: qr; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;check.dnsleak.dnsadblock.com.  IN      NS

;; ANSWER SECTION:
check.dnsleak.dnsadblock.com. 60 IN     A       184.108.40.206

;; Query time: 1 msec
;; SERVER: 22.214.171.124#53(126.96.36.199)
;; WHEN: Thu Apr 23 20:06:55 UTC 2020
;; MSG SIZE  rcvd: 90

$

Some things are immediately apparent:

This server does not actually serve responses that are relevant to the questions it receives. Instead, it seems to always respond with an A record for the name the client sent!?
This misbehavior both leads to very strange situations where the answer is entirely irrelevant, and also causes side-effects like complete failure when looking up things that must exist like check.dnsleak.dnsadblock.com NS.
You have delegated the check.dnsleak.dnsadblock.com zone to this server, so it ought to be authoritative. But for whatever reason it doesn't set the aa flag as expected.

I would guess that there are many more issues remaining to be found, these are just the glaring issues that I noticed looking at the response to my first queries.
Overall, do consider the amount of work it will take to actually construct a working nameserver, also whether you could instead build your service on top of an already proven implementation.
Comment: Well, it was supposed to just grab the ip address of whatever resolver you have in place - hence why it only responds with A records. I thought I can get away with just a mere hundred lines of code and some DNS mashup. It works allright but fails when trying to provide a wildcard certificate due to NS record not showing up propely.
Comment: @RomeoMihalcea I would just add a note regarding the "it works alright" statement: It has one specific behavior that you desire (or something like it), but it lacks the foundational behaviors required for interoperability.

Route53 NS record not showing up


Are these definitions equivalent?

Question: In the book "Essential Linear Algebra with Applications", written by Titu Andreescu, there is the following definition:

As you can see, at the bottom of the image appears the symbol $\cdot$ about which nothing is said. Since I was creating notes about the section where this definition is, I decided to "formalize" this definition by doing the following:
Let $F$ be a field. We define an binary operation $\cdot:M_{m,n}(F)\times F^n\to F^m$ such that for $A=[a_{ij}]\in M_{m,n}(F)$ and $X=[x_i]\in {F^n}$ we have that $A\cdot X=Y\in F^m$ in which $Y=[y_i]$ with $y_i=\sum_{k=1}^na_{ik}x_k$. We obtain therefore a map $F^n\to F^m$ which sends $X$ to $A\cdot X$.
Although the definition I made seems to make sense, I'm afraid that this definition does not make sense. Since I intend to continue using the definition above, I would like to know if it is equivalent to that of the book and if it is correct taking into account the already known properties of the multiplication between matrix and vector.
Comment: The author uses $A\cdot X$ but it is the same thing as $A X$ above.
Comment: @Gribouillis But the author had not yet defined any operation using the symbol ⋅.
Comment: This symbol is often used for multiplication. You can write $2\cdot 3 = 6$, it is perfect. Here the author uses it for matrix product. He may have omitted the dot.
Answer: Yes, it is correct. Note that the operation mentioned by Titu Andreescu is simply the product of two matrices, in a case in which the second matrix has a single column.
Comment: But in this part of the book multiplication between matrices had not yet been defined .
Comment: What about the multiplication of a matrix by a vector?
Comment: He also didn't define the multiplication between vector and matrix.

Are these definitions equivalent?


Xamarin SQLite Connection With Lock error

Question: I'm using sqlite-net-pcl for Xamarin Forms / Xamarin Andriod the previous library SQLite.Net-PCL are crashing at run time because its no longer being maintained by it's author as mentioned here .
The problem that i'm facing with sqlite-net-pcl is when creating SQLiteConnectionWithLock

specific with ISQLitePlatform parameter
new SQLiteConnectionWithLock(ISQLitePlatform, new SQLiteConnectionString(path, true));

Parameter ISQLitePlatform are interface I tried to implement the interface but I didn't figure out the correct implementation
class SQLitePlatform : ISQLitePlatform
    {
        ISQLiteApi ISQLitePlatform.SQLiteApi => throw new System.NotImplementedException();
        IStopwatchFactory ISQLitePlatform.StopwatchFactory => throw new System.NotImplementedException();
        IReflectionService ISQLitePlatform.ReflectionService => throw new System.NotImplementedException();
        IVolatileService ISQLitePlatform.VolatileService => throw new System.NotImplementedException();
    }

Comment: I don't see `ISQLitePlatform` anywhere in that pkg's github repo?
Comment: I believe that what Jason was saying is that the constructor for this class `SQLiteConnectionWithLock` has only one parameter and it's the `SQLiteConnectionString` at least for the latest version **1.6.292**. `public SQLiteConnectionWithLock (SQLiteConnectionString connectionString);` what version do you have installed? @DevC
Comment: Thanks Jason & @Pinedax I just check the packages and I notice their another
 package named  **SQLite.Net.Async-PCL** I removed it and its works.
Comment: Could you please put the answer below, so we can resolve the question and its easily searchable
Comment: Inside SQLite.Net.Interop.ISQLitePlatform
Comment: I have version *1.6.292* too maybe I need to clear solution
Answer: I checked the Packages i had in my solution and delete everything related to this package SQLite.Net-PCL

Included:

1- SQLite.Net.Async-PCL
2 -SQLite.Net.Platform.XamarinAndroidN
Only keep this package sqlite-net-pcl and its works.


The inflection points of $f(x)=(x^2-4x+1)e^{-x}$

Question: I got the function $f(x)=(x^2-4x+1)e^{-x}$. The task is to find the inflection points. The correct answer is $x=4-\sqrt{5}$ and $ x=4+\sqrt{5} $. I got the second derivative to $f(x)$.
But when I equal it to zero I got $x=2+\sqrt{5}$ and $ x=2 - \sqrt{5} $.
What am I doing wrong?
Comment: Do you mean $f(x)=(x^2-4x+1)e^x$?
Comment: yes exactly. sorry forgot e^x
Comment: Please check that my edits are correct.
Comment: Yes it´s correct
Answer: We have
$$\eqalign{
  f(x)&=(x^2-4x+1)e^x\cr
  f'(x)&=(x^2-2x-3)e^x\cr
  f''(x)&=(x^2-5)e^x\ .\cr}$$
There are

zeros at $f(x)=0$, that is, $x=2\pm\sqrt3$;
stationary points at $f'(x)=0$, that is, $x=-1,3$;
inflection points at $f''(x)=0$, that is, $x=\pm\sqrt5$.

I can't explain where the answer of $x=4\pm\sqrt5$ came from, are you sure you copied the question correctly?
Edit.  As we can now see, $f(x)=(x^2-4x+1)e^x$ as originally posed in the question was not the function that the OP intended.
Comment: No they should not, not if you have the correct $f(x)$.  That is my point.
Comment: You can cleary see that $x=1,5$ are not solutions of $x^2 - 2 x - 3 = 0$.
Comment: the inflection points should be: x=4+sqrt(5) and x=4-sqrt(5)
Comment: I´m sure I´m right cause I got the answer book. But I can see you got wrong stationary points. They should be x=1 and x=5
Comment: @Kåba probably your answer book is wrong or you made a typo when writing the function equation.
Comment: When you derivative of the (x^2-4x+1)e^x is (6x-x^2-5)e^x. Hence the stationary points are x=1 and x=5
Comment: The derivative*
Answer: We have:
$$f(x) = P(x) e^x,$$
so $f'' = P'' e^x + 2 P' e^x + e^x P = e^x (2 + 4 x - 8 + x^2- 4x +1  ) = (x^2- 5) e^x$. Since $e^x > 0 $ for  $x \in (-\infty,\infty)$, the solution of $f''(x) = 0$ is given by $x^2 -5 =0 $, so the inflection points are $x_i = \pm \sqrt{5}$.
Hope this helps.
Cheers!
Edit: have a look of the graph of $f(x)$ here.
Comment: There must be a typo in your textbook, as @David points out in his answer. Otherwise you didn't write down the correct $f(x)$. Have a look to the link I have posted in my answer.
Comment: the inflection points should be: x=4+sqrt(5) and x=4-sqrt(5)
Answer: Edit: The answer below was written when the question asked about $f(x)=(x^2-4x+1)e^x$.

Consider the function $g(x)=(x^2-4x+1)e^{-x}$, a little minus sign away from $f(x)$.
The first derivative is $(-x^2+6x-5)e^{-x}$, so the stationary points are at $x=1$ and $x=5$.
The second derivative is $(x^2-8x+11)e^{-x}$. Thus the inflection points of $g(x)$ are at $x=4\pm\sqrt{5}$.
This may account for the reported book answer.
Comment: Thank you very much! this really helped. Saw I had put e^x instead of e^-x
Comment: You are welcome. The answers given to you were all dealt accurately with the question as given. I decided to reverse engineer, and find a plausible scenario that made the reported inflection points correct.


/me/activities request Microsoft Graph Explorer successful 200 response but empty "value":[ ]

Question: I am trying to retrieve the list of entries that can be seen in the Windows 10 timeline view via the User Activities API in Microsoft Graph.
I have selected the UserActivity.ReadWrite.CreatedByApp permission and am getting an HTTP 200 Success response, but the value returned is empty. I am signed in with a Work Account (O365)
https://graph.microsoft.com/beta/me/activities/recent?$top=5

When I look in the timeline view in Windows 10, I see a comprehensive history of activity. The machine is signed in using the same Work Account.
Any help greatly appreciated.
Comment: I am also suffering from this too, any update?
Answer: According to the documentation, only activities created by the current AppID will be returned:

The UserActivity.ReadWrite.CreatedByApp permission will also apply extra filtering to the response, so that only activities created by your application are returned. This server-side filtering might result in empty pages if the user is particularly active and other applications have created more recent activities. To get your application's activities, use the nextLink property to paginate.

I'd suggest dropping the $top parameter and following the nextLink URIs to see if your app's activities show up deeper down the stack.
Comment: Marc, what about when there is no `nextLink` in the result set?  My calls to both *https://graph.microsoft.com/beta/me/activities/recent* and *https://graph.microsoft.com/v1.0/me/activities/recent* are returning `{ "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(userActivity)",
    "value": [] }` with no `nextLink`.
Comment: If there is no `nextLink` then there are no additional pages of data.
Comment: Then I am confused as to what type of data the service should be returning.  What is an "activity?"  I am expecting to receive activities such as what sites I recently visited, files I may have uploaded or changed, etc.  Is this not what the API should be returning?
Comment: I think the app in this case would be SharePoint Online as I am calling the API via an SPFx web part (https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aad-tutorial).  If SharePoint Online is the app with which the activity is associated, shouldn't it be returning things my user has done recently in SharePoint Online (i.e. browsing sites, uploading files, etc.)?
Comment: It only returns activities originating from your App ID. see https://learn.microsoft.com/en-us/graph/api/resources/projectrome-activity?view=graph-rest-beta
Comment: Unless SP is creating activities (which I don't believe it is), then no.


How do I get the current path and add a condition in page.html.twig?

Question: I have the view page called "location/all" which contain all the map details.
I changed some CSS styles.

{% if 'location/all' in url %}

{% else %}

{% endif %}

I tried this code to check the condition, but every time it executes the else part.
Comment: see https://drupal.stackexchange.com/questions/239105/if-string-contains-substring-twig
Comment: in which twig file are you writing this code
Comment: themes\custom\themesname(XXXXX)\templates\system
inside page.html.twig
Comment: is it a suggestion for view-view.html.twig file
Comment: Got the answer
{% set url = url('') %}
{% if 'location/all' in url|render|render %}

{% else %}

{% endif %}
Answer: Try this
{% if 'location/all' in url('<current>')|render|render %}

Alternative solution would be to add the following to your THEMENAME.theme
function THEMENAME_preprocess_page(&$vars) {
  $vars['path'] = \Drupal::service('path.current')->getPath();
}

and use this in your page.html.twig
{% if 'location/all' in path %}

Comment: wouldn't [`path('')`](https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates#path) be better to use? it gets the path instead of the entire URL. either way it's an alternative to `url`
Answer: GOt the Answer
{% set url = url('<current>') %}
{% if 'location/all' in url|render|render %}

{% else %}

{% endif %}

Thanks for your support
Comment: it gives the path alias. what about the base url? for example I want 'taxonomy/term/1' not the word 'students' which I used as alias.
Answer: Try with this code.

{% if '/location/all' == url('<current>') %}

{% else %}

{% endif %}

Comment: HI jeetendra,
thanks for comment its not reflecting
Answer: Try with this code
{% set current_url = url('') %}
{% if 'location/all' in current_url|render|render %}

{% else %}

{% endif %}


Space in batch commands (del and taskkill)

Question: I have a problem using del and taskkill.
del D:\New Folder.exe

I tried changing the code to this:
del D:\"New Folder.exe"

That didn't work
So I tried this:
del "D:\New Folder.exe"

Still not working. But this is working:
del "D:\New Folder"

The problem is I must remove the .exe to make this work.
And I have this problem too:
taskkill /F/IM New Folder.exe

Comment: Do you get error messages from any of those commands?  Do you have a file or folder called `New Folder.exe` on your `D:` drive?  Also, please ask any unrelated questions you have in a separate question here on StackExchange.
Comment: hi that problem has been fixed tnx i will post them on there i didnot know .
Answer: Your del "D:\New Folder.exe" should work just fine...I've tested it just now multiple times.  If it isn't working then you need to post the error code/message you are getting.
Same goes for your taskkill command, and your access denied in the attrib command.
The last two could possibly be related to UAC (user account control) issues, but we won't know if you don't post the actual error.  Make sure you are running the batch file from an Administrative level command prompt.
Oh, and update your questions tags with more than just batch if you would.  Include the specific OS at a minimum.
Comment: HI TNX   ITS WORKING NOW(NOT YET TEST THE TASKKILL BUT I THINK THAT WILL WORK TO) ABOUT ATTRIB even when i use Administrative level i have the same problem i test that on win 7 and win xp (vmware)but its not working perhaps its because some of that file i am trying to unhide them are visble or not exist!
Comment: You would need to post the existing attribs of the file along with whatever error code you are getting.
Comment: attrib -h -S C:\*.* i am getting access denid to the files in root of c drive


Powerapps - unable to get response from Flow

Question: I am building a PowerApp that triggers a PowerAutomate flow.
Upon the trigger, the PowerAutomate flow runs successfully. I have set it up so it ends with a 'Respond to a PowerApp or flow' action so that I can return variables into PowerApps.
However, in PowerApps, it seems that nothing is returned.
Here is the code to trigger the flow. It should set 'Success'(PowerApp variable) to the value of 'success'(PowerAutomate output)
Set(Success,
    testflow.Run(
        input1,
        input2
    ).success
);

The flow runs successfully and returns success=True

However, when I evaluate the variable, we see that it remains empty suggesting that the output from PowerAutomate was empty.

Any idea why this is so? I've been struggling with this for a couple of days now.
Thank you!
Comment: you have to set flow().success. You need to select the result variable
Comment: Yes, with testflow.Run(input1, input2).success, the result variable success is selected.
Comment: perfect let me add thiis as answer, please accept and upvote it. Shall give me some points :)
Answer: you just have to add flow().success and this shall give your your result variable with it's value.
For your case it shall be
 testflow.Run(input1, input2).success

Answer: I found out what was going wrong. It turns out the fields were passed from Flows to PowerApps, just that they were of the incorrect format so PowerApps never populated the variable.
So even if I define a variable as Boolean earlier in the flow, I cannot just pass it through the 'Respond to a PowerApp or flow' action as a variable. I need to redefine it as a Boolean within the action for it to work.
I kind of understand the logic but it's pretty unintuitive by Microsoft since on the Flows side everything is fine.
Following picture shows some testing I did.
Answer: Try removing the .success.
Also try the following:
ClearCollect(colResponse,
    testflow.Run(
        input1,
        input2
    ).success
);


how to create Rtl ViewPager for locale?

Question: How to create Rtl ViewPager with both En and Arabic locale?
I am using this code :
https://github.com/diego-gomez-olvera/RtlViewPager
but i cannot implement both locale.
Comment: More info.Add your code.
Answer: Look at this line in RtlViewPager's source. It controls whether the RtlViewPager is in right-to-left mode.
If you extend RtlViewPager and override this method to always return true, the English locale should also appear as RTL.
For example:
public class AlwaysRtlViewPager extends RtlViewPager {
    public AlwaysRtlViewPager(Context context) {
        super(context);
    }

    public AlwaysRtlViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected boolean isRtl() {
        return true;
    }
}

Just replace your usages of RtlViewPager with this sub-class and you should get the desired result.
Comment: Sir , how to create any Fragment in this code : [link] (https://github.com/diego-gomez-olvera/RtlViewPager)   ,     can you help me?
Answer: You don't need any third party library. Android jetpack recently added new UI component called ViewPager2 which supports RTL Layout.
https://developer.android.com/jetpack/androidx/releases/viewpager2
The below answer talks about Migration guide and sample github app to support RTL view pager.
https://stackoverflow.com/a/59558911/651377

how to create Rtl ViewPager for locale?


Looking for a faster way of searching for a property in a List of classes

Question: Below is the class I'm using to represent a tree structure, for displaying files and folders of a game's archive format.
public class DirNode : INotifyPropertyChanged
{
     public String Name { get; set; }
     public int Index { get; private set; }
     public int FileIndex { get; private set; }
     public int Type { get; private set; }
     public List<DirNode> Directories { get; set; }
     public List<FileNode> Files { get; set; }

     public DirNode(String n, int index, int type, int fi)
     {
           Name = n;
           Directories = new List<DirNode>();
           Files = new List<FileNode>();
           Index = index;
           Type = type;
           FileIndex = fi;
     }
}

Below is a method of the class that I'm currently using to parse path strings into the tree. It worked well enough when I was only loading one archive, but when trying to "mount" multiple archives, the inefficiency certainly shows
 public void AddPath(String[] path, int index, int fileIndex)
        {
            if (path.Length > 1) //It's a Folder;
            {
                bool found = false;
                int i = 0;
                while (i < this.Directories.Count && found == false)//search to see if this folder already exists
                {
                    if (this.Directories[i].Name == path[0])
                    {
                        found = true;
                        String[] newPath = new String[path.Length - 1];
                        Array.Copy(path, 1, newPath, 0, newPath.Length);
                        this.Directories[i].AddPath(newPath, index,fileIndex);
                        return;
                    }

                    i++;
                }
                if (found == false) //new item
                {
                    DirNode dn = new DirNode(path[0], -1, 0,fileIndex);
                    this.Directories.Add(dn);
                    String[] newPath = new String[path.Length - 1];
                    Array.Copy(path, 1, newPath, 0, newPath.Length);
                    this.Directories[this.Directories.Count - 1].AddPath(newPath, index,fileIndex);
                }
            }
            else if (path.Length == 1) //a file!
            {
                DirNode fn = new DirNode(path[0], index, 1,fileIndex);
                this.Directories.Add(fn);
                return;
            }
            else
            {
                //really no reason why we should be here.
                return;
            }
        }

I know BinarySearch requires a pre-sorted list, which won't work, as the lists aren't sorted until after the tree is assembled. But it is, ultimately sorted, so a Hash won't work either. If anybody has any ideas, I'd love to hear them.
Of course, if anybody knows of a virtual implementation of the .NET DirectoryInfo class, that would likely even be better.
Comment: Somewhat. But the good thing is: you do **not** need to sort every time, if you pay attention to always insert the new item at the right position so that the list is (and stays) sorted at all times. And as I wrote, finding the insert position comes for free when you do the binary search for finding the existing item! This will drastically improve performance.
Comment: And to elaborate on the performance hit: currently you search for the item, which takes linear time on each insert, so for n inserts you have roughly O(n^2) to perform (worst case). Sorting an already sorted list is no more expensive than this, so yes, your impression is wrong when doing it as you have been doing it. However, my proposal will find the item or the insert position in O(log2(n)), so that the overall performance will be O(n*log2(n)), which is much cheaper overall in terms of performance.
Comment: Why don't you store the items in Directories and Files sorted at insertion time, so that you can actually perform a binary search on each directory level? The BinarySearch on the List class will give you the index if found and the index complement (use the `~` operator) when not found, so that you know the index where the new item needs to be inserted right away.
Comment: I was under the impression that sorting every time an object is added to the list, would be a serious performance hit, compared to doing it once at the end. Am I wrong?
Answer: Why don't you store the items in Directories and Files sorted at insertion time, so that you can actually perform a binary search on each directory level? The BinarySearch() on the List class will give you the index if found and the index complement (use the ~ operator) when not found, so that you know the index where the new item needs to be inserted right away.
Something like this (not tested in any way, just hacked down in the editor):
Class for comparing the name of two DirNodes:
internal class DirNodeNameComparer: IComparer<DirNode> {
    public static readonly DirNodeNameComparer Default = new DirNodeNameComparer();

    public int Compare(DirNode x, DirNode y) {
        return string.Compare(x.Name, y.Name);
    }
}

Your AddPath method updated to keep a sorted representation:
public void AddPath(String[] path, int index, int fileIndex)
{
    if (path.Length > 1) //It's a Folder;
    {
        DirNode dn = new DirNode(path[0], -1, 0, fileIndex);
        int i = this.Directories.BinarySearch(dn, DirNodeNameComparer.Default);
        if (i < 0) {
            i = ~i;
            this.Directories.Insert(i, dn);
        }
        String[] newPath = new String[path.Length - 1];
        Array.Copy(path, 1, newPath, 0, newPath.Length);
        this.Directories[i].AddPath(newPath, index,fileIndex);
        return;
    }
    else if (path.Length == 1) //a file!
    {
        DirNode fn = new DirNode(path[0], index, 1, fileIndex);
        int i = this.Directories.BinarySearch(fn, DirNodeNameComparer.Default);
        this.Directories.Insert(~i, fn); // really Directories?
        return;
    }
    else
    {
        //really no reason why we should be here.
        return;
    }
}

Comment: Thanks for the feedback, and happy coding! :)
Comment: Okay, wow. So if a match is found, it returns the index, but if it doesn't, doing a binary NOT on the return, gives you the index of the sorted position in the List - and inserting something at that index, pushes everything down by one to make room for it. That's brilliant - thank you very much!

Oh, and - yeah I eventually discovered everything could be done simpler with just the one list, using a "type" parameter, Just never got around to deleting "Files", or giving "Directories" a more accurate name. lol


android.content.ActivityNotFoundException: Unable to find explicit activity class com.example.collegeroamer.NavigationDisplayActivity

Question: I have a kotlin/xml file in android studio. I want to use an image button to go to my activity image display screen but whenever I select the location and destination and then click the navigate button the app stops working
The error
Process: com.example.collegeroamer, PID: 10761
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.collegeroamer/com.example.collegeroamer.NavigationDisplayActivity}; have you declared this activity in your AndroidManifest.xml?
                                                                                at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2065)
                                                                                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1727)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:5320)
                                                                                at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:728)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:5278)
                                                                                at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:709)
                                                                                at android.app.Activity.startActivity(Activity.java:5664)
                                                                                at android.app.Activity.startActivity(Activity.java:5617)
                                                                                at com.example.collegeroamer.MainActivity.onCreate$lambda$0(MainActivity.kt:26)
                                                                                at com.example.collegeroamer.MainActivity.$r8$lambda$v-UY7dqHrHnhJePGV2sXZapuvnU(Unknown Source:0)
                                                                                at com.example.collegeroamer.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
                                                                                at android.view.View.performClick(View.java:7448)
                                                                                at android.view.View.performClickInternal(View.java:7425)
                                                                                at android.view.View.access$3600(View.java:810)
                                                                                at android.view.View$PerformClick.run(View.java:28305)
                                                                                at android.os.Handler.handleCallback(Handler.java:938)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:223)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7656)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

My codes
Android Manifest.xml
<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:dataExtractionRules="@xml/data_extraction_rules"
    android:fullBackupContent="@xml/backup_rules"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.CollegeRoamer"
    tools:targetApi="31">
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity.kt
package com.example.collegeroamer

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageButton
import android.widget.Spinner

class MainActivity : AppCompatActivity() {
    private lateinit var navigateButton: ImageButton
    private lateinit var currentLocationSpinner: Spinner
    private lateinit var destinationSpinner: Spinner
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navigateButton = findViewById(R.id.navigateButton)
        currentLocationSpinner = findViewById(R.id.currentLocationSpinner)
        destinationSpinner = findViewById(R.id.destinationSpinner)

        navigateButton.setOnClickListener {
            val selectedLocation = currentLocationSpinner.selectedItem.toString()

            val intent = Intent(this, NavigationDisplayActivity::class.java)
            intent.putExtra("selected_location", selectedLocation)
            startActivity(intent)
        }
    }
}

NavigationDisplayActivity.kt
@file:Suppress("UNUSED_EXPRESSION")

package com.example.collegeroamer

import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity

class NavigationDisplayActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_display)
        val locationImage = findViewById<ImageView>(R.id.locationImage)

        val selectedLocation = intent.getStringExtra("selected_location")

        val imageResourceId = getImageResourceIdForLocation(selectedLocation ?: "")
        locationImage.setImageResource(imageResourceId)
    }

    private fun getImageResourceIdForLocation(location: String): Int {
        return when (location) {
            else -> R.drawable.default_image
        }
    }
}

Answer: You should declare the NavigationDisplayActivity in the AndroidManifest.xml as below.
    <application
    ...
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".NavigationDisplayActivity" >
    </activity>
</application>