laravel relation owner model

Question: I have Table like
TABLE USERS
  id
  username
  email
  password
  created_at
  updated_at
  created_by
  updated_by

i want to select users and join with this user to get the username by foreign key with created_by
Model Users
class users extends Model
{
  protected $table = 'users';

  public function user()
  {
     return $this->belongTo('App\Users','created_by');
  }
}

I want to know the user who created this user. I store users id on column created_by.
How to do this ?
Comment: Doesn't `users::with("user")->find()->user` give you what you need?
Comment: e.g i have 2 user A and B. But user B is created by A.I want to select user B to show this user B has created by A.name
Comment: `$A = users::with("user")->find(A)` and then `echo $A->name." was created by ".$A->user->name;` ? Isn't that what you need?
Answer: You can use with() function to get what you want, in your case you can have:
$users = user::with('user')->get();

For more information you can visit: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
Answer: Model names must be capitalized and singular.
class User extends Model
{
  protected $table = 'users';

  public function creatorUser()
  {
     return $this->belongTo('App\Users','created_by');
  }
}

$creatorUser = User::findOrFail($someUserId)->creatorUser;

laravel relation owner model


Arduino HC-05 Bluetooth module disconnects when sending data

Question: I'm new to Arduino. I'm trying to build a program to control a breadboard through Arduino using the bluetooth module HC-05. At the moment I don't have anything on the breadboard and I'm just trying to test the connection. This is what I've done so far:
I put the module on the breadboard and I've paired it with the computer. When it's paired, the red led starts blinking slowly. I've connected the bluetooth Rx to Arduino Tx and Arduino Rx to bluetooth Tx following this tutorial: http://playground.arduino.cc/Learning/Tutorial01
I've also implemented both Java and Arduino programs following that tutorial. Here they are:
JAVA
public class Arduino extends PApplet{

public void connect(){
    String[] serials = Serial.list();
    Serial port = new Serial(this, Serial.list()[0], 9600);
    port.write('H');
    port.dispose();
}

ARDUINO
 void setup() {
  Serial.begin(9600);
  Serial.println("Start");
}

void loop() {
  if(Serial.available()){
   int a = Serial.read();
   Serial.print(a);
 }
}

The Java part should send the letter H to Arduino and Arduino should detect that and print it on the Serial monitor. But what actually happens is that I send data, and the led on the HC-05 starts blinking faster (which means the connection is lost). Why does that happen? I'm pretty confused. For the communication I'm using the port COM6 and COM7. It depends on how it connects. To see what port to use I just run the Java program: if the port is not correct, it will just get stuck and send nothing.
Any help is appreciated. Thanks!
Answer: In the end, I've solved this problem by removing this line of code:
port.dispose();

It would never work with it because I was getting rid of the connection. I don't know what I was thinking at the time I did that. That was very silly of me.
Answer: Ok so I had this problem.
If you are using the L293D motor shield, you'll be running the arduino of the same power supply, which I think must affect the power output the the bluetooth HC05 module.
Take out the jumper plug on the L293D motor shield, and run the arduino of a separate power source (e.g PP3 battery) and the problem disappears, OK.


How to bundle local typescript files into main bundle using Rollup

Question: I am trying to create an npm module that can be used in the browser.
I'm using typescript and rollup.
My tsconfig.json is:
{
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "lib",
    "strict": true,
    "rootDir": "src"
  }
}

and my rollup.config.js is:
import typescript from "@rollup/plugin-typescript";

export default {
  input: "src/index.ts",
  output: {
    dir: "lib",
    format: "iife",
  },
  plugins: [typescript()],
};

Inside src/index.ts I have the following:
// src/index.ts
import log from './log'

const myFn = () => {
 ...myFn code
}

My issue is that in the bundle, I get the following:
// lib/index.js bundle
var log_1 = require("./log");

When I actually want to bundle the log file inside the main lib/index.js.
How can I do this with Typescript and rollup?
Note: I have tried to add outFile (ts docs) but that is not supported by "@rollup/plugin-typescript".
Do I have to do the tsc compile myself and then the rollup bundle?
Comment: I'm still looking for an answer to this but if anyone comes across this question, I actually moved to Webpack, and it was much simpler.
Comment: having a similar issue here it seems :/ https://stackoverflow.com/questions/71796571/how-to-replace-global-variable-with-relative-import-using-rollup No option for webpack unfortunately
Answer: Rollup requires the TypeScript compiler to generate ES Modules in order to properly bundle your code. You'll need to change the module format to "ESNext" instead of "CommonJS" in your tsconfig.json or change the @rollup/plugin-typescript configuration in your Rollup config:
typescript({ module: "ESNext" })

As of rollup/plugins#788, you will get a warning if this is not configured correctly.

@rollup/plugin-typescript: Rollup requires that TypeScript produces ES Modules. Unfortunately your configuration specifies a "module" other than "esnext". Unless you know what you're doing, please change "module" to "esnext" in the target tsconfig.json file or plugin options.
Comment: For me it still produces a warning: `Plugin typescript: @rollup/plugin-typescript: Rollup requires that TypeScript produces ES Modules. Unfortunately your configuration specifies a "module" other than "esnext". Unless you know what you're doing, please change "module" to "esnext" in the target tsconfig.json file or plugin options.`
And this is despite putting override for `module` in plugin options: even tried wraping in `compilerOptions`, no dice. Warning is gone once I change `module` in `tsconfig.json`.
Comment: I had the same error, but still rollup complains for not JS files after fixing this https://stackoverflow.com/questions/71796571/how-to-replace-global-variable-with-relative-import-using-rollup if someone has any insight please


Your search yielded no results in Drupal 7.12. I have index 100%. In my local it is working but on the staging server it is not working

Question: Your search yielded no results in Drupal 7.12. I have index 100%. In my local it is working but on the staging server it is not working.
    Check if your spelling is correct.
    Remove quotes around phrases to search for each word individually. bike shed will often show more results than "bike shed".
    Consider loosening your query with OR. bike OR shed will often show more results than bike shed.
Comment: I got the solution. It is a unicode issue. I have added the patch....
Answer: In your search module locate "x{d800}", and replace it with "x{e000}".
This issue has been fixed in the latest version of Drupal.


Erro com foreign key de outro banco

Question: Estou tentando colocar foreign key relacionadas com tabelas de outro banco de dados (Estou realizando testes e as vezes preciso excluir o banco principal).
Entretanto esta apresentando os seguintes erros:

Mensagem 1763, Nível 16, Estado 0, Linha 93 Não há suporte para
  referências de chave estrangeira em todos os bancos de dados. Chave
  estrangeira 'municipios.dbo.Estado'. Mensagem 1750, Nível 16, Estado
  1, Linha 93 Não foi possível criar a restrição ou o índice. Consulte
  os erros anteriores.

Tabela de Estado:
CREATE TABLE Estado (
    CodigoUf INT          NOT NULL,
    Nome     VARCHAR (50) NOT NULL,
    Uf       CHAR    (2)  NOT NULL,
    Regiao   INT          NOT NULL,
    PRIMARY KEY (CodigoUf),

constraint fk_Uf_Regiao foreign key (Regiao) references Regiao(Id)
);

Tabela que estou fazendo a foreign:
create table Clientes(
ID_int          int identity,
ID              AS RIGHT('000000' + CAST(ID_int AS VARCHAR(6)), 6) PERSISTED,
Loja            varchar(4),
Tipo            varchar(4),
CNPJ_CPF        varchar(14),
IE              varchar(14),
Nome            varchar(60),
nome_fantasia   varchar(60),
E_mail          varchar(60),
Telefone        varchar(20),
Endereco        varchar(30),
Bairro          varchar(30),
Cod_Mun         varchar(7),
Municipio       varchar(30),
Uf              int,
CEP             varchar(8),
Bloqueado       varchar(3) default 'NAO',
Forma_pagamento int,
data_cadastro   datetime,
ult_compra      datetime,
primeira_compra datetime,
Media_Atrasos   int,
Tabela_preco    varchar(3),
Tp_entrega      varchar(1),
grp_vendas      varchar(6),

constraint pk_Clientes primary key (CNPJ_CPF),
constraint fk_Clientes_UF foreign key (uf) references [municipios].[dbo].[Estado](CodigoUf) ON DELETE NO ACTION ON UPDATE CASCADE,
constraint fk_Clientes_Mun foreign key (Cod_Mun) references [municipios].[dbo].[Municipio](Cod_Mun) ON DELETE NO ACTION ON UPDATE CASCADE,
constraint fk_Clientes_Tabela foreign key (tabela_preco) references tabela_precos(id),
constraint fk_Clientes_grp foreign key (grp_vendas) references grupo_vendas(id)
)
go

Answer: Marcos, o texto em português da mensagem de erro 1763 não deixa claro qual é a causa:
"Não há suporte para referências de chave estrangeira em todos os bancos de dados"
Em "todos os bancos de dados"?!
--
Mas eis o texto original da mensagem de erro 1763:
"Cross-database foreign key references are not supported. Foreign key '%.*ls'"
Agora ficou claro qual o motivo do erro, certo? Em suma, não é possível referências de chave estrangeira entre bancos de dados.

Erro com foreign key de outro banco


Compare 2 images using C#

Question: Can we compare 2 images of different resolutions and colour.
Comment: when I read that, I thought you were a troll making fun of the OP... and then I realized you were the OP. \*face palm\*
Comment: Sure... scale them down to the same resolution and then "compare" them... whatever that means.
Answer: I think it can be done.
have a look at the below link to find if it helps ur requirment if not atleast should be useful for startup for ur req
Image Comparison using C#

Compare 2 images using C#


An interesting limit: $\lim_{n\rightarrow\infty} \left(\frac{n^{n-1}}{(n-1)!}\right)^{\frac{1}{n}}$

Question: It was a new contributor's question. I answered, got my -1 again and then deleted. Then I asked myself. Then gave it up again. Actually I was gonna ask a different question NOW. When I pressed ask a question, to my surprise, the question I intended to ask yesterday was in the memory!
I wanted to evaluate the following limit by logarithmic limit rule:
$$\lim_{n\rightarrow\infty} \left(\frac{n^{n-1}}{(n-1)!}\right)^{\frac{1}{n}}=\exp\left(\lim_{n\rightarrow\infty}\frac{(n-1)\ln n-\ln (n-1)!}{n}\right)=\exp\left(\lim_{n\rightarrow\infty}-\frac{1}{n}\sum_{k=1}^n\ln(\frac{k}{n})\right)$$
Then I observed a Riemann sum of an indefinite integral inside so that the limit is
$$\exp\left(-\int_0^1\ln xdx\right)=\exp\left((x-x\ln x\vert_0^1)\right)=e.$$
Is my solution correct?  Can you suggest another way? Stirling's approximation formula is excluded.
Comment: Instead of the n-root take the ratio of consecutive terms. You get the result much easier. This is pretty standard think to do and is related to root test and ratio test for series.
Comment: This is a fine way to do it, modulo the fact that $\ln x$ goes to $-\infty$ as $x\to 0^+,$ so simple Riemann sums don't always converge to the integral. Essentially, you have the "lower" Riemann sum converges to your limit, but the "upper" Riemann sum is undefined. So you will need some fancy footwork to get the argument to work. If you know Stirling's approximation, you could use that instead. https://en.wikipedia.org/wiki/Stirling's_approximation?wprov=sfti1
Comment: See https://math.stackexchange.com/q/1885090/42969 for a rigorous argument that $\frac{1}{n}\sum_{k=1}^n\ln(\frac{k}{n})$ converges to $\int_0^1 \ln(x) dx$.
Comment: @OliverDíaz Another way for this limit?
Answer: It is correct up to two things.
First, you should not write $\lim_{n \to +\infty}$ before the existence of the limit is proved. You have to start with
$$\Big(\frac{n^{n-1}}{(n-1)!}\Big)^{1/n} = \Big(\frac{n^{n}}{n!}\Big)^{1/n} = \exp\Big(n \ln(n) - \frac{1}{n} \sum_{k=1}^n \ln(k)\Big) = \exp\Big(- \frac{1}{n}\sum_{k=1}^n \ln(k/n)\Big).$$
Second, the theorem form the convergence of Riemann sums applies to continuous functions on $[0,1]$. Here, the function $\ln$ is continuous on $]0,1]$ only. Yet, it is increasing, so you can add inequalities
$$\int_{(k-1)/n}^{k/n} \ln x dx \le \frac{1}{n} \ln(k/n) \le \int_{k/n}^{(k+1)/n} \ln x dx.$$
over all $k \in \{1,\ldots,n\}$, to get a lower bound and an upper bound and prove the existence of the limit.
Other method :
$$\frac{(k+1)^{k+1}/(k+1)!}{k^k/k!} = \frac{(k+1)^k}{k^k} = (1+1/k)^k \to e \text{ as  } k \to +\infty,$$
so an application of Ces`ar'o lemma (take logarithms) yields
$$\Big(\frac{n^{n}}{n!}\Big)^{1/n} \to e \text{ as  } k \to +\infty.$$
Comment: I am EEE engineer. Sorry.
Answer: By the Stirling formula:
$$\dfrac{n^{n-1}}{(n - 1)!} = \dfrac{n^n}{n!} \sim \dfrac{e^n}{\sqrt{2 \pi n}}$$
then :
$$\left(\dfrac{n^{n-1}}{(n - 1)!}\right)^{\frac{1}{n}} \sim \dfrac{e}{(2 \pi n)^{1/2n}} \to e$$
Comment: Nice! But Stirling's formula is exluded. Thanks.
Comment: I don't give -1.


Split up a memorystream into bytarray

Question: Im trying to split up a memorystream into chunks by reading parts into a byte array but i think i have got something fundamentally wrong. I can read the first chunk but when i try to read rest of memorystream i get index out of bound even if there are more bytes to read. It seems that the issue is the size of the receving byte buffer that need to be as large as the memorystrem. I need to convert it into chunks as the code is in a webservice.
Anyone knows whats wrong with this code
fb.buffer is MemoryStream
  long bytesLeft = fb.Buffer.Length;
                fb.Buffer.Position = 0;
                int offset =0;
                int BUFF_SIZE = 8196;

                while (bytesLeft > 0)
                {
                    byte[] fs = new byte[BUFF_SIZE];

                    fb.Buffer.Read(fs, offset, BUFF_SIZE);
                    offset += BUFF_SIZE;
                    bytesLeft -= BUFF_SIZE;
                }

Comment: Actually, you don't even need to use `Read` here; just use `GetBuffer` and then in the loop, `Buffer.BlockCopy` the data from the backing buffer to the smaller buffers
Answer: offset here is the offset into the array. It should be zero here. You should also be looking at the return value from Read. It is not guaranteed to fill the buffer, even if more data is available.
However, if this is a MemoryStream - a better option might be ArraySegment<byte>, which requires no duplication of data.
Comment: Thanks , stupid misstake. Seen this 'not guaranteed to fill buffer' before and always wondered what it means. Is the read operation some type of random process or?
Comment: @klashagelqvist On a `NetworkStream` it pretty much is. If not enough data has arrived yet to fill the buffer, but the connection hasn't been closed either, it will only fill part of the buffer with the available data, and return. But I don't think such partial reads can happen on a MemoryStream.
Comment: @klashagelqvist indeed, as CodeInChaos notes, MemoryStream probably won't bite you here, but that is an implementation detail. I strongly suggest following the formal Stream API, which *only* guarantees "none" or "some"
Answer: Please look at this code for Stream.Read from MSDN from a glance - you shouldn't be incrementing offset - it should always be zero.  Unless, of course, you happen to know for a fact the exact length of the stream in advance (therefore you would create the array the exact size).
You should also always grab the amount of bytes read from Read (the return value).
If you're looking to split it into 'chunks` do you mean you want n 8k chunks?  Then you might want to do something like this:
List<byte[]> chunks = new List<byte[]>();
byte chunk = new byte[BUFF_SIZE];
int bytesRead = fb.Buffer.Read(chunk, 0, BUFF_SIZE);
while(bytesRead > 0)
{
  if(bytesRead != BUFF_SIZE)
  {
    byte[] tail = new byte[bytesRead];
    Array.Copy(chunk, tail, bytesRead);
    chunk = tail;
  }
  chunks.Add(chunk);
  bytesRead = fb.Buffer.Read(chunk, 0, BUFF_SIZE);
}

Note in particular that the last chunk is more than likely not going to be exactly BUFF_SIZE in length.

Split up a memorystream into bytarray


Values passed to controller change to null

Question: I have come across this for the 1st time. I have passed a value from my view to controller, which generated an error. After placing breakpoints across the action that is retrieving it I found that the value is being retrieved but when passing from the post action to the get action it is changing to null. Any idea whats causing this?
My code as follows:
<code> [HttpPost]
    [ValidateInput(false)]
    public ActionResult reservation_step_1(string x)
    {
        string val = x;
        return RedirectToAction("reservation_step_2", "Home", new { val = val });
    }

    [HttpGet]
    public ActionResult reservation_step_2(string val)
    {
        string rat = val;

        string a = rat.Substring(0, rat.Length - 16);
        string b = a.Substring(2);

        return View();
    }
</code>
Comment: What is the value of `x`?
Comment: x is the value being passed from the view, It is a value from a selected checkbox
Comment: The code you have shown works fine.
Comment: That seems very odd  as I have just tried it again. The value I tried with is "R 400.00(per day)" This value varies but once I tried running it again it gave me a null error
Comment: You have invalid characters (the `<` and `>`) - and that is why I asked you want the value of `x` was :)
Comment: `` itself is HTML tag, you should sanitize it first before passing as string parameter.
Comment: Even after removing invalid characters before passing to the controller I am having the same issue
Answer: Based on the comments to the original post, it sounds like you need to add [ValidateInput(false)] to the reservation_step_2 method if you're passing HTML about.
Comment: Hi Daniel, I've tried that and there still seems to be no luck
Comment: Hmm, I'm running exactly what you've posted and the value is populated. Do you have any action filters or annotations on the controller?


Delete element in C

Question: I allocated a pointer to pointer in C in this way:
    double **dataset = (double **)malloc(CHUNK * sizeof(double *));

    if (dataset == NULL) {
        printf("Something went wrong in load_dataset(), memory allocation failed!");
        exit(1);
    }

    for (int i = 0; i < CHUNK; i++) {
        dataset[i] = (double *)malloc((d + 1) * sizeof(double));
        if (dataset[i] == NULL) {
            printf("Something went wrong in load_dataset(), memory allocation failed!");
            exit(1);
        }
    }

Then I read from a file CHUNK points with which I fill the dataset.
After I process the first point I have to delete it from dataset and move back of 1 position every element. suppose that dataset contain pointer to pointer that point to 1-dimensional point with ids from 1 to 50. After some stuff, it should contain point from 2 to 50 (obviously it need a realloc at the end).
I tried this:
    CHUNK--;
    for (int i = 0; i < CHUNK; ++i) {
        printf("id: %.2f\n", dataset[i][0]);
    }
    printf("------------\n");
    memmove(dataset[0], dataset[1], CHUNK * sizeof(double *));
    dataset = realloc(dataset, CHUNK * sizeof(double *));
    if (dataset == NULL) {
        printf("Something went wrong in initialize_cluster(), memory allocation failed!");
        exit(1);
    }

    for (int i = 0; i < CHUNK; ++i) {
        printf("id: %.2f\n", dataset[i][0]);
    }
    printf("-----------\n");

It doesn't work. This delete the first element but doesn't move all the element. The print show:
id: 1.00
id: 2.00
id: 3.00
id: 4.00
id: 5.00
id: 6.00
id: 7.00
id: 8.00
id: 9.00
id: 10.00
id: 11.00
id: 12.00
id: 13.00
id: 14.00
id: 15.00
id: 16.00
id: 17.00
id: 18.00
id: 19.00
id: 20.00
id: 21.00
id: 22.00
id: 23.00
id: 24.00
id: 25.00
id: 26.00
id: 27.00
id: 28.00
id: 29.00
id: 30.00
id: 31.00
id: 32.00
id: 33.00
id: 34.00
id: 35.00
id: 36.00
id: 37.00
id: 38.00
id: 39.00
id: 40.00
id: 41.00
id: 42.00
id: 43.00
id: 44.00
id: 45.00
id: 46.00
id: 47.00
id: 48.00
id: 49.00
------------
id: 2.00
id: 3.00
id: 4.00
id: 5.00
id: 6.00
id: 7.00
id: 8.00
id: 9.00
id: 10.00 <------Here it seems to
id: 10.00 <------stop to move
id: 11.00
id: 12.00
id: 13.00
id: 14.00
id: 15.00
id: 16.00
id: 17.00
id: 18.00
id: 19.00
id: 20.00
id: 21.00
id: 22.00
id: 23.00
id: 24.00
id: 25.00
id: 26.00
id: 27.00
id: 28.00
id: 29.00
id: 30.00
id: 31.00
id: 32.00
id: 33.00
id: 34.00
id: 35.00
id: 36.00
id: 37.00
id: 38.00
id: 39.00
id: 40.00
id: 41.00
id: 42.00
id: 43.00
id: 44.00
id: 45.00
id: 46.00
id: 47.00
id: 48.00
id: 49.00
-----------

Comment: I have understood nothing.
Comment: what didn't you understand? The result must be that the first element is eliminated
Comment: @chqrlie points are d-dimensional, + 1 is the ids of each point. I have a dataset in a file that is something like point_id value_1 value_2... value_d
Comment: I think I got it: points are d-dimensional, you allocate `(d + 1)` elements because the first element is the ID. Printing this is as a float with 2 decimals is misleading.
Comment: `memmove(dataset[0], dataset[1], CHUNK * sizeof(double *));` I think you mean `(CHUNK - 1) * sizeof(double *)`, otherwise you move one more pointer than expected
Comment: @chqrlie, yes it my fault, i'll correct it. But anyway the problem is memmove seems not working
Comment: @DavidRanieri is my fault again, I omitted a line, at the beginning there is a ''CHUNK--''. I'm going to edit
Comment: @DavidRanieri: not only should it be `(CHUNK - 1) * sizeof(double *)`, the arguments should be `&dataset[0]` and `&dataset[1]` or equivalent expressions.
Comment: @chqrlie why `&dataset[0]` and `&dataset[1]` and not `dataset[0]` and `dataset[1]`
Comment: @LucaMarchio: because you are moving the contents of the `dataset` array. You could also write: `memmove(dataset, dataset + 1, (CHUNK - 1) * sizeof(*dataset));` Just like `realloc`, `memmove` and `memcpy` are confusing and error prone, even for savvy programmers I must admit, I recommend writing a loop instead, that will potentially outperform the `memmove` call: `for (int i = 0; i < CHUNK - 1; i++) dataset[i] = dataset[i + 1];`
Comment: Do you know if computationally is the same? In this sense should I use memmove or the for loop?
Comment: @LucaMarchio: you can accept the answer by clicking n the grey checkmark below its score.
Answer: To update the dataset and drop the first point, you can move the pointers one position using memmove but your code is incorrect: you pass the addresses of the first 2 points, instead of the addresses of the pointers inside the array of pointers.
You should write:
    free(dataset[0]);  // free the first point
    memmove(&dataset[0], &dataset[1], (CHUNK - 1) * sizeof(*dataset));
    dataset[CHUNK - 1] = NULL;  // clear the pointer to avoid duplicate pointers

There is no need to reallocate the array, especially if you read one more point at the end (into dataset[CHUNK - 1]). If you are meant to reallocate the array, you should not consider reallocation failure an error:
    double **new_dataset = realloc(dataset, (CHUNK - 1) * sizeof(*dataset));
    if (new_dataset != NULL) {
        // realloc succeeded, use the new pointer
        dataset = new_dataset;
    } else {
        // realloc failed: the block was not reallocated and is still valid
        // keep using the original pointer
    }

Also be aware that after the shift there are only CHUNK - 1 points available so the printing code must stop at CHUNK - 1. Using a variable for the number of points seems a better approach.
Note that just like realloc, memmove and memcpy are confusing and error prone, even for savvy programmers I must admit, I recommend writing a loop instead, that will potentially outperform the memmove call:
    free(dataset[0]);  // free the first point
    for (int i = 0; i < CHUNK - 1; i++) {
        dataset[i] = dataset[i + 1];
    }
    dataset[CHUNK - 1] = NULL;  // clear the pointer to avoid

EDIT from your comments and code update, it seems CHUNK is indeed a variable. It is confusing to use all capitals for variable names. All capitals are idiomatic for macros representing a fixed quantity, such as an array length.
Comment: @LucaMarchio: no there is no need to free `dataset`. Either `realloc` succeeded and the return value (possibly identical to `dataset`) must be used or it failed and returned `NULL` and the original value of `dataset` is still valid and can be used for the rest of the code. It is unlikely for `realloc` to fail at reducing the length of an allocated object, but the C Standard allows it.  Note that `realloc` is quite error prone and has caused many software flaws in the past 40 years.

Delete element in C


Showing that $A = \{\tan x \mid x \in (-\frac{\pi}{2}, \frac{\pi}{2})\}$ is not bounded, without calculus.

Question: I have to show that $A = \{\tan x \mid x \in (-\frac{\pi}{2}, \frac{\pi}{2})\}$ is not bounded.
Since $\tan\colon (-\frac{\pi}{2}, \frac{\pi}{2}) \to \mathbb R$ is surjective $\Rightarrow \tan((-\frac{\pi}{2}, \frac{\pi}{2})) = \mathbb R$, we know that $\mathbb R$ is not bounded $\Rightarrow A$ not bounded. Is this correct? Any other solutions not involving calculus?
Comment: Your conditional statements are true, but I'm not sure about *correctess*. I'm afraid there might be circularity here. How do you know that $\text{im}(\tan)=\Bbb R$?
Comment: Your reasoning is circular.
Comment: What is your definition of $\tan$?
Comment: Its six x/cos x
Comment: Well since tan has codomain R and is surjective Im(tan) must be R, How to show that R is the domain of tan...than i dont know
Comment: @phi How do you know that your function $\tan$ is surjective?
Comment: well for every y in R the equation tan x = y has at least a solution in (-pi/2, pi/2), x = arctan y + kpi
Answer: Use the definition of $\sin, \cos$ and $\tan$ to show that the range of $\tan$ is $\mathbb{R}$! So $\cos x$ is the rpojection of the respective point on the unit circle onto the $x-$axis, $\sin x$ - onto the $y-$axis (you get this respective point $P_x$ by rotating the point $P_0(1,0)$ counterclockwise by $x$ radians). Take then the vertical line that is parallel to $y$-axis and contains $P_0(1,0)$. Take any point $P_{y_0}(1,y_0)$ from that line. Connect this point $P_{y_0}$ with (0,0). The segment you've got will intersect the unit circle at some point $P_\alpha$. It can easily be shown (it involves some obvious manipulations with triangles (similar triangles or whatever)) then that $y_0$ is equal to $\tan \alpha$, where $\alpha\in(-\frac\pi 2, \frac\pi 2)$ is the measure of the angle made up be the segment we've just drawn and the positive part of the $x$-axis. So since our $y_0$ was arbitrary, this shows that the range of $\tan$ is indeed the whole set of real numbers.
Answer: For any $a \in (0,\frac{\pi}{2})$, the mid point of $a$ and $\frac{\pi}{2}$ also belongs to $(0,\frac{\pi}{2})$.
Let $t = \tan(\frac{a}{2})$, we have:
$$\tan(\frac{\frac{\pi}{2}+a}{2})
=\tan(\frac{\pi}{4} + \frac{a}{2}) = \frac{1+t}{1-t}
= \frac{(1+t)^2}{1-t^2} = \frac{1 + \frac{2t}{1+t^2}}{\frac{1-t^2}{1+t^2}}
= \frac{1 + \sin a}{\cos(a)} \ge 2\tan(a)
$$
So start with $\tan(\frac{\pi}{4}) = 1$, we get
$$\begin{align}
\tan(\frac{3\pi}{8}) &= \tan(\frac{\frac{\pi}{2} + \frac{\pi}{4}}{2}) \ge 2 \tan(\frac{\pi}{4}) = 2\\
\implies\tan(\frac{7\pi}{16}) &= \tan(\frac{\frac{\pi}{2} + \frac{3\pi}{8}}{2}) \ge 2 \tan(\frac{3\pi}{8}) \ge 2^2\\
&\;\vdots\\
\implies \tan(\frac{\pi}{2} - \frac{\pi}{2^n}) &=
\tan(\frac{\frac{\pi}{2} + (\frac{\pi}{2} - \frac{\pi}{2^{n-1}})}{2}) \ge 2 \tan(\frac{\pi}{2} - \frac{\pi}{2^{n-1}}) \ge 2^{n-2}\\
\end{align}$$
This implies $\tan(x)$ is unbounded above in $(0,\frac{\pi}{2})$. Since $\tan(-x) = -\tan(x)$, this also implies $\tan(x)$ is unbounded below on $(-\frac{\pi}{2},0)$.
Answer: Well, it seems to me that the easiest approach is to show that there exists a left neighborhood of $\pi/2$  where $\sin$ is larger than, say, $1/2$, and $\cos$ is not bounded away from zero. How do you do that? The answer depends on your definition of the goniometric functions sin and cos. The ``baby'' approach implies continuity, so it leans on some hidden calculus.
But you could also show that the inequality $$\frac{\sin x}{\cos x} > K$$ is solved in a left neighborhood of $\pi/2$ by putting $\cos x = X$, $\sin x = Y$, and using the fact that $X^2+Y^2=1$.
Anyway, I doubt that you have a definition that allows you to work with these inequalities without using any calculus idea.
Comment: I guess Calculus was developed to answer this kind of questions
Comment: Probably. And much depends on your level of satisfaction about rigor. I remember that my high school book claimed that the tangen function is clearly unbounded, since the denominator approaches zero while the numerator approaches one. And we, the students, were completely satisfied by this "proof".


Multi Page Selection VBO

Question: Is there a way to achieve multi-page selection. Everytime I go to the next page, my selection gets lost. Any chance to keep my selection over multiple pages?
Answer: There is a patch for same feature https://www.drupal.org/node/1207348

Multi Page Selection VBO


Correct way to Redirect based on browser user-agent?

Question: I am building a Spring MVC based application where I want to redirect user's to specific portion of the site based on their browser.
I am using a Filter applied to /site/home.jsp to read the User-Agent to determine the browser type.
HttpServletRequest req = (HttpServletRequest) request;
String uaString = req.getHeader("User-Agent");

Further I want to redirect users as below:

Firefox: redirect to /site/firefox/home.jsp
IE: redirect to /site/ie/home.jsp
Unknown: redirect to /site/UnsupportedBrowser.jsp

My confusion is what is the correct way to redirect the user from my BrowserDetector filter?
1) Simply redirect the user?
resp.sendRedirect("/AppName/site/ie/home.jsp");

2) Use an HTTP Temp redirect?
resp.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
resp.setHeader("Location", "/AppName/site/ie/home.jsp");

3) Server side redirect?
RequestDispatcher request_Dispatcher=request.getRequestDispatcher("/ie/home.jsp");
request_Dispatcher.forward(request,response);

4) Any other correct way?
Comment: What are you trying to achieve by sniffing the browser server-side?
Comment: I need to do perform some browser-specific business logic... Firefox users go through a specific flow and IE through different... Trust me... it's a use-case.
Comment: But...there's no way to _actually_ tell what browser is being used to view your site...UA sniffing is just a (slightly) educated guess at best.
Comment: I agree... but since this is going to be an internal site... UA spoofing is not an issue...
Answer: Idea number 3 is probably a bad idea, as it will most likely result in you having to perform this check for every request, which is inefficient (only slightly, but small inefficiencies can mount up).
Idea's number 1 & 2 are also not the best approach, because both will result in a Temporary redirect (307) response, wheras what you probably want is a permanent redirect (301). This is because the browser in question will always be the same - FF and IE never share there list of permanent moves, so even if both browsers are used by the same client machine this will not cause a problem. You should use 301 for reasons of, again, efficiency - if the browser always goes directly to the correct place, it is less work for your server to do.
To sum up, I think idea 2 is the closest, but you should use this instead:
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
resp.setHeader("Location", "/AppName/site/ie/home.jsp");

Keep in mind that User-Agent strings can be spoofed and cannot be 100% relied upon.
This is my personal opinion, YMMV...
Answer: First and foremost: DON'T DO SERVER-SIDE BROWSER SNIFFING!
Server-side browser sniffing is a bad idea for a bunch of different reasons, but here's just a few of them:

There are hundreds of different browsers and that number changes all the time, so detecting them all is a race you can't win
Search engines really don't like it when you give them different stuff than you give to real browsers (and they do test it)
It doesn't reliably tell you the capabilities of the user's browser because they may have spoofed their user agent string (for various reasons) or may have other things installed that increase or decrease the capabilities their indicated browser has natively

A much better approach is to use Progressive Enhancement or Graceful Degradation.
That being said, one option that works more reliably is to do the sniffing in the browser and then redirect them client-side accordingly. Modernizr will tell you what capabilities their browser has, and from there you can decide what to serve them.


Set parent as overflow hidden to cut off animation but keep showing child element

Question: I have two menus between which you can toggle using a switch. Every menu item has a dropdown that shows when you click on a menu item.
The problem is when clicking the switch, an animation is shown for the transition between the two menus (slide in and slide out). I want to keep the sliding animation only inside the menu element, so I used overflow-y: hidden; to make this happen. However this also cuts off my dropdown menus since they are a child of the parent that has overflow: hidden.
I made a codepen showing the problem here:
https://codepen.io/twan2020/pen/jOMMoom
When you switch the menu, you can see the animation overflows the menu container.
If I use below code the animation looks nice, but the menu doesn't open anymore when clicking on an item.
.categoriemenu .categorielijst {
  width: 100%;
  margin-bottom: 0px;
  display: flex;
  justify-content: space-evenly;
  position: relative;
  overflow-y: hidden;
}

How can I fix this?
I tried setting the product-menu (which is the class of the dropdown menus) to position:fixed but this breaks the styling, my menu also has variable heights so I would like to know if there is an easier solution to this?
Comment: @CBroe Got it to work by setting `overflow-y:hidden` only for the duration of the animation. Thank you
Comment: maybe you want to consider writing a self answer with your solution to avoid having the answer only in comments. see https://stackoverflow.com/help/self-answer
Comment: There are solutions/workarounds for ["Popping Out of Hidden Overflow"](https://css-tricks.com/popping-hidden-overflow/), but those are rather complex, and depend on specific circumstances. I'm guessing your best bet here is to apply `overflow-y: hidden` only for the duration of your menu switch animation, and reset it to the default after.
Comment: @CBroe I didn't think about that. Sounds like a great solution. I will try that.
Answer: I fixed it by setting a timer on the overflow-hidden for the duration of the animation like this:
$('.toggle-switch input').on('change', function() {
    if ($('input[name=switch]:checked', '.toggle-switch').val() == 1) {
        $(".categorielijst").css('overflow-y', 'hidden');
        $("#menu1").addClass('animate__slideInUp');
        $("#menu2").addClass('animate__slideOutUp');
        $("#menu1").css('display', 'flex');
        $("#menu1").removeClass('animate__slideOutDown');
        $("#menu2").removeClass('animate__slideInDown');
        setTimeout(function() {
            $(".categorielijst").css('overflow-y', 'visible');
        }, 600)
    } else if ($('input[name=switch]:checked', '.toggle-switch').val() == 2) {
        $(".categorielijst").css('overflow-y', 'hidden');
        $("#menu1").css('position', 'absolute')
        $("#menu1").addClass('animate__slideOutDown');
        $("#menu2").addClass('animate__slideInDown');
        $("#menu2").css('display', 'flex');
        $("#menu1").removeClass('animate__slideInDown');
        $("#menu2").removeClass('animate__slideOutUp');
        setTimeout(function() {
            $(".categorielijst").css('overflow-y', 'visible');
        }, 600);
    }
});

It's not perfect because if you spam click the toggle it will still sometimes kind of glitch and overflow out of the container but if you click like a normal person it works fine.


Issue with running input and if/else code in a single code

Question: Please don't hate me if something like this has been asked, I couldn't find a similar problem.
I'm learning python, and I'm trying to get a small piece of code to work in IDLE shell 3.9.7 like this
>>> mark=int(input("enter mark"))
    if mark>=90:
        print("excellent")
    elif mark<90 and mark>=75:
        print("good")
    elif mark<75 and mark>=40:
        print("average")
    else:
        print("fail")

with the idea that you enter the mark, then it prints one of the statements without having to run the input code then the if/elif/else statements afterwards (I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately.) However, when I run the code, I enter the mark and nothing happens. I've tried different indentation and putting the input bit at the end, but it just asks for the mark and then nothing happens. I'm not sure what I'm doing wrong, as the app that I'm using to learn has it parsed exactly like this. Appreciate any help.
Answer:
(I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately

Probably you want a function, like this:
def foo(mark: str) -> None:
    if mark>=90:
        print("excellent")
    elif mark<90 and mark>=75:
        print("good")
    elif mark<75 and mark>=40:
        print("average")
    else:
        print("fail")

that you can call this way in the shell:
>>> foo(int(input("Enter your mark: ")))
10
fail

Answer: Try this it should work just had to put it in a for loop
while True:
    mark=int(input("enter mark: "))
    if mark>=90:
        print("excellent")
    elif mark<90 and mark>=75:
        print("good")
    elif mark<75 and mark>=40:
        print("average")
    else:
        print("fail")


Console Application on VB2008 - Integer.TryParse Method Error

Question: I am using Integer.TryParse Method to validate whether user input is a numeric or non-numeric in my program.
1)if the user input is numeric, the program will then proceed and validate that the user input is range from 0 to 9.
2)If the user is enter a non-numeric input, the program will display the message "invalid input" and ask user to start from beginning.
Following is my coding:
 Sub Main()
    Dim sevenNumbers As Integer()
    sevenNumbers = New Integer(6) {}
    Dim index As Integer
    Dim number As Integer
    Dim reEnter As Boolean = True

    Console.WriteLine("Please enter 7 integers: ")
    Console.WriteLine("<ATTENTION: FROM 0 TO 9 ONLY>")
    Console.WriteLine()

    While reEnter
        For index = 0 To 6

            Console.WriteLine("Please enter the integer no." & "{0}" & " : ", index + 1) 'Prompt user to enter 7 integers.
            sevenNumbers(index) = Console.ReadLine() 'The 7 integers are stored in an array.

            If Integer.TryParse(sevenNumbers(index), number) Then
                While sevenNumbers(index) < 0 Or sevenNumbers(index) > 9
                    Console.WriteLine("<invalid input>")
                    Console.WriteLine()
                    Console.WriteLine("------------------------------------------")
                    Console.WriteLine("<Please re-enter the 7 integers>")
                    Console.WriteLine("------------------------------------------")
                    Console.WriteLine()
                    reEnter = True
                    Exit For
                End While

            Else
                Console.WriteLine("<invalid input>")
                Console.WriteLine()
                Console.WriteLine("------------------------------------------")
                Console.WriteLine("<Please re-enter the 7 integers>")
                Console.WriteLine("------------------------------------------")
                Console.WriteLine()
                reEnter = True
                Exit For

            End If

            reEnter = False

        Next
    End While

End Sub
However, when a user enter a non-numeric input, the program can't continue and shows an error that forced to close.
i tried this
Sub Main()
        Dim num As Integer
    Console.Write("enter num:")
    Dim input = Console.ReadLine

    If Integer.TryParse(input, num) Then
        Console.WriteLine("valid. num = " & num)
    Else
        Console.WriteLine("invalid")
    End If
End Sub

it does works and i am wondering which part of my coding is wrong??
Thank for help!!
Answer: Your two samples of code are different.  In your second attempt, you do this:
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then

The above code reads into a variable called input that will be a String (because Console.ReadLine returns a String).  Then, you try to parse the string into a number.
However, in your original code, you do this (some lines omitted for clarity):
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
...
sevenNumbers(index) = Console.ReadLine()

In this case, you are reading into a variable that you have explicitly declared to be an Integer.  If the user types "abc" then the conversion will fail at this point - you won't even get to the TryParse because you can't complete the innput.
Instead of reading to an integer, you need to read into a String variable and then parse that value into an Integer (as you did in your second code).
You could have spotted this yourself by taking note of the line that the error actually occurs on when debugging: you should note that the program crashes on the ReadLine, not on the TryParse.
Comment: Yes, i have changed sevenNumbers to String instead of using integer and it does works! Thank you!
Answer: Um. This line:
sevenNumbers(index) = Console.ReadLine()

Is storing whatever text has been read into an array of Integers. If it's compiling, then by the time you reach any later code, you're too late to control the conversion. It's already happened.
Maybe sevenNumbers should be String()?
(You really ought to turn on OPTION STRICT and OPTION EXPLICIT - it should find problems like this for you when it compiles the code)
Comment: Thank you for the tips and now i am able to run my program!


Drush bootstrap level error

Question: Im running onto some issues with Drush. I worked with php 5.3 and after upgrading to 5.5, i ran into some issues and decided to downgrade my PHP version back to 5.3. Now im running into the issue that Drush isnt working anymore.
<code>Command cache-clear needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment [error]
to run this command.
The drush command 'cc all' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                     [error]
Hint: This error often occurs when Drush is trying to bootstrap a site that has not been installed or does not have a configured
database.

Drush was attempting to connect to :
  Drupal version    : 7.28
  Site URI          : http://default
  Database driver   : mysql
  Database hostname : 127.0.0.1
  Database username : root
  Database name     : drupal_practice2
  Default theme     : garland
  Administration theme: garland
  PHP configuration :
  Drush version     : 4.5
  Drush configuration:
  Drush alias files :
  Drupal root       : /var/www/drupal
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

You can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command
line or $options['uri'] in your drushrc.php file.
</code>
Ive been searching on google for almost 3 days now and re-installing my computer would be a lot faster. I have lots of data so i dont want to re-install.
Someone that can help me with the solution?
Comment: You were using Drush version 7 with Php 5.3? Right?
Comment: I believe you should update Drush version, Check this out http://docs.drush.org/en/master/install/#drupal-compatibility
Comment: Yes, please update Drush to 8.1.17. Grab the phar file from https://github.com/drush-ops/drush/releases and follow the instructions on http://docs.drush.org/en/8.x/install/ We don't have time to debug any issues with an ancient Drush versions.
Comment: Add also report which version of PHP that is used in the CLI - run `php -v` in terminal.
Answer: Your problem is that Drush is running the PHP version that you have installed for your hosting environment (and Drush's own php.ini). You need to get Drush to run its own PHP that it installs with.
What host are you running on? If it is Windows then open a console and type set. That will show you the environment variables that you are using for your account. If there is a PHP variable in there, note it's contents and delete it by issuing the following command in the command windows: set PHP=
If that doesn't work set it back to what is was before. Any other platform I cannot help you with.
Also check this post: Modifying the PHP or PHP configuration that drush runs under
Answer: Before doing anything time-consuming just go to the root of the directory and then run the command again.
Run from here at Drush console: /var/www/drupal

Drush bootstrap level error


Passing maps into Jenkins pipeline jobs

Question: I have a Jenkins Job DSL seed job that calls out to a couple of pipeline jobs e.g.
pipelineJob("job1") {
    definition {
        cps {
            script(readFileFromWorkspace('job1.groovy'))
        }
        parameters {
            choiceParam('ENV', ['dev', 'prod'], 'Build Environment')
         }
    }
}
pipelineJob("job2") {
    definition {
        cps {
            script(readFileFromWorkspace('job2.groovy'))
        }
        parameters {
            choiceParam('ENV', ['dev', 'prod'], 'Build Environment')
         }
    }
}

job1.groovy and job2.groovy are standard Jenkinsfile style pipelines.
I want to pass a couple of common maps into these jobs.  These contains things that may vary between environments, e.g. target servers, credential names.
Something like:
def SERVERS_MAP = [
'prod': [
        'prod-server1',
        'prod-server2',
      ],
'dev': [
        'dev-server1',
        'dev-server2',
      ],
]

Can I define a map in my seed job that I can then pass and access as a map in my pipeline jobs?
Answer: I've come up with a hacky workaround using the pipeline-utility-steps plugin.
Essentially I pass my data maps around as JSON.
So my seed job might contain:
def SERVERS_MAP = '''
{
  "prod": [
    "prod-server1",
    "prod-server2"
  ],
  "dev": [
    "dev-server1",
    "dev-server2"
  ]
}
'''

pipelineJob("job1") {
    definition {
        cps {
            script(readFileFromWorkspace('job1.groovy'))
        }
        parameters {
            choiceParam('ENV', ['dev', 'prod'], 'Build Environment')
            stringParam('SERVERS_MAP', "${SERVERS_MAP}", "")
         }
    }
}

and my pipeline would contain something like:
def serversMap = readJSON text: SERVERS_MAP
def targetServers = serversMap["${ENV}"]
targetServers.each { server ->
   echo server
}

I could also extract these variables into a JSON file and read them from there.
Although it works, it feels wrong somehow.
Comment: I've done very similar things in my Jenkins pipelines. Essentially it works around the strings-only limitation of env vars by converting objects to strings to save in the env, then re-converting them back out elsewhere. It's not "wrong", it's what gets the job done given the constraints.
Answer: You can use string parameter pass the Map val, downstream read it as json format.
UPSTREAM PIPELINE
timestamps{
node("sse_lab_CI_076"){ //${execNode}
    currentBuild.description="${env.NODE_NAME};"

    stage("-- regression execute --"){
        def test_map =
        """
            {
                "gerrit_patchset_commit": "aad5fce",
                "build_cpu_x86_ubuntu":     [
                    "centos_compatible_build_test",
                    "gdb_compatible_build_test",
                    "visual_profiler_compatible_build_test"
                ],
            }
        """
        build(job: 'tops_regression_down',
            parameters: [string(name: 'UPSTREAM_JOB_NAME',
                                value: "${env.JOB_BASE_NAME}"),
                        string(name: 'UPSTREAM_BUILD_NUM',
                                value: "${env.BUILD_NUMBER}"),
                        string(name: 'MAP_PARAM',
                                value: "${test_map}"),
                        ],
            propagate: true,
            wait: true)
    }
}

}
DOWNSTREAM PIPELINE
timestamps{
node("sse_lab_inspur_076"){ //${execNode}
    currentBuild.description="${env.NODE_NAME};"
    stage('--in precondition--'){
        dir('./'){
            cleanWs()
            println("hello world")
            println("${env.MAP_PARAM}")
            Map result_json = readJSON(text: "${env.MAP_PARAM}")
            println(result_json)
        }
    }
}

}

Passing maps into Jenkins pipeline jobs


Print middle word in a string. C programming

Question: I need help on code that print out a middle word of string.
First Example:

Input:  My name is Alex
Output: either name or is <-- is the middle

Second Example:

Input:  Hello. I Need help on my coding.
Output: Help <-- middle word

Hopefully someone can help me out. I will try to follow up.
Answer: Here's an idea:

Split string into words
Now that you know how many words there are, decide how to handle the even case
Print the decided words

You can use strtok() for the splitting, and perhaps assume that a "typical" sentence has not more than 50 words, each being no longer than 16 characters. Just to simplify the code.
Comment: @trumpetlicks I wrote it in parallel. It happens a lot. I also think it describes a simpler and clearer solution, your "check to see if there are any more tokens" action is not very well described in my opinion, and never needed in mine.
Comment: @trumpetlicks To be frank, unwind's answer has more clarity than yours. This is probably why his answer has been upvoted more.
Answer: The full code :
#include <stdio.h>
#include<string.h>
#include<conio.h>
int main(){
char str[] = "good men to come to the aid of their country";
char delims[] = " ";
char *result;
char word[100][100];
int loop=1;
result = strtok(str, delims );
strcpy(word[0],result);
while( result != NULL ) {
    loop++;

    strcpy(word[loop],result);
     result = strtok( NULL, delims );

   }
int mid=loop/2-1;
// to print the middle element
printf("word is %s \n",word[mid+1]);
getch();
return 0;

Comment: The only thing I would add here is a case that checks to see if size%2 == 1 (i.e. the case where there is only 1 middle word weresus 2 middle words)
Comment: i add all the header but i cant compile and run? whats wrong?
Comment: 13 C:\Users\Fufu\Documents\middle.cpp `input' undeclared (first use this function)
  (Each undeclared identifier is reported only once for each function it appears in.)
Comment: input string means the string of which you want to find the mid element.
Comment: output i got is 0 . (
can we use something like
printf("ENTER A STRING...: ");
gets(str);
or is there another easy way to do? sorry for the trouble.
Comment: i got the output for every word.


Is it possible to choose a number so that the function is continuous at the origin?

Question: Is it possible to choose a number $\alpha$ so that the function $f : R^{2} \rightarrow R$ with
$f(x,y) = \lbrace \; \frac{(2x - y)^2}{x^2 + y^2}, \;(x,y) \neq (0,0); \\ \qquad \quad \qquad \alpha, \qquad (x,y) = (0,0) \;\rbrace$
is continuous at the origin?
I tried subbing $y=mx$ in but I can't seem to come to any convincing conclusions.
Any help is greatly appreciated!
Answer: Try to compute the limit along the lines $y=2x$ and $y=0$.
For $y=2x$, $f(x,2x)=0 \to 0$ as $x\to 0$.
For $y=0$, $f(x,0)=4 \to 4$ as $x\to 0$.
In order to have continuity at $(0,0)$ the above limits should be equal to $\alpha$, therefore such $\alpha$ does not exist.
P.S. In this case for $y=mx$, $f(x,mx)=(2-m)^2/(m^2+1)$. So you have a infinite choices fo $m$ to prove that the function can not be continuously extended at $(0,0)$.
Answer: There is no well defined limit. To show this consider the two paths that approach the origin.
Take $(x(t),y(t)) = (t,0)$. By substituting this in and taking $t\to 0$ we obtain
$$\lim_{t\to 0} \frac{(2t - 0)^2}{t^2 + 0^2} = \lim_{t\to 0}\frac{4t^2}{t^2} = 4$$
while on the other hand by taking $(x(t),y(t)) = (t,t)$ we get by taking $t\to 0$ the result
$$\lim_{t\to 0}\frac{(2t-t)^2}{t^2 + t^2} = \lim_{t\to 0}\frac{t^2}{2t^2} = \frac{1}{2}$$
and thus we have two paths approaching the origin which give different values. This means that it is not a removable singularity (i.e. no $\alpha$ can be selected to make it continuous at the origin).


Como usar debug sip no asterisk?

Question: No software Asterisk, é possível efetuar um debug de um numero de telefone somente? sem ele ser peer do do meu server?
sei que existe os comandos:
    sip set debug peer 1000
    sip set debug ip 172.16.0.100

de modo similar ao debug é possivel fazer o controle do verbose para somente um usuario?
caso não seja possível existe algum modo padronizado para fazer testes desse tipo em produção? para filtrar chamadas incomming
Answer: Olá, tentarei responder as perguntas por partes.
1- No software Asterisk, é possível efetuar um debug de um numero de telefone somente? sem ele ser peer do do meu server?
Você pode filtrar pelo IP deste peer, como você já sabe, mas se isto não for suficiente você pode utilizar o wireshark e filtrar a capturas por chamadas voip, por ip de origem, destino, conteúdo do pacote (filtrando por peer, por exemplo) etc.
Sugestão de leitura: Wireshark - Voip Calls
2- de modo similar ao debug é possível fazer o controle do verbose para somente um usuario?
Sim, mas pelo log ao invés do CLI. Você pode filtrar as chamadas para somente um usuário pelo log do asterisk, desde que o log do tipo 'verbose' esteja habilitado no /etc/asterisk/logger.conf
Exemplo:
full => notice,warning,error,verbose,dtmf,fax

A partir do asterisk 11 toda chamada possui um identificador (call-id) que possibilita o rastreamento dela no log. Exemplo:
[2017-04-11 09:17:02] VERBOSE[50999][C-00000620] pbx.c: Executing [1234@CONTEXTO-PADRAO:1] NoOp("SIP/PEERQUALQUER-00000507", "### RECEBENDO CHAMADA DE 1234567890 PARA 1234 ###") in new stack

Na linha acima é possível ver que o asterisk recebeu uma chamada do peer PEERQUALQUER para a extensão 1234. Todas as linhas desta chamada tem o identificador [C-00000620] que pode ser filtrado com um 'grep', por exemplo:
grep "C-00000620" /var/log/asterisk/full

Sugestão de leitura: Call Identifier Logging
3- caso não seja possível existe algum modo padronizado para fazer testes desse tipo em produção? para filtrar chamadas incomming
Eu utilizo os dados do arquivo de log para filtrar e analizar fluxo chamadas entrantes. Quando quero mais detalhes, principalmente de sinalização, utilizo o sngrep para analise em tempo real das mensagens, diálogos e transações SIP. Utilizo o wireshark para análise de arquivos pcap quando não preciso de análise em tempo real.
Answer: Você pode utilizar o SNGREP para monitorar direto no terminal tem uma saída muito detalhada, ela for projetada para monitorar trafego SIP.
É uma ferramenta leve e muito util no dia a dia, segue o gitbub do projeto.
https://github.com/irontec/sngrep

Como usar debug sip no asterisk?


PCA with zero and high correlation in data

Question: How would the eigen values look like when we apply PCA to a dataset with zero correlation between variables and when there is very high correlation between variables
Comment: this looks like a homework question.  what have you learned from your initial research?
Answer: If some data set has literally zero correlation between its variables then its correlation matrix is literally the identity matrix, which has eigenvalues of all 1's for as many columns as there are in the matrix. If all the eigenvalues are the same then
doing PCA will not help you much in terms of dimension reduction, because the first principal component will not account for any more variation then the following principal components, because eigenvalues literally mean how much variation in the data is accounted for by the corresponding principal component.
As the amount of correlation increases, then the first eigenvalue will slowly start to increase, and the later ones will decrease to 'compensate.' As such, PCA will be better performed on highly correlated data.
Here is some R code if you'd like to see it for yourself.
<code>    no.cor<-rbind(c(1,0,0),c(0,1,0),c(0,0,1))
    eigen(no.cor)
    low.cor<-rbind(c(1,0.1,0.1),c(0.1,1,0.1),c(0.1,0.1,1))
    eigen(low.cor)
    high.cor<-rbind(c(1,0.8,0.8),c(0.8,1,0.8),c(0.8,0.8,1))
    eigen(high.cor)
</code>
Comment: I believe the second question is a little subtler than your answer might suggest, because more than one eigenvalue can increase.  What happens depends on precisely what "very high correlation between variables" means.  Perhaps, then, you could include in your answer some indication of your interpretation of this phrase.


AWS + Tomcat 8 + VRaptor 4: após aumentar o volume da instância, app não starta

Question: Boa tarde!
Temos uma aplicação rodando na Amazon e estava tudo funcionando perfeitamente até ontem.
Tivemos de trocar o volume da instância pois o antigo havia atingido 100% da sua capacidade... Para isto, realizei todos os passos no tutorial da própria Amazon... Temos um outro app rodando em PHP e aquele voltou a operar normalmente após a troca de volume...
Nos logs do Tomcat, está retornando o seguinte erro:
16-Sep-2015 17:30:44.925 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.jboss.weld.environment.servlet.Listener
 org.jboss.weld.exceptions.DeploymentException: java.lang.InternalError: Enclosing method not found
    at org.jboss.weld.executor.AbstractExecutorServices.checkForExceptions(AbstractExecutorServices.java:66)
    at org.jboss.weld.executor.AbstractExecutorServices.invokeAllAndCheckForExceptions(AbstractExecutorServices.java:43)
    at org.jboss.weld.executor.AbstractExecutorServices.invokeAllAndCheckForExceptions(AbstractExecutorServices.java:51)
    at org.jboss.weld.bootstrap.ConcurrentBeanDeployer.addClasses(ConcurrentBeanDeployer.java:60)
    at org.jboss.weld.bootstrap.BeanDeployment.createClasses(BeanDeployment.java:209)
    at org.jboss.weld.bootstrap.WeldStartup.startInitialization(WeldStartup.java:328)
    at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:73)
    at org.jboss.weld.environment.servlet.Listener.contextInitialized(Listener.java:140)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1101)
    at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1786)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.common.util.concurrent.ExecutionError: java.lang.InternalError: Enclosing method not found
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2231)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3979)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3983)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4871)
    at org.jboss.weld.util.cache.LoadingCacheUtils.getCacheValue(LoadingCacheUtils.java:52)
    at org.jboss.weld.util.cache.LoadingCacheUtils.getCastCacheValue(LoadingCacheUtils.java:80)
    at org.jboss.weld.resources.ClassTransformer.getBackedAnnotatedType(ClassTransformer.java:175)
    at org.jboss.weld.resources.ClassTransformer.getBackedAnnotatedType(ClassTransformer.java:194)
    at org.jboss.weld.bootstrap.BeanDeployer.loadAnnotatedType(BeanDeployer.java:119)
    at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:96)
    at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$1.doWork(ConcurrentBeanDeployer.java:62)
    at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$1.doWork(ConcurrentBeanDeployer.java:60)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
    at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
    ... 4 more
Caused by: java.lang.InternalError: Enclosing method not found
    at java.lang.Class.getEnclosingMethod(Class.java:1057)
    at sun.reflect.generics.scope.ClassScope.computeEnclosingScope(ClassScope.java:50)
    at sun.reflect.generics.scope.AbstractScope.getEnclosingScope(AbstractScope.java:74)
    at sun.reflect.generics.scope.AbstractScope.lookup(AbstractScope.java:90)
    at sun.reflect.generics.scope.AbstractScope.lookup(AbstractScope.java:90)
    at sun.reflect.generics.factory.CoreReflectionFactory.findTypeVariable(CoreReflectionFactory.java:110)
    at sun.reflect.generics.visitor.Reifier.visitTypeVariableSignature(Reifier.java:165)
    at sun.reflect.generics.tree.TypeVariableSignature.accept(TypeVariableSignature.java:43)
    at sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68)
    at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138)
    at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
    at sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68)
    at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138)
    at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
    at sun.reflect.generics.repository.MethodRepository.getReturnType(MethodRepository.java:68)
    at java.lang.reflect.Method.getGenericReturnType(Method.java:241)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedMethod.<init>(BackedAnnotatedMethod.java:38)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedMethod.of(BackedAnnotatedMethod.java:32)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedMethods.computeValue(BackedAnnotatedType.java:193)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedMethods.computeValue(BackedAnnotatedType.java:186)
    at org.jboss.weld.util.LazyValueHolder.get(LazyValueHolder.java:35)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$EagerlyInitializedLazyValueHolder.<init>(BackedAnnotatedType.java:154)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedMethods.<init>(BackedAnnotatedType.java:186)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedMethods.<init>(BackedAnnotatedType.java:186)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.<init>(BackedAnnotatedType.java:66)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.of(BackedAnnotatedType.java:47)
    at org.jboss.weld.resources.ClassTransformer$TransformClassToBackedAnnotatedType.load(ClassTransformer.java:83)
    at org.jboss.weld.resources.ClassTransformer$TransformClassToBackedAnnotatedType.load(ClassTransformer.java:80)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3559)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2349)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2312)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2227)
    ... 17 more

16-Sep-2015 17:30:45.012 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStop Exception sending context destroyed event to listener instance of class org.jboss.weld.environment.servlet.Listener
 java.lang.NullPointerException
    at org.jboss.weld.servlet.WeldInitialListener.contextDestroyed(WeldInitialListener.java:120)
    at org.jboss.weld.servlet.api.helpers.ForwardingServletListener.contextDestroyed(ForwardingServletListener.java:30)
    at org.jboss.weld.environment.servlet.Listener.contextDestroyed(Listener.java:85)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4776)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5390)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1101)
    at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1786)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Já segui vários tutoriais, tentei alterar as configuração do app(context, beans, pom), alterar versão da próprio Weld e nada...
Alguém pode dar uma luz ?
Obrigado, abraços!
Answer: Amigos, encontrei o problema.
A biblioteca Guava estava conflitando através das dependências que eu havia instalado... Para verificar isto, executei um mvn dependency:tree e adicionei-a nas tags exclude.
Abraços!


How to initiate a devise logout with AJAX

Question: I am wanting to use Sweetalert2 to initiate a devise logout / sign out but the code below is generating an invalid CSRF token error in rails.
The below code initiates a DELETE HTTP request to the devise sign out URL but that's when when the CSRF error occurs and doesn't sign out. Note the ERB tag for destroy_user_session_path. It produces the same error if I hard code the link to the logout page.
Any help on how to approach this would be greatly appreciated.
function logoutSwal() {
    Swal.fire({
    title: 'Ready to Leave?',
    text: "Select 'Logout' below if you are ready to end your current session.",
    type: 'question',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    confirmButtonText: 'Logout'
    }).then((result) => {
        if (result.value) {
            fetch('<%= destroy_user_session_path %>', {
                method: 'DELETE'
            }
        }
    })
}

UPDATE
The below function now partially works, it correctly logs out (deletes the session) but doesn't redirect to the login page. If I refresh the page (CTRL-R) I am taken to the login page. I suspect the issue is now something to do with the devise controller and responding to AJAX / JSON?
Do I have to update the controller to respond (i.e. redirect) to this request?
Function:
window.ajaxLogout = function(logoutUrl) {
    Swal.fire({
        title: 'Ready to Leave?',
        text: "Select 'Logout' below if you are ready to end your current session.",
        type: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        confirmButtonText: 'Logout'
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: logoutUrl,
                headers: {
                    'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
                },
                type: "DELETE"
            })
        }
    })
}

Log entry when running the function:
Started DELETE "/logout" for IPXXX at 2019-10-29 19:14:47 -0400

Processing by Users::SessionsController#destroy as */*
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Account Load (0.3ms)  SELECT  "public"."accounts".* FROM "public"."accounts" WHERE "public"."accounts"."subdomain_name" = $1 LIMIT $2  [["subdomain_name", "demo"], ["LIMIT", 1]]
   (0.2ms)  BEGIN
   (0.6ms)  SELECT COUNT(*) FROM "users"
   (0.3ms)  COMMIT
Completed 204 No Content in 19ms (ActiveRecord: 3.8ms)

Comment: read documentation for fetch ... *By default, fetch won't send or receive any cookies from the server* ... so I'm assuming it's a lack of cookie problem ... you'll want the appropriate `credentials` option in your `init` argument (the second one) - see [documentation](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
Comment: Thanks, that put me on the right path. I can now pass a valid CSRF token to the controller and delete the session but its not redirecting (as it normally would for an HTML response) to the login page with a success message. See update above.
Comment: `its not redirecting` what isn't? The current page? `$.ajax` loads data, doesn't change the current page
Comment: wow, so you abandoned `fetch` and went for `jQuery.ajax` instead? I take it you already use jQuery and didn't load jQuery just for this!
Comment: Yes jQuery was already loaded, was just trying ajax. Fetch and ajax both have the same issue with the redirect. More specifically the Devise Session Controller actions aren't running. See here for the controller actions (by actions i mean the flash notice and the `respond_to_on_destroy` method: https://github.com/plataformatec/devise/blob/14863ba4c92cd9781a961be0486f0ea7dfe84144/app/controllers/devise/sessions_controller.rb#L27
Answer: In the end I just used the ajax success function to redirect to the login page.
window.ajaxLogout = function(logoutUrl, loginUrl) {
  Swal.fire({
    title: "Ready to Leave?",
    text: "Select 'Logout' below if you are ready to end your current session.",
    icon: "question",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    confirmButtonText: "Logout"
  }).then(result => {
    if (result.value) {
      $.ajax({
        url: logoutUrl,
        type: "DELETE",
        success: function() {
          window.location.href = loginUrl;
        }
      });
    }
  });
};


Behavior of multiprocessing.Pool on exception?

Question: Suppose I have a program that looks like this:
jobs = [list_of_values_to_consume_and_act]
with multiprocessing.Pool(8) as pool:
    results = pool.map(func, jobs)

And whatever is done in func can raise an exception due to external circumstances, so I can't prevent an exception from happening.
How will the pool behave on exception?

Will it only terminate the process that raised an exception and let other processes run and consume the jobs?

If yes, will it start another process to pick up the slack?

What about the job being handled by the dead process, will it be 'resubmitted' to the pool?

In any case, how do I 'retrieve' the exception?
Answer:
No processes will be terminated at all. All calls to the target
functions from within the pool's processes are wrapped in a
try...except block. Incase an exception is caught, the process
informs the appropriate handler thread in the main process which
passes the exception forward so it can be re-rasied. Whether or not other jobs will execute depends on if the pool is still open. Incase you do not catch this re-raised exception, the main process (or the process that started the pool) will exit, automatically cleaning up open resources like the pool (so no tasks can be executed now since pool closed). But if you catch the exception and let the main process continue running then the pool will not shutdown and other jobs will execute as scheduled.
N/A
The outcome of a job is irrelevant, once it's run once by any process,
that job is marked completed and not resubmitted to the pool.
Wrap your call to pool.map in a try...except block? Do note that
incase one of your jobs do raise an error, then the results of other
successful jobs will become inaccessible as well (because these are
stored after the call to pool.map completes, but the call never
successfully completed). In such cases, where you need to catch
exceptions of individual jobs, it's better to use pool.imap
or pool.apply_async

Example of catching exception for individual tasks using imap:
import multiprocessing
import time

def prt(value):
    if value == 3:
        raise ValueError(f"Error for value {value}")

    time.sleep(1)
    return value

if __name__ == "__main__":
    with multiprocessing.Pool(3) as pool:
        jobs = pool.imap(prt, range(1, 10))
        results = []

        for i in range(10):
            try:
                result = next(jobs)
            except ValueError as e:
                print(e)
                results.append("N/A")  # This means that this individual task was unsuccessful
            except StopIteration:
                break
            else:
                results.append(result)

    print(results)

Example of catching exception for individual tasks using apply_async
import multiprocessing
import time

def prt(value):
    if value == 3:
        raise ValueError(f"Error for value {value}")

    time.sleep(1)
    return value

if __name__ == "__main__":
    pool = multiprocessing.Pool(3)
    job = [pool.apply_async(prt, (i,)) for i in range(1, 10)]
    results = []

    for j in job:
        try:
            results.append(j.get())
        except ValueError as e:
            print(e)
            results.append("N/A")

    print(results)

Comment: Thanks! I learnt so much from your very good explanation!


linear mixed model with repeated measures

Question: I am trying to wrap my head around linear mixed models for repeated measures with random effects. I'm choosing to conduct this type of model due to missing values in my dataset.
I am interested in analyzing how differing amounts of antibiotics affect the growth of caterpillars. Approximately 24 larvae were organized into 5 treatment groups, with the treatment groups consisting of either 0, 3, or 4 different antibiotic combinations. Larvae were then measured at three varying instar time points--again, some values are missing either at random, or because the larvae did not survive to a given time point.
I am using the lmer package in R to conduct this analysis and would appreciate any help in regards to my model. So far I am using long-format data, that is organized in the following way:
| larvae | treatment | antibiotic amount | instar | weight |

And right now, my model looks like this:
mod <-lmer(weight ~ instar + treatment + (1|larvae), data=data_long)

With larvae being my random effect, instar and treatment as my predictor variables, and the weight as the dependent variable. Again, each larvae in theory is measured (their weight) up to 3 time points (the instar column).
Is this the right model to be using to assess growth rates between individuals and within treatment groups?
Comment: What is the question?
Comment: Sorry--edited. Is this the right model to be using to assess growth rates between individuals and within treatment groups?
Answer: The reason for using a linear mixed model is to account for the correlations in the repeated measurements of weight within each larvae. The model now says that weight changes linearly with instar time and that different treatment groups act additively. Assuming that treatment is a factor, the model says that you have five parallel lines for the weight over time, one for each treatment. In the random-effects part, you have included random intercepts. This says that correlations between the different weight measurements for each larva are the same. That is, the correlation between measurements 1 and 2, is the same as the correlation between 1 and 3, and the correlation between 2 and 3.
Whether this is a "reasonable" model is difficult for us to say. You need subject-matter knowledge to claim that (you can probably tell if these are reasonable assumptions). Nonetheless, you can extend the model and test whether these assumptions are supported by the data. For example, by including the interaction term between time and treatment, you can relax the assumption of parallel lines for weight. And by including a random slope, you can relax the assumption of constant correlation over time. Though you should be careful making your model too complex because the size of your dataset is small.


How to access the different objects using jQuery?

Question: I have developed some code for image sliding in which whenever a mouse event occurs I want the id of the other div except on which the mouse is present.
My code is:
$('#div1,#div2,#div3,#div4,#div5,#div6').mouseover(function () {
    $('#div1,#div2,#div3,#div4,#div5,#div6').css('width', '100px')
    $("." + $(this).data('class')).animate({
        'width':"400px",
    }, {
        'duration':1500,
        easing:'easeOutBack',
    })
});

Comment: Ohhh dear, use class instead 100K of ids.
Comment: Try jquery.not(this): http://api.jquery.com/not/
Comment: Can you provide an [example](http://jsfiddle.net) of your problem. It's not very clear in your question. Also, a description of why the code you have doesn't work would be helpful.
Comment: Try $('#'+this.id).animate({yourcode});
Comment: @Dineshkani Why on earth would you do that? `this` is already the element you want, re-selecting it using its `id` property makes no sense.
Comment: numbers are not allowed in ids. O.o but in HTML5 its fine.
Answer: I would suggest altering this to use classes rather than ids. It would make your code much neater.
Give every element that you want to have this effect a class of animated and try this code instead.
$('.animated').mouseover(function () {
  $(this).removeClass('animated');
  $('.animated').css('width', '100px')
  $(this)
    .addClass('animated')
    .animate({
      'width':"400px",
    }, 1500);
});

Here is an example showing it in action. Although I don't think your code does what you want it to.
Answer: Use .not to remove the hovered over div from the set of matched elements.
$('#div1,#div2,#div3,#div4,#div5,#div6').mouseover(function () {
    $('#div1,#div2,#div3,#div4,#div5,#div6').not(this).css('width', '100px')
    $("." + $(this).data('class')).animate({
                    'width':"400px",
                }, {
                    'duration':1500,
                    easing:'easeOutBack',
                })
    });

On a side note, it would be cleaner to use a class selector in this situation.
Answer: $( function() {
$("[id^=div]").mouseover( function() {
  var my = $(this).attr("id");
  var id = new Array;
  $("[id^=div]").each( function() {
    if($(this).attr("id") != my) {
       id.push($(this).attr("id"));
    }
  });
});
});

Working Fiddle or Demonstration
You can access each and every property.
I have taken all ids and added all ids to array id. You can access it further in your function.


Offline access on iPad to svn diff information

Question: I've seen a couple iOS apps that allow access to svn logs, but none as nice as iOctocat is for git.  It appears I could use iOctocat on a network to collect all the data, and then view it offline.  I need to do that for svn, not git.
I'm looking for a way to read svn log commit diffs in an offline state on an eReader (prefer iPad, but could switch to say Kindle Fire if required.)  Is there any OSX software/scripts that can get an svn server log, perform diffs, and output into files for viewing on an iPad, or alternatively, into a PDF that can be viewed darn near anywhere?
I'm trying to get a bit more productive on my 1.5 hour bus ride, and this could help tremendously...
Answer: Git is a DVCS which consists in having the whole repository, with its whole history, on every "client" machine. SVN is a centralized VCS, where the working copy only has the latest version of every file. The history is only available on the server.
If offline work is so important, git is obviously a much better choice, and you should switch to git. I don't think any SVN tool will ever give you access to previous versions offline, because that's just not how SVN works.
Answer: If you just want to review the logs, you can generate a PDF file easily enough. The command:
svn log | enscript -o log.ps

makes a PostScript file from the log for the current working directory. You can follow that with:
pstopdf log.ps

to generate log.pdf, a PDF file that contains your Subversion log. You can obviously automate that process to your heart's content. You might even run the process every few hours and post the result on an internal web server where it's easy to grab. You can also make the PDF file that you generate a lot fancier by configuring enscript, which has oodles of options (font, margins, columns, headers, footers, etc.) so you can make a really nice looking file.
For convenience, here's a version all on one line:
svn log -l 10 | enscript -o - | pstopdf -i -o svnlog.pdf

The -l 10 option to svn log limits the output to the 10 most recent log entries -- customize that as you wish, or customize the output with other options.
The next step would be to write a shell script or other small program that would filter the log to show just the most recent changes, generate diffs for the changed files, and wrap that all up into a PDF for you to review. As you can see from the above, the tools you'd need to do that are already there -- you just need to put them together in the right order.


How to exclude gatsby-created pages from being indexed?

Question: Context
Gatsby, the headless CMS marvel, alongside gatsby-plugin-advanced-sitemap makes generating a robust sitemap.xml file a breeze.
The plugin supports excluding pages with either by slug or with clever regular expression.
However in my case, I have 2 collections of User-Generated Content pages:

the collection A, with pages that need to be hosted, and indexed,
the collection B, with pages that need to be hosted, but NOT indexed.

The B collection has not a slug pattern making them identifiable with a regular expression.
Question
How to exclude the collection B from indexation?
Comment: Example slugs would help answer this question. Please provide examples. Also post your code of your `gatsby-plugin-advanced-sitemap` inside your `gatsby-config.js`.
Answer: Files that you don't include (or exclude) in your sitemap.xml can be indexed too if their robotx.txt allows Google's robots with an index attribute, or if the links from other pages to the page have a follow attribute.
Regarding your question, the plugin allows you to add a exclude array of pages that won't be added in your sitemap.xml despite being retrieved by your query. So, in your gatsby-config.js:
{
      resolve: `gatsby-plugin-advanced-sitemap`,
      options: {
        query: `{}`, // your query
        mapping: {}, // add if needed
        exclude: [
          `/dev-404-page`,
          `/404`,
          `/404.html`,
          `/offline-plugin-app-shell-fallback`,
          `/terms-and-conditions`,
          `/terms-of-use`,
          `/cookie-policy`,
          `/privacy-policy`,
          /(\/)?hash-\S*/,
        ],
        createLinkInHead: true,
        addUncaughtPages: true,
        additionalSitemaps: [], // add if needed
      },
    },

Ideally, your excluded pages may follow a regular expression way to be excluded automatically when generated. However, if don't, as the code above shows, you can add manually. In this case, nor /terms-of-use, /cookie-policy, or /privacy-policy won't be added in your sitemap.xml.


Add background to a div based on a Node's Image Field

Question: I had a request approach me and am blanking on a smooth way to implement this. We have on content type that on occasion will have a background image in a a div. The image will be a washed out background image behind content. The content authors want to add this page by page using an Image Field.
How would you implement this?
I'm assuming I can do this through our custom theme -- perhaps a theme_preprocess_page() or theme_process_page()?
Answer: You could try BackgroundField:

BackgroundField started as an extension of the CCK ImageField that
  allows a CSS selector and background attributes to be set for a
  content-type. This is particularly helpful for allowing your node
  authors to add images to a node that are integrated into the theme of
  the site. With the inclusion of the Image field in Drupal 7,
  BackgroundField was rewritten to extend that core functionality.
Comment: With this module added I removed a gunk load of code from my templete.php file. It looks so nice and clean again. Thank you. Thank you.
Answer: I created a module to do that: Field Group Background Image
The idea is creating a div wrapper (with Field Group), specifying the image field of your content type as the background image.


How to calculate the % change between 2 tuples

Question: I have a function that performs calculations on dictionary keys, and updates them. Each key is a 4-D point (a tuple), for example:
original_key = (6.0, 3.0, 4.8, 1.8)
updated_key = (6.513333333333332, 2.962666666666666, 5.238666666666668, 1.833333333333333)

I'd like that the function will stop updates the keys, once the % change between the original key and the new key will be 10% or less.
How can I calculate the change between 2 tuples with this structure? (note: it is ok to change it to other types other then tuple)
Edit
Consider a 4-d space, and I'd like to check if the change between the distance of 2 points changed in 10% or less
Comment: How do you define the percent change? Do you mean the percent change between each "coordinate" in the 4-D point?
Comment: What do you mean by total? The change in euclidean distance?
Comment: How would you make sense of a total percent change? the whole 10% change could come from any of the members of the tuple
Comment: You can use something like `for item in zip(original_key, updated_key):` which will give you a tuple (orig, updated) and compare the way you like.
Comment: I meant in total, not each coordinate
Comment: Yes, in euclidian distance. Consider a 4-d space, and I'd like to check if the change between the distance of 2 points changed in 10% or less
Comment: so just use output of zip and calculate euclidian distance with lambda or helper function.
Comment: Can you write a sample code to what you meant?
Answer: If you don't already have a distance function, define one e.g.
from math import sqrt

def distance(a, b):
    return sqrt(sum([(p - q)**2 for p,q in zip(a, b)]))

or use a lambda as mentioned in the comments, and stop updating when abs(distance(current_key, new_key) / distance(current_key, old_key)) <= 0.1.


Observing @Relation changes in a DataBase

Question: If I something like the following:
@Relation(parentColumn = "id", entityColumn = "fk_id", entity = User.class)
private List<User> users;

This list is a model which gets updated via LiveData.
But I want to be able to update this when I detect changes to the User table. Right now, it only picks up what exists in the DB, but whenever an update happens to the user table, this list does not get updated. Any suggestions?
Answer: You have not been very specific in what you are doing or want (which database you use, who is updating the database...).

But I want to be able to update this when I detect changes to the User
  table. Right now, this only picks up what exists in the DB but
  whenever an update happens to the user table, this list does not get
  updated. Any suggestions?

Option 1
If you are doing the update/insert/delete in the same app as the List users, then you can easily update your List in your code.
Option 2
If another app/service is updating the database, I suggest you use a trigger to update your List.
See http://www.coderconsole.com/2015/02/android-sqlite-trigger-demo.html for an example.
Detecting the change in Java is tricky, see Calling a Java method from a sqlite trigger (android) .
Here is an example where you use a ContentObserver to monitor your Sqlite database (the flat file itself) https://gist.github.com/JBirdVegas/3874450
Option 3
If another app/service is updating the database, you can use a BroadcastReceiver to pick up the changes.


Ordenar lista com vue

Question: Ba tarde senhores, sou iniciante com vue e estou criando uma lista, mas estou com dificuldade para entender como irei ordenar lista clicando na coluna titulo segue exemplo:

new Vue({
  el: "#lista",
  data:{
    users :[
      {nome: "Marcos Santos", email: "email@example.com"},
      {nome: "Lennon Bueno", email: "email@example.com"}
    ]
  }
})
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Vue 1</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      Nome
      Email

      {{item.nome}}
      {{item.email}}

Gostaria quando clicasse em nome ordenasse por nome, e por email ordenasse pelo email, por onde eu começo?
Comment: É só ordenar a array de dados. Sua dúvida é sobre como ordenar, ou sobre como rodar uma função (como a de ordenação) a partir de um clique?
Comment: @bfavaretto como rodar a ordenação a apartir do cllick
Answer: Você começa pela método sort que as arrays têm em JavaScript. Esse método retorna uma função onde você define como comparar um par de valores a e b. Ela deve retornar um valor menor que zero se a for menor que b, zero se forem iguais, ou um valor maior que zero se a for maior que b. E para comparar strings o método localeCompare convenientemente retorna um valor compatível com o sort.
Para amarrar um evento no Vue, basta usar os atributos @evento="..." (ou v-on:evento="...") no elemento-alvo, e registrar o método a ser executado na lista de métodos do app ou componente.
No seu caso, pode fazer assim:

new Vue({
  el: "#lista",
  data:{
    users :[
      {nome: "Marcos Santos", email: "email@example.com"},
      {nome: "Lennon Bueno", email: "firstname.lastname@example.com"}
    ]
  },
  methods: {
    sortUsers: function(chave) {
      this.users.sort(function(a, b) {
        return a[chave].localeCompare(b[chave])
      });
    }
  }
});

      Nome
      Email

      {{item.nome}}
      {{item.email}}

Answer: Conforme recomendação da documentação do Vue, utilize uma propriedade computed e a biblioteca Lodash. Link da documentação.
No exemplo, coloquei de acordo com a documentação, deixei comentado o código e também inseri um recurso adicional, o de inverter a ordem das colunas, exemplo de A-Z e Z-A.

new Vue({
    el: "#lista",
    data: {
        // Coluna padrão para ordernar
        colunaSort: 'nome',

        // Opção de ascendente ou descendente, padrão inicia como asc
        colunaOrder: 'asc',

       // Itens para ordenar
        users: [
            {nome: "Marcos Santos", email: "firstname.lastname@example.com"},
            {nome: "Zeus Bueno", email: "firstname.lastname@example.com"}
        ]
    },
    methods: {

        // Metodo que define qual a coluna que será ordernada
        // Também define se é  ascendente ou descendente
        sort: function(coluna) {

            // Se é a mesma coluna que está setando, então vai inverter a orderm de exibição
            if (this.colunaSort == coluna) {
                this.colunaOrder = (this.colunaOrder == 'asc') ? 'desc' : 'asc';
            }

            // Se é uma coluna diferente, seta a coluna e define como ascendente
            else
            {
                this.colunaSort = coluna;
                this.colunaOrder = 'asc';
            }
        }
    },
    computed: {
        // Metódo que faz o sort das colunas, definindo o nome da coluna e a ordem
        orderedUsers: function() {
            return _.orderBy(this.users, this.colunaSort, this.colunaOrder)
        }
    }
});

      Nome
      Email

      {{item.nome}}
      {{item.email}}

Comment: Perfeito! de grande ajuda =)

Ordenar lista com vue


Formulating a recursive definition

Question: Let Σ(k) = 1 + 3 + 5 + ... + (2k+1) be the sum of all odd natural numbers from 1 up to and including (2k+1). Formulate a recursive definition for Σ including both the base case Σ(0) = 1 and a (k+1)th case.
Base case:  Σ(0) = 1  ⇒ 0 + 1   ⇒ 2(0) + 1
so the base case holds.
How do I formulate a recursive definition for the (k+1)th case?
Comment: Hint: We are adding $2k+3$ to $\Sigma(k)$.
Comment: Notice from this recursive definition you can get sum of first $k$ odd naturals is equal to $\frac{(2k)^{2}}{4}$ if $k$ is odd and $\frac{(2(k-1)+1)^{2}}{4}$ if $k$ is even
Answer: "How do I formulate a recursive definition for the $(k+1)^\text{th}$ case?"
You do it by writing $f_{k+1}$ in terms of $f_k$:
$$f_k = \sum_{n=0}^{k} 2n+1$$
$$f_{k + 1} = \text{???}$$
Figure out the "???"

 $$f_{k+1} = \sum_{n=0}^{k+1} 2n+1$$

$$f_{k+1} = g(f_k) \tag{A}$$
Now you want to figure out $g$, because $g$ is what relates $f_k$ and $f_{k+1}$.  So use the known formulas for $f_k$ and $f_{k+1}$ to figure out what $g$ should be.  If you need more info here is a hint:

 To convert $f_k$ into $f_{k+1}$, you need to add something.  So ultimately you need to find $f_{k+1} = f_k + \text{???.  }$  Subtract the common terms from each side.

If you really need to see the final answer:

 $f_{k+1} = f_k + h(k)$

 $\sum_{n=0}^{k+1} 2n+1 = \sum_{n=0}^{k} 2n+1 + h(k)$

 $\left(\sum_{n=0}^{k} 2n+1\right) + 2(k+1)+1= \left(\sum_{n=0}^{k} 2n+1\right) + h(k)$

 $2(k+1)+1= h(k)$

 $f_{k+1} = f_k + 2k+3$
Answer: Hint: $(k+1)^2-k^2=2k+1$
The recursive definition for $\Sigma(k)$ would be
$$
\Sigma(k)=\Sigma(k-1)+2k+1\tag{1}
$$
since that is the same as saying
$$
\overbrace{1+3+5+\dots+(2k+1)}^{\Sigma(k)}=\overbrace{1+3+5+\dots+(2k-1)}^{\Sigma(k-1)}+(2k+1)\tag{2}
$$
Apply the hint to $(1)$ for a closed form for $\Sigma(k)$.
Answer: Your base case value is somewhat offpoint.
The idea of a recursive function is one that will use previous values to ascertain later ones.
For example,
\begin{align} &\sum(2) = 1+3+5 = 9  = \sum(1) + 2(1)+3\\
&\sum(3)=1+3+5+7=16=\sum(2)+2(2)+3
 \end{align}
In general, $\sum(k+1)$ will be obtained similarly based on $\sum(k)$, as André explains in the comments. I'll leave it up to you to prove $$\sum(k+1) = \sum(k) + 2k+3$$
Comment: How can he prove the last equality when it's supposed to be the definition?
Comment: Ah, I should have read more carefully. If he's supposed to "formulate" a recursive definition, he may as well show the final equation holds.
Answer: Let $k = 1, 2, 3, \ldots$ be the sequence of natural numbers. We have the recursive formula
\begin{align*}
&s(k) = 2k-1,\\
&\Sigma(0) = 0,\\
&\Sigma(k) = \Sigma(k-1) + s(k).
\end{align*}
Then, computing $\Sigma(k)$ from $k=1$ to $k=6$, we obtain
$k=1 \quad s(1)=1 \quad \Sigma(1)=1$
$k=2 \quad s(2)=3 \quad \Sigma(2)=1+3=4$
$k=3 \quad s(3)=5 \quad \Sigma(3)=1+3+5=9$
$k=4 \quad s(4)=7 \quad \Sigma(4)=1+3+5+7=16$
$k=5 \quad s(5)=9 \quad \Sigma(5)=1+3+5+7+9=25$
$k=6 \quad s(6)=11 \quad \Sigma(6)=1+3+5+7+9+11=36$
I hope that you find it useful.

Formulating a recursive definition


Windows Text Search Tool Including PDFs

Question: Looking for recommendations for tool/process to search through roughly 2TBs of data looking for certain phrases. This would include office docs, .txt, and PDFs.
I see a lot of tools out there for this, but not seeing many that can do PDFs.
Thanks.
Answer: Try this: http://www.microsoft.com/enterprisesearch/en/us/search-server-express.aspx
"The following connectors come out of the box in Search Server 2010 Express and SharePoint Server 2010:

SharePoint sites
Windows file shares
Exchange public folders
Lotus Notes
Web sites
IFilters for additional repositories
Structured content in databases
Federation object model

" - http://www.microsoft.com/enterprisesearch/searchserverexpress/en/us/compare.aspx
PDF and other iFilters are available.
Read this as well which discusses some limitations.

Windows Text Search Tool Including PDFs