Error after disable Index in a table

Question: I would like to do Bulk Insert, but it takes a long time. My Idea is to disable Index on the table, to do INSERTs a little bit faster. But after that I get this error:

Error: The query processor is unable to produce a plan because the index CRMD_MKTTG_TG_I~0 on table or view 'CRMD_MKTTG_TG_I' is disabled.

I am generating my table with this script:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [CRMD_MKTTG_TG_I](
    [CLIENT] [nvarchar](3) NOT NULL,
    [GUID] [varbinary](16) NOT NULL,
    [TG_GUID] [varbinary](16) NULL,
    [BP_GUID] [varbinary](16) NULL,
    [BP_ORG] [nvarchar](2) NOT NULL,
    [BP_DEL] [nvarchar](1) NOT NULL,
    [REL_GUID] [varbinary](16) NULL,
    [RELATIONSHIP] [nvarchar](6) NOT NULL,
    [TYPE_BP_GUID] [nvarchar](1) NOT NULL,
    [TYPE_REL_GUID] [nvarchar](1) NOT NULL,
    [ROW_NUMBER] [int] NOT NULL,
 CONSTRAINT [CRMD_MKTTG_TG_I~0] PRIMARY KEY CLUSTERED
(
    [CLIENT] ASC,
    [GUID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

any idea?
Comment: Disabling clustered index to do things faster?
Comment: You may wish to take a step back and ask the question "How do I speed up a bulk insert on this table given this data", with details of the data (including the *order* of the source data with regard to the clustered index columns), the number of rows, the time it's currently taking, and your bcp statement. It might help to do a bit more diagnosis in advance to figure out what's slow -- there's no point dropping indexes if you're being constrained by your network bandwidth, for example.
Comment: CRMD_MKTTG_TG_I~0 is the cluistered index. you cannot disable it.
Comment: That PK is just strange to me.   Why is GUID alone not enough for a PK?  Why not just let [ROW_NUMBER] be the PK?    Insert in the order of the PK to minimize index fragmentation.
Answer: [CRMD_MKTTG_TG_I~0] is a clustered index. If you disable it, you can't access to the data (select, insert, update, delete data).
Read Disable Indexes and Constraints:

Disabling an index prevents user access to the index
and for clustered indexes to the underlying table data.

In this case, you can only:

drop the clustered index and transform it into a heap,
query your table
and then create a new clustered index.
Comment: How about: **`ALTER INDEX [CRMD_MKTTG_TG_I~0] REBUILD`**?
Comment: You can use rebuild to enable a disabled index. however while the clustered index is disabled, you still can't query the table, hence the OP error.

Error after disable Index in a table


Changing preprocessed values during compile time

Question: I have written some code using pre processor directives to skip some statements to be executed.But My C code inside main is interested to change previously #defined values and assign new values as per condition and also change the result of pre processed statements too during run time.In short I have to change the pre processed statements during run time. How can I do this?
Comment: Show some code. Your question is unclear. Read about [C preprocessing](https://en.wikipedia.org/wiki/C_preprocessor) & [cpp](https://gcc.gnu.org/onlinedocs/cpp/). You probably cannot do what you want (because *compile* time & *run* time are different and may happen on different computers with *cross-compiling*). **Improve your question** (by editing it), say more about your OS and system
Answer:
In short I have to change the pre processed statements during run time

This is impossible. Read about C preprocessing & cpp. Compile-time and run-time are different (and the compiled code could even run on a different machine, read more about cross-compiling). If using GCC, use gcc -C -E foo.c > foo.i to preprocess your foo.c source file into foo.i preprocessed form (and then use an editor or a page to look inside that generated foo.i)
Perhaps you want to load additional code at runtime. This is not possible with pure C99 standard code. Perhaps your operating system offers dynamic loading. POSIX specifies dlopen. You might also want to use JIT compiling techniques to construct machine code at runtime, e.g. with libraries like GCCJIT, asmjit, GNU lightning, libjit, LLVM, ...
Read also about homoiconic languages. Consider coding in Common Lisp (e.g. with SBCL).
Perhaps you want to customize your GCC compiler with MELT.
Comment: Thanks for clever answer.So I should give it try in different way.:-)
Answer: Not possible. Preprocessing happens before compile-time.
The compiler only sees the result of the preprocessor, nothing more.


How one can get a field auto loaded with node title by passing nid

Question: How one can get a field auto loaded with node title by passing nid. I mean instead of getting the selectllist of all available title i want it to be auto loaded with corresponding node title.
NOTE: I have passed nid to that content type. Now have to fetch the corresponding node title into a field.
Thanks in advance ,
Manju
Comment: Are you opposed to using jquery for this?  If not you may have to do a form_alter to grab the args() value and change the default value to whatever the NID is
Comment: I am new to drupal and so have only basic knowledge about it. Could you pls elaborate the steps for it . Thanks
Comment: We are not using jquery.. Is there a way where I can get it with the existing functionalities without need for coding?
Comment: Is this on content type field or what form is it?
Comment: yes it is on content type field only ....
Comment: Are you on a node form ?
Answer: Prepopulate might solve your problem.

The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.
For example, the following URL,
http://www.example.com/node/add/blog?edit[title]=this is the title
will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.
Answer: The Node Reference URL Widget worked well for my issue. I got the field autopopulated using the value from URL.
Manju


How to XOR between a byte and a word on PDP-11?

Question: The main problem we encountered is that one number is saved as a byte, the other is saved as a word and we realize that there's a built in XOR in PDP-11.
Comment: https://stackoverflow.com/questions/4749585/what-is-the-meaning-of-xor-in-x86-assembly
Comment: @PosticaÐenis I think the user's problem is that he wants to do this on PDP-11 architecture.
Comment: So zero-extend the shorter one or truncate the longer one.
Comment: Bytes on PDP-11?
Comment: @MartinRosenau: What's weird about that?  [PDP-11](https://en.wikipedia.org/wiki/PDP-11_architecture) has 8-bit bytes and 16-bit words.  It's not one of those old architectures with a non-power-of-2 word size.
Comment: @PeterCordes OK. Thanks. I just read your link. I was thinking that PDP-11 works like other "pre-CPU" computers or the modern TMS320 where the memory does not store bytes but 16-bit words (so there are no instructions that can handle bytes).
Comment: @MartinRosenau: Ah yes, right some machines only have word-addressable memory ([the most recent mainstream CPU example being early DEC Alpha in the early 90s](https://stackoverflow.com/questions/46721075/can-modern-x86-hardware-not-store-a-single-byte-to-memory/46818162#46818162), but also including some modern DSPs)  But they still have bytes, you just have to load + shift&mask if you want them separately.  (But in that case the OP would already know how to deal with bytes using full registers to have stored a byte in the first place)
Answer: The XOR instruction on the PDP-11 only works on 16-bit words.
You will have to make a 16-bit word out of the byte operand first. Whether that is zero-extension or sign-extension (maybe SXT can help?) is up to you.
Then apply XOR to the two word arguments.


Injectivity of morphism: 2-folded covering space of wedge sum circle projective plane

Question: I've read (and I see it more or less clearly) that a 2-folded covering space $\tilde{X}$ of $X=S^1 \vee \mathbb{R}P^2$ is a 2-sphere with 2 unit circles tangently attached to antipodal points. If my reasoning is correct, $\pi_1(\tilde{X}) = \langle a, b \rangle$ is generated by two loops, each one around each circle, while $\pi_1(X) = \langle c, d \mid d^2=1 \rangle$ ($c$ loops around the circle, $d$ is the generator of the group of the plane).
Now, the covering map $\pi$ between them induces an injective homomorphism between the fundamental groups. But in this case, the two circles map to the same one in $X$, so $a$ and $b$ both map to $c$. Where is the error, in the covering spaces themselves or my calculation of their fundamental groups? Any help is appreciated.
Thank you in advance :)
EDIT: I include a picture showing how I think the covering would work. Points in $S^2$ get mapped to their projection on the plane, and points in both $S^1$ go to the same position in the $S^1$ of the image.
Comment: *Notation:* Use `\langle a, b \rangle` for better angle-brackets: $\langle a, b \rangle$.
Answer: You seem to have switched around $X$ and $\overline{X}$: $\pi_1(X)\cong\langle c,d|d^2=1\rangle$, rather, and $\pi_1(\overline{X})\cong\langle a,b\rangle$.
So the trouble must be that the map $p:\overline{X}\to X$ which is given by the components $S^1=S^1$ and $S^2\twoheadrightarrow\Bbb RP^2$ is not actually a covering map. Consider, say, any neighbourhood of the base point of $S^1$ (which is forced to be shared by both copies of $S^1$). It pulls back under $p$ to two identical but nondisjoint copies in $\overline{X}$ and it is completely impossible to have the "disjoint sheets" condition met. So, $p$ is not a covering.
EDIT: I now see you have defined your space $\overline{X}$ differently to how I expected from the notation $S^1\vee S^2\vee S^1$. The map is now a covering but it does not send both $a,b$ to $c$. In this image:

Observe that while $a\mapsto c$ is true, the loop class associated to $b$ - which must be about the same base point as $a$ - actually crosses into a loop around $\Bbb RP^2$ after projection by $p$. Note the purple line around $S^2$ which runs $\beta\to\alpha$: this projects to a generator of $\pi_1(\Bbb RP^2)$. So, $b\mapsto dcd$. And the homomorphism induced by $(a,b)\mapsto(c,dcd)$ is an injection. So all is well!
Comment: I don't see how... As I understand, the map works the way I drew, and the two presages are disjoint (I have edited the question to include a picture). But anyhow, what would the covering be then? It is a past exam question and it asks for two non-isomorphic 2-sheet coverings
Comment: Preimages* instead of presages
Comment: @Josemi Judging by your picture, you aren't considering the wedge sum of *all three* spaces, $S^1\vee S^2\vee S^1$. Your space is something different (in that notation, it is implied all wedges are joined at the same basepoint)
Comment: Oh, I'll change it. I came across that notation searching for similar questions and didn't put much thought into it.
Comment: @Josemi I've updated my answer to account for the new definition of $\overline{X}$
Comment: OH! I should've taken more care regarding the basepoint, thank you so much! One last question, if the basepoint in your picture is $\alpha$, the element $b$ should actually be a loop, right? So you'd have to run from $\alpha$ to $\beta$, then loop around the circle, and back to $\alpha$. So wouldn't it be $b \mapsto dcd$ then?
Comment: @Josemi Oh sorry, I forgot to close it off. I guess it should run $\alpha\to\beta\to\beta\to\alpha$, so $b\mapsto dcd$ would be correct ($d^{-1}=d$)


I have to show $B\in F[A]$.

Question: Let $A,B\in M_n(F)$. Set $C(A)=\{X\in M_n(F) \mid XA=AX\}$. Similarly $C(B)$ is defined. If $C(A)\subseteq C(B)$, I have to show $B\in F[A]$. ($F$ is a field.)
Comment: http://math.stackexchange.com/questions/497806/matrices-b-that-commute-with-every-matrix-c-commuting-with-a
Comment: What's definition of $F[A]$ ?
Answer: This is a well-known theorem contained in Wedderburn's "Lectures on matrices", page 106.
Theorem (Wedderburn): If the matrix $B$ commutes with every matrix that commutes with $A$ then $B$ is a scalar polynomial of $A$.
See here for a proof, or this article.

I have to show $B\in F[A]$.


Update mysqli query with inner join

Question: How to excute query and set done value = 1 if its 0  vice versa, I tried this code but doesn't work:
UPDATE orders set orders.done=1 inner
JOIN mydate on orders.order_no=mydate.order_no and orders.date=mydate.order_date
where done.orders=0

Comment: get rid of PHP and run your query in console/phpmyadmin and see what's wrong
Comment: please share table structure
Answer: Try this:
UPDATE orders
join mydate on orders.order_no=mydate.order_no and orders.date=mydate.order_date
set orders.done=1
where order.orders=0

Update mysqli query with inner join


Eclipse project build failed to init ct.sym for jre/lib/jrt-fs.jar

Question: This has been a nightmare lately to setup Eclipse 2020 for some demo servlet.
The project structure is:

The demo servlet dies with "Http Status 500 - Error instantiating servlet class" with the root cause as "java.lang.ClassNotFoundException".
There is a red cross beside my project and an error log stating:

Failed to init ct.sym for C:\Users\Pratyay Mukherjee\AppData\Local\Temp\eoi8BAC.tmp\plugins\org.eclipse.justj.openjdk.hotspot.jre.minimal.stripped.win32.x86_64_14.0.2.v20200815-0932\jre\lib\jrt-fs.jar

I have tried rebuilding the project again and again as that is the solution for everything wrong with Eclipse. What is going wrong in my project and how can I get the servlet to work without errors?
Comment: I had also tried demoapp.AddServlet as well in web.xml file.
Comment: See https://stackoverflow.com/a/63955520/6505250
Comment: which error are you addressing with this? The red cross beside project or the ClassNotFoundException
Comment: It addresses the root error of running Eclipse with the wrong JRE (with an incomplete system library) which can cause multiple subsequent errors (have a look at the Eclipse source code, if you are really interested in what is used where from the system library). Did an error remain after you fixed it?
Comment: I had downloaded jdk from https://www.oracle.com/java/technologies/javase-jdk15-downloads.html . The primary reason for downloading only JDK is that both JRE and JDK can be used to run Eclipse. While downloading JDK there was no prompt for any minimal download.
Comment: Java 15 is too new, you need [this plugin](https://marketplace.eclipse.org/content/java-15-support-eclipse-2020-09-417) for it and not everything might work yet. Better use Java 11 which has LTS and which you can e.g. downloaded from [AdoptOpenJDK](https://adoptopenjdk.net/) (Oracle provides JDKs only and there are still free to use but not free anymore to bundle as part of your product).
Comment: Nope same error. The description says : "The server encountered an internal error that prevented it from fulfilling this request." just as before along with whatever error I had mentioned before. I downloaded Java 11 with OpenJ9, re-installed Eclipse IDE 2020-09, and set the AdoptOpenJDK RE at the time of installation. Still no luck
Comment: thanks for your help. I solved the problem. I was using some minimal old JRE that I had installed previously.
Answer: The following fixed the issue for me.

Installed OpenJDK 15.0.1 on my computer.
In Window/Preferences/Java/Installed JREs, I added a link to the new Java version (and named it "openjdk-15" to help identify it). I unchecked the existing jre and selected the newly installed.
I started a NEW PROJECT, and for the JRE, made sure to select the new default jre.
I copied over the source code of the failing project into the new project.

See https://www.eclipse.org/forums/index.php/t/1106241/


Probability of rolling sixes in 50 rolls of a fair die

Question: A fair die is rolled 50 times. Find the probability of observing:

a) exactly 10 sixes
   b) no more than 10 sixes
   c) at least 10 sixes

I know how to do

a) $\frac{50!}{10!(40!)}$x$(\frac{1}{6})^{10}$x$(1-\frac{1}{6})^{50-10}$
  =0.1155

Please help me out to do b) & c)  I have tried same formula above and changing power to 9, 11 etc...
But Can't get right answer.!
Appreciate your help!
Comment: if you can compute the $a$ then just note that $b$ is just the sum of getting exaclty $1$ six plus exactly $2$ sixes$\ldots$ plus $10$ sixes. What about $c$ now?
Comment: A related answer of mine: http://math.stackexchange.com/questions/179660/need-to-clarify-the-at-least-concept-in-combination/179664#179664 It is related in the sense that it is another example of breaking an "at least" or "at most" problem into several "exactly" problems.
Comment: sorry! I have tried without changing power, changing 2 sixes,+ 3 sixes,+4sixes..plus 10 sixes...but can't get answer.
Comment: (b) is 161379376595505164004862308502197265625 / 202070319366191015160784900114134073344. (c) should be easy to derive from this and (a).
Answer: Hint: You will get no more than 10 sixes if you get no sixes or one six or two sixes or three sixes or ... or nine sixes.  Since these possibilities are mutually exclusive, you can add the individual probabilities to get the total probability.
Once you've solved (b), think how you can use that answer to solve (c).
Comment: does this mean $\frac{50!}{10!(40!)}$x$(\frac{1}{6})^{1}$x$(1-\frac{1}{6})^{50-1}$
Comment: Well, that is the chance of getting **exactly** 1 six.  You need to work out something similar to this formula, and the one in question (a) for 10 sixes, but for each number of sixes from zero to nine...
Comment: @SbSangpi: That is neither the chance of getting exactly $1$ six nor the chance of getting exactly $10$ sixes. Formula $(1)$ in my answer gives the chance of getting exactly $k$ sixes.
Comment: @robjohn is correct - sorry, I missed that Sb Sangpi hadn't changed the binomial coefficient in his comment.  Remember that for 10 sixes, you used $\frac{50!}{10! (50-10)!} \times (\frac{1}{6})^{10} \times (1-\frac{1}{6})^{50-10}$.  So when you want to move to exactly one six, you need to change the 10's occuring in the first factor to 1's.
Answer: Hint: Your formula can be generalized to exactly $k$ sixes with
$$
\binom{50}{k}\left(\frac16\right)^k\left(\frac56\right)^{50-k}\tag{1}
$$
where
$$
\binom{n}{k}=\frac{n!}{k!\,(n-k)!}\tag{2}
$$
Comment: can u provide more about question b) & c) ?. thx
Comment: That was the intent of the hint. You can add the formula above for $k=0$ to $k=10$ to get b). Then note that the sum of the answers for b) and c) is $1$ plus the answer for a).
Answer: Hint: If you get no six, you don't get exactly one six, or exactly two, or exactly three, and so on.
Similarly, if you get exactly one six, you don't get nonte, nor exactly two, and so on.
If you have several possibilities which exclude each other (i.e. if one of then occurs, none of the other has occurred), then the probability of getting any of those possibilities is just the sum of the probabilities of the individual probabilities.
"No more than 10" is "None, or one, or …, or 8, or 9, or 10".
"At least 10" is "more than 9", which is the opposite of "not more than none".
Since you already know how to calculate the probability of "Exactly $k$ sixes", those hints should enable you to solve the other questions.


Como armazenar imagens num vetor Android?

Question: Tenho imagens dentro da drawable e para acessa-la basta R.drawable.myimage.
Como armazenar essa imagens num vetor?
Comment: Já tentou armazenar apenas a referencia delas?
Comment: Qual é o seu intuito?
Comment: @ramaral é o seguinte para poder passar por parâmetro, exemplo `image[0], image[1]....` mudando os números com um incrementador
Comment: @ramaral ou utilizando String para acessa-las
Comment: @DiegoF não como seria?
Answer: Não guarde as imagens, guarde os seus resource Id usando um int[]:
int[] imagensIds = {
    R.drawable.image1,
    R.drawable.image2,
    R.drawable.image3
};

Você pode passar todas as imagens para um método:
processaImagens(imagensIds);

ou apenas uma:
processaImagem(imagensIds[1]);

Declare o métodos da seguinte forma:
private processaImagens(int[] imagensIds){
}

private processaImagem(int imagemId){
}

Comment: Pra falar a verdade eu não tinha nem chegado a pensar em algo pra responder, a sugestão foi meio que automática quando vi a pergunta. :/
Comment: +1 Acredito que essa é a melhor forma.
Comment: @DiegoF Eu ainda esperei que você respondesse.
Comment: @ramaral é possível colocar os  ` resource Id` num bloco notas ou seja `arquivo.txt` fazer ler esse arquivo e armazenar num vetor de inteiro? se sim como?
Comment: Sim é possível. Um `resource Id` não é mais do que um inteiro. Pode usar SharedPreferences para isso.
Comment: Como você sabe não devemos utilizar os comentários para fazer e responder novas perguntas:)
Comment: @ramaral beleza vou abri uma nova pergunta
Answer: como esta resposta está muito tempo sem complemento vai ai:
///crio um Gallery
Gallery gallery1;
//declara um array de imagens já coladas no Drawable como pic0....:
Integer[] imagensID = {
R.drawable.pic0,
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3
};
no onCreate eu inicio e faço a logica para pegar as imagens
//////////galeria de fotos, carroussel e tudo mais
Gallery gallery = (Gallery)findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
           //se chegar na ultima imagem, volta para a primeira
            if (position >=9){
                gallery.setAdapter(new ImageAdapter(getApplicationContext()));
                return;
            }
        }
    });

    gallery.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
         return true;
        }
    });
    ///////fim da galeria de fotos

//ciro uma classe para configurar as imagens e tal
///inicio do image adapter, peguei em algum lugar e melhorei para o meu uso
///se lembrasse daria os créditos
public class ImageAdapter extends BaseAdapter{
private Context context;
private int itemBackground;
public ImageAdapter(Context c){
context =c;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground=a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
@Override
public int getCount(){
return imagensID.length;
}
@Override
public Object getItem(int position){
return position;
}
@Override
public long getItemId(int position){
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageView = new ImageView(context);
imageView.setImageResource(imagensID[position]);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setPadding(10, 10, 10, 10);
            imageView.setLayoutParams(new Gallery.LayoutParams(650, 600));
            imageView.setBackgroundResource(itemBackground);
            return imageView;
    }

//pega a imgem e seta na imageView com o tamnaho do setLayoutParams
public View getView1(int position, View convertView, ViewGroup parent){
ImageView imageView = new ImageView(context);
imageView.setImageResource(imagensID[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(780, 1280));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
///fim do image adapter


Mudar cor do link quando passar o mouse por cima no Bootstrap

Question: Comecei a aprender bootstrap hoje e fiz um site de teste bem simples. Nele tem um navbar com alguns links. A questão é que não consigo trocar a cor nos links ao passar o mouse de jeito nenhum, só fica com a interação padrão (escurecer ao passar o mouse). Se alguém puder me ajudar, ficaria grato, segue o código

HTML

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

        <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Staatliches" rel="stylesheet">

        <link rel="stylesheet" type="text/css" href="css/style.css">
        <title>Teste</title>

                    Teste

Indicadores

Aprendizagem

Gráficos

Simulador

Carteira

Registrar-se

Entrar

Exemplo

Testando a página em Bootstrap

CSS

body {
    font-family: "Poppins";
    margin: 0px;
}

/*----------Navbar----------*/

.container-fluid a:hover{
    color: rgb(26, 244, 183);
}

#navbar {
    background-color: rgb(46,41,58);
    margin: 0px;
}

.navbar, .navbar-default {
    border: none;
}

nav a:hover {
    color: aqua;
}

.navbar-nav {
    color: aqua;
}

Comment: Temos uma solução para esta no Stackoverflow.com: https://stackoverflow.com/questions/16625972/change-color-of-bootstrap-navbar-on-hover-link
Comment: Era só colocar a declaração **!important** no hover ficando assim: **`nav a:hover { color: aqua !important; }`**
Answer: A solução seria está?
.navbar-default .navbar-nav>li>a:focus,
.navbar-default .navbar-nav>li>a:hover {
    color: aqua;
}

Comment: Seria bom você aprender a utilizar as ferramentas de debug dos navegadores, isso te ajuda a identificar quais seletores css estão afetando os elementos que você quer alterar
Comment: Funcionou amigo, valeu!
Answer: Pelo estilo do CSS do Bootstrap, os links  da nav tem mais força, ou seja, tem maior especificidade (veja como calcular a especificidade nesta resposta) do que quando você coloca nav a{ color: aqua; }. O Bootstrap define as propriedades dos links com o estilo abaixo:
.navbar-default .navbar-nav>li>a {
    color: #777;
}

Ou seja, o estilo acima tem mais força do que:
nav a{
   color: aqua;
}

E isso vale o mesmo para o :hover. Se você deseja forçar que uma propriedade tenha prioridade, ignorando estilos com maior força e prioridade, basta adicionar !important à propriedade:
nav a:hover {
    color: aqua !important;
}

Veja:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

        <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Staatliches" rel="stylesheet">

        <link rel="stylesheet" type="text/css" href="css/style.css">

        <title>Teste</title>

                    Teste

Indicadores

Aprendizagem

Gráficos

Simulador

Carteira

Registrar-se

Entrar

Exemplo

Testando a página em Bootstrap

Comment: Deu certinho aqui, valeu!


java.sql.Date and java.sql.Time to org.joda.time.DateTime

Question: As the question title says,
I have java.sql.Date and java.sql.Time as input
Now I want to convert them to a DateTime object, but since the getDay, getYear etc. methods are deprecated I can't figure out how to combine the two...
Comment: Can you get a `long` from the sql data types, and use that to construct a joda DateTime?
Comment: I can get a long from both, but adding them together doesnt do the job...
Comment: What's the idea behind adding these types? They both represent a time since the Epoch.
Comment: You can just pass your `java.sql.Date` or `java.sql.Time` to the constructor of Joda's `DateTime`, but it sounds like you want more than just that. What do you mean exactly by "adding them together"?
Comment: It sounds like his date is stored in one column, and the time is stored in a separate column in his database. Luc, can u explain?
Comment: Yes, the date and time are stored in different columns, but for my output I need a "beginDateTime" and an "endDateTime" where begin contains the date + startTime and end contains date + endTime
Comment: @Luc - Just check my answer. See if that helps your cause.
Answer: Just see if this does the trick for you.
Date date = new Date(System.currentTimeMillis()); // Prints 2013-03-08
Time time = new Time(System.currentTimeMillis()); // Prints 15:40:33

String myDate = date + " " + time;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date utilDate = new java.util.Date();
try {
    utilDate = sdf.parse(myDate); // You get a Java Util Date object(Fri Mar 08 15:40:33 IST 2013)
} catch (ParseException pe) {
   // TODO something.
}

DateTime dateTime = new DateTime(utilDate); // You get your JODA object.

Comment: Using formatting to construct a Date is inefficient, and ignores joda time's rich API. Why not simply combine a LocalDate and LocalTime into a DateTime?
Answer: You could create a DateTime object from the date and add a Duration object to that DateTime object, resulting in a single object whcih is the Date + Time instant in time represented by your input.
Something like the following:
Date d = //your Date
Time t = //your time

DateTime result = new DateTime(d).plus(t.getTime());

This will result in an Immutable object representing the instant you want....I I understood your question correctly and what you are after is a way of "adding" two different classes representing time.
Answer: Just do some tricks on java.sql.Time: calculate the duration. java.sql.Time set date components to January 1, 1970 implicitly.
    java.sql.Date epoch = new Date(70, 0, 1);
    java.sql.Date date = new Date(113, 2, 8);
    java.sql.Time time = new Time(1, 1, 1);
    DateTime dt = new DateTime(date.getTime())
            .plus(time.getTime() - epoch.getTime());
    System.out.println(date);
    System.out.println(time);
    System.out.println(dt);


Evitando comparação "!=null" em Java

Question: Eu trabalho com Java e por inúmeras vezes eu tenho que fazer um teste object != null no objeto antes de acessá-lo para evitar NullPointerException
Entretanto, acho que essa prática acaba tornando o código muito feio, sujo e difícil de se ler.
Existe alguma alternativa para evitar essa comparação todo momento que eu desejar acessar o método de um objeto?
Por exemplo:
System.out.println("Nome: " + pessoa.getNome());

Para ficar seguro se torna:
if (pessoa!=null) {
    System.out.println("Nome: " + pessoa.getNome());
}

Comment: A propósito, no rodapé da pergunta ele colocou: "Baseado em uma pergunta famosa do SO". Isso é atribuição suficiente, imagino.
Comment: Interessante, tanto pergunta quanto resposta são traduções da fonte que você listou.
Comment: Sim. O que você quis dizer?
Comment: Foi só uma constatação, não vejo nada de errado. No stackoverflow em inglês, um dos requisitos é que o autor faça uma pergunta sobre um problema concreto que está encontrando, não teórico. Não sei quais são as recomendações para a versão em português, mas acho que seria mais sincero se colocasse um aviso no topo dizendo que pergunta e resposta apareceram originalmente na versão em inglês, com link para ela. Da forma que está, parece que a pergunta e resposta são originais suas, com "fonte" na versão em inglês. Fonte, neste caso, sendo "cópia" (geralmente, "fonte" é somente uma referência).
Comment: Entendo seu ponto. Também achava incorreto/estranho isso a princípio, mas tem um post no meta que cita exatamente isso: _Apoiamos a re-escrita de perguntas ou respostas do Stack Overflow, desde que elas beneficiem a sua comunidade. Tenha sempre em mente, porém, que traduções automatizadas ou mal escritas não são permitidas._ [Aqui NÃO É o stackoverflow.com](http://meta.pt.stackoverflow.com/questions/1/aqui-no-o-stackoverflow-com). A propósito, não simplesmente traduzi, dei meu ponto de vista nisso. Isso foi um problema real que já enfrentei no passado e aquela pergunta/resposta já me ajudaram.
Comment: Ok, também acho que esta pergunta/resposta beneficiam a comunidade, mas se fosse o autor da pergunta/resposta dos originais, teria a sensação de que é uma cópia sem atribuição apropriada da autoria, por mais que tenha um ou outro elemento original :-)
Comment: O que acharia o autor dessa pergunta ou resposta no SO.com então: [Por que processar uma lista ordenada é mais rápido que uma não ordenada?](http://pt.stackoverflow.com/q/3163/3117) ? :-)
Comment: Não tinha visto, mas faria o mesmo comentário que fiz aqui...
Comment: Link original: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java
Answer: Qual estilo de código utilizar?
Existem dois tipos de programação que podemos utilizar: por contrato ou defensiva.

A programação por contrato é algo mais difícil de encontrar por aí. Ela prega que a pessoa deve ver o que o método espera, o que a documentação diz para usar e seguir. Problema do desenvolvedor se não seguir essas regras. Erros acontecerão mas isso não importa, ele não enviou os dados direito. Como isso afeta o código? Você não precisaria validar os atributos recebidos e simplesmente deixar o erro estourar. O problema dessa abordagem são os diversos erros de runtime que aparecerão e também a necessidade constante de uma documentação detalhada e atualizada.
Já a programação defensiva prega que você deve validar tudo que for importante para o método chamado. Validar desde os atributos simples (String, int, etc) como objetos do seu modelo (Casa, Carro, etc). A desvantagem disso é que você sempre terá um if a mais em seu código para validação.

O que posso fazer para validar?
Você pode usar diversas técnicas para validar uma atributo:

Usar bibliotecas que diminuam o código. O ApacheCommons, por exemplo, tem diversas classes que facilitam a validação. Posso citar o StringUtils.isBlank(texto) para validar se o texto está vazio ou não. E o interessante é que para facilitar a leitura do código, eles criaram o método isNotBlank(texto) que é a negação.
Utilizar o JSR 303: Bean Validation. É a especificação de validação dos dados. Basta anotar com um @NotNull e pronto. Dê uma olhada no Hibernate Validator.
Fazer um IF na unha. Essa é uma solução bem simples, mas como já foi dito deixa o código maior. O melhor mesmo seria isolar esse código em um método a parte.
Utilizar assert. Esse eu não recomendo e para falar a verdade, ninguém recomenda a utilização do assert em produção. Ele mata a thread que invocou o método.

Conclusão
Para esse tipo de situação não existe uma solução perfeita, mas existe alternativas que ajudam no desenvolvimento de um código mais limpo.
Comment: Uma prova de que aqui não é o SO.com :-). No final é a comunidade que decide o que é bom para cá ou não. Mas uma coisa me intrigou, pq não recomenda asserts? Vou pesquisar sobre isso, mas é a primeira vez que vejo alguém desrecomendando.
Comment: Justamente pelo seu conceito. Não é nem aconselhável fazer um try/catch em um assert (http://www.coderanch.com/t/396087/java/java/assert-statements-catch-blocks). O conceito do assert é, deu problema e a coisa foi feia. Tanto que para ativar um assert um parâmetro na JVM é necessário -ea por exemplo. No google é fácil encontrar referências que falam que o assert não deve ser utilizado em produção. http://stackoverflow.com/questions/4347164/appropriate-use-of-assert
Answer: Complementando as respostas acima, tenho mais uma sugestão.
Ela até que foge bastante do que você normalmente vê em Java, mas é muito interessante.
A API Google Guava, que é mais um desses canivetes que você tem disponíveis pra te ajudar, tem uma parte orientada ao tratamento de nulos.
Eles mesmos exemplificam na documentação mas vou deixar uns exemplos aqui pra clarificar a resposta.
Primeiro exemplo de como remover completamente null do seu código:
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // retorna true
possible.get();       // retorna 5

O que aconteceu aí? Você tem uma classe Optional<T> que pode ou não ter um valor, só que ela te obriga a tratar esse valor na hora, pois se você invocar get() sem um valor ali dentro, é lançada uma IllegalStateException, justamente para não  existir null em lugar nenhum.
Se quiser um valor default também é possível:
possible.or(0); // retorna o valor se existir, se não houver nada, retorna 0

A ideia é você realizar esses tratamentos longe da regra de negócio. Assim que os recebe do usuário, ou no momento em que os retorna do banco de dados, para que não se preocupe com isso nas partes mais complexas.
Se você clicar o link acima vai ver muito mais classes, exemplos e métodos utilitários.

"Null sucks." - Doug Lea
Answer: Esse é um problema que desenvolvedores sem muita experiência costumam enfrentar: eles ou não sabem ou não confiam no contrato que estão participando e na defensiva acabam exagerando na verificação por null's. Adicionalmente, quando escrevem o próprio código, eles possuem o hábito de retorna null's para indicar alguma coisa, e isso acaba gerando a necessidade de verificar por null's pelo método que tentou invocar o objeto.
Em resumo, exitem dois casos que pedem a verificação por null's:
1) Quando null não é uma resposta válida, em termos de contrato:
Nesse caso, use o recurso AssertionError ou apenas deixe a exceção ocorrer, use as informações geradas pelo error ou exception para debugar deu código e entender por que a condição indesejada aconteceu, então conserte sua lógica para evitar essa condição. Faça todos os tipos de testes possíveis, quanto antes o erro ou a exceção ocorrer melhor, você não vai querer descobrir um bug depois que houver lançado seu programa.
assertion é um recurso que foi adicionado ao Java 1.4 mas que ainda não é tão praticado pelos programadores. É excelente para encontrar bugs pois você pode fazer testes para se certificar que você está tendo o resultado esperado em determinados pontos do programa.
"- Mas eu posso fazer esses testes usando ifs, correto?"
Correto, entretanto com assertions você testa de uma forma muito mais prática pois não precisa escrever todo um código de manipulação e exibição da mensagem de erro. Além do mais o assert não é habilitado por padrão, logo você pode habilitá-lo enquanto debuga seu programa e quando distribui-lo os asserts vão normalmente desabilitados. Usando uma lógica com o if você deve se lembrar de apagar o código de depuração de erros antes de distribuir seu programa para não correr o risco de exibir uma mensagem para o usuário que nunca deveria ter sido exibida.
Sintaxe:
assert <condição>

ou
assert <condição> : <objeto>

Se a condição falhar um AssertionError é lançado. Caso um objeto tenha sido indicado no segundo parâmetro o método toString() do objeto será adicionado à informação do erro lançado pelo AssertionError.
Exemplo:
public Pessoa obterPessoa(int id) {
    Pessoa resultado = null;
    if (id > 50) {
        resultado = datasource.getPessoa(id);
    } else {
        resultado = new Pessoa(id);
    }
    assert resultado != null : "pessoa nula no método obterPessoa()";

    return resultado;
}

Em resumo:

Conheça seu contrato, debug-o e confie nele.

2) Se null for uma resposta válida em termos de contrato:
Nesse caso não há muita escolha, você tem que testar o objeto antes de usá-lo.
Ou se quiser melhorar seu código você pode muda-lo e inicializar seus objetos e seus atributos, para eles nunca retornarem null, nem que o método do objeto retorne vazio isso já evita o temido NullPointerException.
Talvez você queira dar uma olhada no Null Object Pattern
Exemplo:
public interface Animal {
    public void makeSound();
}

public class Dog implements Animal {
    public void makeSound() {
        System.out.println("woof!");
    }
}

public class NullAnimal implements Animal {
    public void makeSound() {
    }
}

Ao invés de inicializar um objeto da class Animal como null inicialize-o como NullAnimal
Fonte(s): Avoiding "!= null" statements in Java?

Evitando comparação "!=null" em Java


unsupported operand type error when adding objects within list using sum function

Question: I have a Serie class implemented to represent series of data and it's tag. When I add Serie objects and also numbers I get the expected output. However when I sum the same elements within a list I get following error message:

TypeError: unsupported operand type(s) for +: 'int' and 'Serie'

Toy example code
As a toy example code to understand the problem we can use:
import pandas as pd
import numpy as np

class Serie(object):

    def __str__(self):

        s = "> SERIE " + str(self.tag) + ": \n"
        s += str(self.data)
        return s

    def __init__(self, tag=None, data=pd.DataFrame()):
        """
        Creates object Serie

        @type tag: str
        @param tag: Tag for the Serie
        """
        self.tag = tag
        self.data = data

    def __add__(self, other):
        if isinstance(other, int) or isinstance(other, float):
            tag = str(other) + "+" + self.tag
            serie = Serie(tag)
            serie.data = self.data + other
        else:
            try:
                tag = self.tag + "+" + other.tag
            except:
                print ("ERROR: You can't add to somehing that is not a Serie or a number." )
                return None
            serie = Serie(tag)
            serie.data = self.data + other.data
        return serie

s1 = Serie("fibonacci",pd.Series([1,1,2,3,5,8]))
s2 = Serie("2power",pd.Series(np.linspace(1,6,6)**2))
s3 = 10
sumSerie = s1+s2+s3
print sumSerie

This prints the result as expected:
>>>
> SERIE 10+fibonacci+2power:
0    12.0
1    15.0
2    21.0
3    29.0
4    40.0
5    54.0
dtype: float64

Error when using sum of objects within list
However when I run following lines:
l = [s1,s2,s3]
sum(l)

I get error message:

sum(l)
  TypeError: unsupported operand type(s) for +: 'int' and 'Serie'

And same error message is displayed when I run:
l2 = [s1,s2]
sum(l2)

But in l2 list there is no int variable.
Questions
Why is this error message being displayed? This is confusing as I was able to sum the objects outside the list.
Is there something I can do in order to achieve performing the sum of the objects within the list?
EDIT
As suggested in the comments, I added the __radd__ to correctly overload the add method. So I added the below lines to the Serie class:
def __radd__(self,other):
    return self.__add__(other)

Then the sum works. But not as expected.
If I run the below code:
>>> print sum(l)

I get this output:
> SERIE 10+0+fibonacci+2power:
0    12.0
1    15.0
2    21.0
3    29.0
4    40.0
5    54.0
dtype: float64

Which is definitely not the same I expected. There is a +0 extra within the tag. How can this be? However if I use the option I stated in my answer print np.array(l).sum() the result is correct.
EDIT 2
After overloading add method correctly I was suggested to use below method to perform the sum as expected:
reduce(lambda a, b: a+b, l)

This approach worked to be able to use sum function for the list and get the correct result.
As stated by pault in the comments in sum method "start defaults to 0" as detailed in sum function's documentation. That was why the extra +0 was being added to the tag before.
In conclusion I believe I would preferrably use the option using numpy.sum function instead:
np.array(l).sum()

Comment: You need to implement `__radd__` as well. While `s2+s3` works for you currently, you will see that `s3+s2` will not.
Comment: That is because as stated in the [docs](https://docs.python.org/2/library/functions.html#sum) you linked *"start defaults to 0"*. Try: `reduce(lambda a, b: a+b, l)` (or use `operator.add` instead of the `lambda`).
Comment: I implemented this on `python 2.7` and `python 3.5` and got same results
Comment: Possible duplicate of [How to properly overload the \_\_add\_\_ method?](https://stackoverflow.com/questions/36785417/how-to-properly-overload-the-add-method)
Comment: Thanks @pault, this acomplishes one of the issues. But the output is not the same as the one I expect. And I believe this is definitely not a duplicate of [this post](https://stackoverflow.com/questions/36785417/how-to-properly-overload-the-add-method)
Comment: Thanks @pault. Using `reduce(lambda a, b: a+b, l)` did the trick. However I think I would go for using `np.array(l).sum()` instead.
Answer: Not sure why using the sum function is not possible. But a workaround to get the desired output from the lists would be to create a numpy array from the list and use numpy.sum function as you can see below:
np.array(l).sum()

This gives the sum of the objects from the list as expected.
Comment: I would still like to know why the `sum(l)` is not possible. I guess it's the same reason why you can't do something like `sum(["a","b"])` as explained in [sum function's documentation](https://docs.python.org/2/library/functions.html#sum).


OCSP Location error in pkiview.msc. But OCSP responders seem to work

Question: I am currently setting up a new internal Windows PKI infrastructure in our organisation, to replace an old setup.
Things are mostly fine, but the OCSP location has the status "Error" in the pkiview console. When I check a certificate with certutil (certutil -URL test-certificate.cer or certutil -urlfetch -verify test-certificate.cer) it shows up as verified. So the responder does seem to work.

Does anyone know why the error status might show up in pkiview? Or where to find relevant logs about this error?
Some more info about the setup:

As you can see in the image, it's a two tier PKI with an offline root CA and a domain joined issuing CA.
The AIA and CDP locations are located on two Ubuntu-based Nginx servers, with keepalived for HA purposes.
A script on the Nginx servers fetches the new CRL from the issuing CA every 15 mins.
The same two Ubuntu servers have a second Nginx server block, which runs a load balancer to direct ocsp requests to two ocsp responder servers. This way, the certificates can contain just one ocsp url, and clients do not have to wait for timeouts when one ocsp responder would be down.

When googling the problem I found that this might be due to a stale CA-Exchange certificate. But renewing that did not help.
Update
I tested this with Wireshark and when launching pkiview, no ocsp request is actually made. When running certutil -URL test-certificate.cer Wireshark clearly shows the ocsp request and response.
Answer: After some more searching I figured it out.
For the ocsp responder servers I used the same array as the old pki setup, since you can simply add multiple configurations to an array.
When these servers were set up, i followed this guide to get a nicer url for the ocsp location. (http://ocsp.domain.com instead of http://ocsp.domain.com/ocsp) This involved creating a new IIS site and editing an IIS config file.
This worked fine for clients in in the past, and still does. But seems to cause the error in pkiview. In the past, the ocsp location was not added to endpoint certificates. It was just used for one application that had the urls in it's config file. So it did not show up in pkiview.
When we reverted back to the standard IIS configuration and renewed the CAExchange certificate, the error went away.


reduce to the case $[0,1]$ in equidistribution modulo $1$

Question: I am trying to prove a theorem using an optimal solution. Given $(y_n)_{n \in \mathbb{N^{*}}}$ such that $\exists \delta > 0, \forall n \in \mathbb{N^{*}} y_{n+1} - y_n \geq \delta$ then for almost every $\xi \in \mathbb{R}$ (Lebesgue) the sequence $(\xi y_n)_{n \in \mathbb{N^{*}}}$ is equidistributed modulo $1$.
I found a proof considering an arbitrary interval $[a,b]$ but some people told me it's sufficient to prove the result for almost every $\xi \in [0,1]$ but I am not convinced. In fact, if we prove the result just for almost every $\xi \in [0,1]$ the sequence $\xi y_n$ does not cover all the interval $\xi \in [0,1]$.
I am trying to find a counterexample, if we have a sequence $ \frac{1}{16} \leq y_n \leq \frac{1}{2}$ then multiplying by $\xi \in [0,1]$ gives us  $ 0 \leq \xi y_n \leq \frac{1}{2}$ and if we take $\xi \in [1,2]$ we got $ 0 \leq \xi y_n \leq 1$. Do you see what I mean? I think that the argument reducing to $[0,1]$ is not always true.
Thanks in advance !
Answer: I discovered that such an example does not exist. In fact, we have $y_{n+1} - y_{n} \geq \delta$ so $\lim\limits_{n  \longrightarrow +\infty}^{}$. If we suppose that we have proved the result for almost every $\xi \in [0,1]$. Then the result is true for almost every $\xi \in \mathbb{R}$. In fact, if we take $a > 0$, then we got $a y_{n+1} - a y_{n} \geq a \delta > 0 $   so $a \xi y_n$ is equidistributed for almost every $\xi \in [0,1]$ then $\xi y_n$ is equidistributed for almost every $\xi \in \mathbb{R}^{+}$. Then we deduce the result (because if ${x_n}$ is equidistributed modulo $1$ then ${-x_n}$ is equidistributed modulo $1$.


Flutter and Firestore: How can access variables from Stateful Widget to create a new document?

Question: i want to use a final variable from a StatefulWidget inside a StatelessWidget to create a new document in Firestore.
But i get always the same issue: Only static members can be accessed in initializers
My StatefulWidget Code:
class UserProfile extends StatefulWidget {
  UserProfile({this.auth, this.onSignedOut, this.userID});
  final BaseAuth auth;
  final VoidCallback onSignedOut;
  final String userID;

   @override
     _UserProfileState createState() => new _UserProfileState();

}

My StatelessWidget Code:
class _UserProfilState extends State<UserProfile> {
  final DocumentReference userdocuments =
    Firestore.instance.collection("Users").document(widget.userID); //Here i get the Error, because widget.userID
}

My Question: How can i use the the userID Variable from the StatefulWidget, to create a new document based on the userID. Thanks for our help
Answer: You can get the value in the initState method
class _UserProfilState extends State<UserProfile> {

DocumentReference userdocuments;

@override
 void initState() {
   userdocuments =
   Firestore.instance.collection("Users").document(widget.userID);
   super.initState();
  }
}


Elastic IPs in Amazon EC2

Question: When I use Elastic IPs in I can't use SSH. When I try to login, following message is show
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.

Comment: What is your question?
Comment: I got it. after edit .ssh/known_hosts and it's OK,now.
Answer: Edit your .ssh/known_hosts file and delete the line corresponding to your AMI.
The problem is that the first time you connected, ssh saved the remote key of that machine you connected to, and when you enabled Elastic IPs, that remote key changed.
http://developer.amazonwebservices.com/connect/thread.jspa;?messageID=104781&#104781
Answer: Alternatively, use ssh-keygen -R <hostname|IP address> to remove the entry from the known_hosts file.

Elastic IPs in Amazon EC2


SQL query: group and count distinct values

Question: Given this DB table:
A_column       B_column
---------------
A1      1
A1      2
A1      2

A2      1
A2      1
A2      1

A3      2
A3      3
A3      4
A3      5

How do I write SQL SELECT query to print out number of unique values in B_column per value in A_column, so output would be like this:
A1     2
A2     1
A3     4

I tried this, but doesn't seem to work properly:
SELECT A_column, count(B_column) FROM table GROUP BY A_column

Answer: Use distinct:
SELECT A_column, count(distinct B_column) FROM table GROUP BY A_column


Why my does drawer navigator screen has no header title, using nested (StackNavigator, DrawerNavigator)

Question: I have problem regarding disappeared header title, Currently I used Nested StackNavigator and DrawerNavigator, I have module when the user is logged in they use the drawer navigator else they will back to stack navigator.
Problem: Why does my header title disappeared ?
Here is my App.js
    const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();

const UnauthenticatedScreen = () => {

    return (
        <Stack.Navigator>
                <Stack.Screen
                    name="Login"
                    component={Login}
                    options=
                    {{
                        headerShown: false,
                    }}
                />
                <Stack.Screen
                    name="Registration"
                    component={Register}
                    options={{
                        headerStyle: {
                            backgroundColor: '#4ABDFF'
                        },
                        headerTitleStyle: {
                            color: '#fff',
                        },
                        headerTintColor:'#fff',
                    }}

                />

                <Stack.Screen
                    name="Privacy"
                    component={PrivacyPolicy}
                    options={{
                        headerStyle: {
                            backgroundColor: '#4ABDFF'
                        },
                        headerTitleStyle: {
                            color: '#fff',
                        },
                        headerTitle:'Privacy Policy',
                        headerTintColor:'#fff',
                    }}
                />

                <Stack.Screen
                    name="RegistrationSuccess"
                    component={RegistrationSuccess}
                    options=
                    {{
                        headerShown: false,
                    }}
                />
        </Stack.Navigator>
    )

}

const AuthenticatedDriverScreen = () => {
    return (
        <Drawer.Navigator drawerContent={props=><CustomDriverDrawer {...props} />} initialRouteName="DriverDashboard">
            <Drawer.Screen
                name="DriverDashboard"
                component={DriverDashboard}
                options={
                    {
                        drawerLabel: 'Home',
                        drawerIcon: ({focused, color, size}) => (
                            <Icon type="font-awesome" name="home" style={{fontSize:size, color:"black"}} />
                        ),

                    }
                }
            />

        </Drawer.Navigator>
    )
}

function Navigator() {
    const isLogin = true;
    return (
        <NavigationContainer>
         {isLogin ? <AuthenticatedDriverScreen/> : <UnauthenticatedScreen/>}
        </NavigationContainer>

    )
}

Authenticated User Screen:

Very well appreciated for your help.
Comment: drawer not providing header
Comment: @NishargShah question. how have a header title when i acess my dashboard?
Comment: bind both screens into createStackNavigator and you can access it
Comment: can you please deep more explain or have example for that @NishargShah
Comment: please create demo problem in online editor ( snake expo ), so I can easily modify it and solve your problem
Comment: Hi @NishargShah https://snack.expo.io/Xdx8BWWjO
Answer: First of all, you need to remember that thing React Navigation providing drawer functionality and screen functionality separately.
for connecting two functionality in one you need to bind the screen with a drawer so you can see both things in one go.
that's why first you need to make one screen navigator that contains single/multiple screen(s) so you can bind that navigator with a drawer like the below code.
const BindedScreenComponent = () => {
    return (
      <Bind.Navigator>
        <Bind.Screen
            name="Bind"
            component={() => <Text>Bind</Text>}
        />
      </Bind.Navigator>
    )
}

after that, you need to bind that code into the drawer component so the drawer component can render a whole navigator and give you the desire results
<Drawer.Screen
    name="DriverDashboard"
    component={BindedScreenComponent}
    options={
        {
            drawerLabel: 'Home',
        }
    }
/>

snake: https://snack.expo.io/@nishargshah/react-navigation-5-boilerplate
Comment: Hi Nishard Question, How to pass the binding on the CustomDrawer.js ?
Comment: Why you want to pass it in customer drawer?
Comment: Hi @Nisharg. your example is all good, however there is problem on the options. i can't configured the header bar
Comment: headerTintColor:'#fff' if i set this to the options, there is no changing on the binded screens
Comment: can you explain more deep, so incase someone encounter this problem they will understand more what you suggest to me.
Comment: Based on your explanation how the user access the nested navigator screen? example when the user click the Login button if true user will move on the screen AuthenticatedDriverScreen. how the binded  screen component will work on that?
Comment: here is a very good article https://reactnavigation.org/docs/screen-options-resolution/
Answer: My Old Explanation is correct for multiple screens bound in one screen but if you want only one screen with one drawer then you can use headerShown: true in your drawer options so, it will automatically show the header of the drawer.
Here is the example: https://snack.expo.io/@nishargshah/react-navigation-5-drawer


Found Eigenvector is close to the solution but not correct, what step am I missing?

Question: While practicing finding eigenvectors I have this matrix A:
\begin{bmatrix}
9 & 0\\
0 & 4
\end{bmatrix}
The eigenvalues I found are $\lambda = 9,4$
(A) In finding the corresponding eigenvector to $\lambda=9$, I did:
$A-I\lambda$
\begin{bmatrix}
9-9 & 0\\
0 & 4-9
\end{bmatrix}
\begin{bmatrix}
0 & 0\\
0 & -5
\end{bmatrix}
$-\frac{1}{5}R2 \rightarrow R2$
\begin{bmatrix}
0 & 0\\
0 & 1
\end{bmatrix}
Then I swapped R1 and R2
\begin{bmatrix}
0 & 1\\
0 & 0
\end{bmatrix}
(B) and got the eigenvector :
\begin{bmatrix}
0\\
1
\end{bmatrix}
But when I used those online calculators to check they gave me:
\begin{bmatrix}
1\\
0
\end{bmatrix}
Was I supposed to swap the columns in step (A) similar to row echelon form? I did not think to do that during my calculations since the second row is all zeros, but I am thinking that may be wrong. If someone can confirm if that is the missing step, I would really appreciate it. Thank you.
Comment: the square matrix you show in part A   is completely wrong.
Comment: Then you need to review how to solve equations properly. For matrix A and matrix B, the solutions have the form $(a,0)^T$ with $a$ arbitrary, yet you insist that you are solving them and getting the vector $(0,1)^T$? Let me put it plainly: solving with either matrix should be trivial, yet you get the wrong answer multiple times? You don't know how to solve a system that says $0=0$ and $x_2=0$? Then you don't know how to solve equations.
Comment: @WillJagy I re-did the problem and added in the steps to show what I did, though I still got the same matrix and so I don't see what you mean. Are you able to elaborate more now?
Comment: Your final matrix translates to the system of linear equations $x_2=0$. Yet you give as a solution a vector of the form $(x_1,x_2)^T=(0,1)^T$, that is, one that does *not* satisfy the system. Why?
Comment: @ArturoMagidin Okay I see what you mean. I don't see how it doesn't satisy the system because when I checked it by doing Ax (where x is my incorrect eigenvector), I got, following your notation, $(0,4)^T$ which is a scalar of x. So it is clear I am missing some sort of knowledge here. Also, with the given original matrix, you would end up with either $x_1=0$ or $x_2 = 0$ for each eigenvalue, no? How can I correctly determine which corresponds to the correct eigenvalue? If I am not being clear, let know and I shall rephrase.
Comment: Actually, is that itself the issue? That when multiplying the reduced row echelon matrix by $(x_1,x_2)^T$ (while set equal to $(0,0)^T$) and like above I get $x_2=0$ that I am supposed to let it be equal to some parameter, s, and then let the other value $x_1=0$ (and vice versa)?
Comment: You are lost. If $\lambda$ is an eigenvalue of $A$, and you calculate $A-\lambda I$, what you are then looking for is vectors $x$ such that $(A-\lambda I)x=\mathbf{0}$, not vectors that are mapped to nonzero scalar multiples of themselves.
Comment: @ArturoMagidin Yes, that is correct. Conceptually, I understand. It is computationally that is it does not match up and I am not sure where specifically. Is this one of those things where I look (or test and then adjust accordingly) and see if I have to "flip" the eigenvector? I think I may just be saying incorrect things.
Comment: No, you do not understand, conceptually or otherwise, and instead are wasting time writing nonsense. How about you take the matrix A, or the matrixB, and actually try to solve, **explicitly**, the equation $M\mathbf{x}=\mathbf{0}$? Don't "conceptualize". Just **solve**.
Comment: @ArturoMagidin I did solve it directly in that form, reached the same conclusion multiple times, and still was unable to pinpoint what I am doing specifically. That was the purpose of this post, to see if someone can clarify. I am a person who is trying to learn something new and unfamiliar and your last comment did not provide any guidance. Since you seem to have lost patience, you are able to stop engaging in what is now a lengthy comment section.
Answer: You found the eigenvalue $\lambda = 9$. You want to find a corresponding eigenvector, that is, a vector $x$ such that $Ax = 9x$, or equivalently, $(A-9I)x = 0$. Writing this as a matrix equation,
$$\begin{bmatrix} 0 & 0\\ 0 & -5 \end{bmatrix}\begin{bmatrix}x_1 \\ x_2 \end{bmatrix} =  \begin{bmatrix}0 \\ 0 \end{bmatrix} $$
So we want to find the $x_1, x_2$ that would make this true. To do this with row reduction, you have to remember what the values in the matrix represent, coefficients for $x_1$ and $x_2$. Swapping rows, multiplying by scalars, and adding rows do not change the underlying system. So we do those steps to make the matrix as simple as posssible before solving. Swapping columns is not allowed - this can completely change the system!
Your row reduction to $\begin{bmatrix} 0 & 1\\ 0 & 0 \end{bmatrix}$ is correct. Putting that back in our matrix equation: $$\begin{bmatrix} 0 & 1\\ 0 & 0 \end{bmatrix}\begin{bmatrix}x_1 \\ x_2 \end{bmatrix} =  \begin{bmatrix}0 \\ 0 \end{bmatrix} $$
Multiplying out to get the "traditional" system of equations, just so it is clearer what things mean.
$$\begin{align*} 0 x_1 + 1 x_ 2 & = 0 \\ 0 x_1 + 0 x_2&= 0\end{align*}$$
The second equation just says $0+0 = 0$, so that does not give any information. The first tells us $x_2 = 0$. In conclusion, $x_1$ is free (can be anything) and $x_2 = 0$. As a vector, this looks like $ \begin{bmatrix}x_1 \\ 0 \end{bmatrix}$ for $x_1$ being any number. You may recall that any scalar multiple of an eigenvector is also an eigenvector for the same eigenvalue. So we can simply state the eigenvector for $\lambda = 9$ is $ \begin{bmatrix}1 \\ 0 \end{bmatrix}$, knowing that this means any scalar multiple of that vector works, which is exactly what solving the equation told us. And to double check $$ \begin{bmatrix} 9 & 0\\ 0 & 4 \end{bmatrix}\begin{bmatrix}1\\ 0 \end{bmatrix} =  \begin{bmatrix}9 \\ 0 \end{bmatrix} = 9 \begin{bmatrix}1 \\ 0 \end{bmatrix} $$
This is exactly what we expect from an eigenvector for $\lambda = 9$, that $Ax = 9x$.
I hope this clarifies things and wasn't too long winded. Once you're very familiar with using row reduction to solve systems of equations, you might be able to do this without writing as many steps out. But for now, I would write out the "traditional" system of equations to make sure it is clear what is happening.
Comment: Your explanation is thorough and clear. I figured out my issue was that I was misinterpretting the results and how to represent them. I got $x_2=0$ and because that was the variable left, what I was doing was taking it's coefficient, 1, and I was thinking of $x_1$ as $0x_1$ and this is how I got my incorrrect eigenvector. Of course now it is clear what is going on, that I just take their respective values, i.e. like you said: $x_2=0$ and let $x_1=s$ thus giving the correct eigenvector).


Database Pager for a new entity type

Question: I have implemented a new entity type that requires paged access to DB and meet a probem with several pagers for independent entities on the same theme page.
The problem is that that entity can be used along with the node, thus two (or more) pagers may co-exist on the same page. The element property of PagerDefault apparently does not work (see discussion). In addition, PagerDefault simply uses $_GET['page']) to find required page number, which leads to even bigger confusion - both absolutely independed DB queries share same HTTP page query parameter.
What do you believe is good solution of this problem?
Further investigations have revealed a bug with EntityFieldQuery::pager()
Answer: I'm not sure I understand your problem ... Are we talking about like a node/edit page or a View? Or is this a menu page callback where you want node(s) and this entity both with paged output on a single html page ... ?
If you have written custom PHP/SQL/EFQ in a menu page callback, I see no reason you cannot explicitly set $element uniquely as needed in your queries.
Where is your http page query parameter coming from? A view? A url() you created by hand? If you have 2 pagers, you should have 2 $GET parameters ...
Edit: this is what I mean blog example
Comment: I have menu page callback. As far as I understand, I can not choose element in a reliable way - no collision detection implmented in PageDefault. As it is clear from documentation, that if I choose element number for one pager, I have to set element for all pagers to eliminate collision, which I can not do in my circumstances. I understand that it will work somehow, but without reliable guaranty of collision avoidance.

Probably, I am wrong and just do not get the pager concept.
Comment: sorry please list what you have on the page that requires pagers. A view? EFQ listings? what ...
Comment: I have a node that use EFQ listings for text posts and
I plan to have another entity (in another block) that retrieve different information from the DB, and should use pager to limit amount of data. The problem is if I can use PagerDefault extender for both pagers, or it is impossible.
Comment: Thanks, tenken. The blog example is really helpful. But in my case I can not be sure that a page will have just one pager, of if all pagers will be assigned with ID - my part of job is just a couple of modules, not a site.

Database Pager for a new entity type


Hibernate / JPA Why many-to-many join column id is false?

Question: to-many tables mapped like this :
Resume.java :
<code> @ManyToMany(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE
        })
 @JsonIgnore
   @JoinTable(
           name = "resume_skills",
           joinColumns = @JoinColumn(name = "skill_id"),
           inverseJoinColumns = @JoinColumn(name = "resume_id"))
 private List<Skill> skills = new ArrayList<Skill>();

 public void addSkill(Skill skill) {
     skills.add(skill);
     skill.getResumes().add(this);
 }
</code>
Skill.java
<code>   @ManyToMany(mappedBy="skills")
   @JsonIgnore
   private List<Resume> resumes;
</code>
I do this :
<code>Resume resumeToAdd = new Resume(resume.getGithubAdress(),
            resume.getLinkedinAdress(),
            resume.getCoverLetter(),
            resume.getPicture(),
            employee
            );

    resumeDao.save(resumeToAdd);

    Skill skill = skillService.findById(1).getData();
    System.out.println(skill);
    resumeToAdd.addSkill(skill);
    resumeDao.save(resumeToAdd);
</code>
But it occurs an error, for example it added a Resume with id 60 and it's trying to add mapping with skill id 60 But it cant because there is  no skill in database with id of 60, it should be 1. What did i miss here?
Answer: Looks like you mixed up the order of the mapping. It should be this:
<code>@JoinTable(
       name = "resume_skills",
       joinColumns = @JoinColumn(name = "resume_id"),
       inverseJoinColumns = @JoinColumn(name = "skill_id"))
</code>


Measurability in product space

Question: Given a probability space $(\Omega, \mathcal{F}, P)$ and a random variable $X$ defined on it, s.t. $X\geq 0$, I want to show that the mapping
$$(\omega, t)\mapsto \mathbf{1}_{\{X(\omega)\geq t\}}$$
is measurable on the measure space $(\Omega\times[0,\infty),\mathcal{F}\times\mathcal{B}([0,\infty)),P\otimes\lambda)$, for $\lambda$ denoting the Lebesgue measure.
My thoughts were to simply use the definition and look at the preimages of this mapping. One would then have, e.g.
$$\mathbf{1}_{\{X(\omega)\geq t\}}^{-1}(\{0\})=\{(\omega, t): X(\omega)<t\}=\{(\omega, t): \omega\in X^{-1}([0,t))\}.$$
Since $X$ is a random variable, it is measurable, so $X^{-1}([0,t))\in\mathcal{F}$. However, I cannot see at the moment why $\{(\omega, t): \omega\in X^{-1}([0,t))\}$ belongs to the product $\sigma$-algebra, since one coordinate depends on the other. I'm grateful for any hints.
Answer: If $a < b$ then there exists $q \in \mathbb{Q}$ such that $a < r < b$. Thus
$$\{(\omega, t): X(\omega)<t\} = \bigcup_{r \in \mathbb{Q}} \{(\omega, t): X(\omega)< r < t\}$$ where
$$\{(\omega, t): X(\omega)< r < t\} = \{(\omega, t): X(\omega)< r\} \cap \{(\omega, t): r < t\}$$
Futher
$$ \{(\omega, t): X(\omega)< r\}  = \{X^{-1}((\infty, r))\}\times [0, \infty) \in \mathcal{F} \times \mathcal{B}([0,\infty))$$
$$\{(\omega, t): r < t\} = \Omega \times (r, +\infty)  \in \mathcal{F} \times \mathcal{B}([0,\infty))$$
q.e.d.

Measurability in product space


$\int^{\pi}_0 \log{\sin{x}}dx$

Question: I saw a integral like this and try to solve it by using
$$
\sin{\frac{\pi}{n}}\sin{\frac{2\pi}{n}}\cdots\sin{\frac{(n-1)\pi}{n}}\ = \frac{n}{2^{n-1}}
$$
The $\log$ is based on $e$.
The following is what I try:
$$
\int^{\pi}_0 \log{(\sin{x})}dx=\underset{n\rightarrow \infty}{\lim}\overset{n}{\underset{i=1}{\sum}}(\frac{\pi}{n})\log{(\sin{\frac{i\pi}{n}})}\\=\underset{n\rightarrow \infty}{\lim}\frac{\pi}{n}\log{(\sin{\frac{\pi}{n}}\sin{\frac{2\pi}{n}}\cdots\sin{\frac{(n-1)\pi}{n}})}\\=\underset{n\rightarrow \infty}{\lim}\frac{\pi}{n}\log{(\frac{n}{2^{n-1}})}=\pi\underset{n\rightarrow \infty}{\lim}\frac{\log{(\frac{n}{2^{n-1}}})}{n}\\=-\pi\underset{n\rightarrow \infty}{\lim}{\frac{2^{n-1}}{n}\frac{2^{n-1}-n2^{n-1}\log2}{2^{2n-2}}}=-\pi\underset{n\rightarrow \infty}{\lim}{\frac{1-n2^{-1}\log2}{n}}\\=\frac{\log2}{2}\pi
$$
But I'm not sure whether I did right for the whole evaluation.
Please help me to check, appreciate.
BTW, my typesetting is by tablet, perhaps it's not neat.
Comment: $\lim_{n\to\infty}\frac{1}{n}\log(\frac{n}{2^{n-1}})=\lim_{n\to\infty}\log(\frac{n}{2^{n-1}})^{\frac{1}{n}}=\log\frac{1}{2}$?
Comment: @xfireskyx yes, after an easy checking, L'Hospital rule is right! so your mistake appears at $$\dots=-\pi\frac{1-n2^{-1}\log2}{n}$$, may be you lost $2^{n-1}$ when multiply.
Comment: You are wellcome, best wishes!
Comment: I'm a bit confused by the notation you have used, although I can say that the final answer should be twice that and negative. Edit : (I assume you mean base-10 log by log)
Comment: By log, do you mean log base 10 or the natural log?
Comment: @Philosophiae I try to make it clear. It's natural logarithm.
Comment: @allegro.sostenuto Natural log.
Comment: @monotoneoperator So the answer should be $\log{(\frac{1}{2})}\pi$ ?
Comment: @xfireskyx yes the answer should be $\pi\log\frac{1}{2}$.
Comment: @xfireskyx your proof has a little mistake in $$\dots=\pi\lim_{n\to\infty}\frac{1}{n}\log(\frac{n}{2^{n-1}})=-\pi\lim_{n\to\infty}\frac{2^{n-1}}{n}\frac{2^{n-1}-n2^{n-1}\log2}{2^{2n-2}}=\dots$$ I don't know  how to get this equality.
Comment: @monotoneoperator that's because the denominator tends to infinty, then in my mind, $\log(\frac{n}{2^{n-1}})$ tends to -$\infty$, so I put a negative outside in order to get $\lim\frac{\infty}{\infty}$ and use L'Hopital rule.
Comment: I think your idea is very beautiful, your answer connect the relation between the product $\sin\frac{\pi}{n}\dots\sin\frac{(n-1)\pi}{n}=\frac{n}{2^{n-1}}$ and the integral $\int_{0}^{\pi}\log(\sin x)dx$ which make my eyes lit up!
Comment: @xfireskyx L'Hospital rule? you say $\lim_{x\to\infty}\pi\frac{1}{x}\log(\frac{x}{2^{x-1}})$?
Comment: @monotoneoperator Yeah, but I see I don't need to do it.
Comment: @monotoneoperator Got it ! Thanks very much !
Comment: Doesn't using L'Hopital's Rule for this limit just result in an endless loop?
Comment: I'm still not at all sure how you got from the the first step to the second step in the limit, did you try using L'Hopital's Rule?
Comment: I've seen quite a few methods to evaluate this particular integral, and this is a particularly interesting approach. Well done to both you and @Philosophiæ who helped complete the proof.
Answer: While the method provided in the other answer is certainly the best way to solve this problem, if you are keen on understanding how to solve it via the limit approach you gave, the following would work:
$$\pi\lim_{n\to\infty}\frac{\ln\left(\frac{n}{2^{n-1}}\right)}{n}$$
From here, we can move the n in the dominator to the exponent of the argument of the logarithm like this:
$$\pi\lim_{n\to\infty}\ln\left(\left(\frac{n}{2^{n-1}}\right)^{1/n}\right)$$
In this case, since the natural logarithm is a continuous function we can swap the order of the limit and the function, yielding:
$$\pi\ln\left(\lim_{n\to\infty}\left(\frac{n}{2^{n-1}}\right)^{1/n}\right)$$
Which simplifies to:
$$\pi\ln\left(\lim_{n\to\infty}\frac{n^{\frac{1}{n}}}{2^{1-\frac{1}{n}}}\right)$$
The limit as $n$ approaches infinity of the denominator is clearly 2 as the exponent simplifies to $1-\frac{1}{\infty}$
The limit of the $n^{th}$ root of $n$ is 1, which can be shown using the following reasoning:
$$\lim_{n\to\infty}n^{\frac{1}{n}}=\lim_{n\to\infty}e^{\frac{\ln(n)}{n}}$$
By L'Hopital's Rule:
$$\lim_{n\to\infty}\frac{\ln(n)}{n}=\lim_{n\to\infty}\frac{\frac{1}{n}}{1}=0$$
Therefore:
$$\lim_{n\to\infty}n^{\frac{1}{n}}=\lim_{n\to\infty}e^{\frac{\ln(n)}{n}}=e^{0}=1$$
Resulting in $\pi\ln(\frac{1}{2})$ or $-\pi\ln2$
Comment: Nice solution (+1)!
Answer: The notation you have used is a bit confusing and your final answer is also wrong. But, this is a very standard question and there is a very neat way to solve this integral, which is as follows
$$
\begin{aligned}
\int\limits_{0}^{\pi}\ln (\sin(x))dx &= \int\limits_{0}^{\pi/2}\ln(\sin(x))dx+\int\limits_{\pi/2}^{\pi}\ln(\sin(x))dx\\
&= \int\limits_{0}^{\pi/2}\ln(\sin(x))dx+\int\limits_{0}^{\pi/2}\ln(\cos(x))dx\\
&=
\int\limits_{0}^{\pi/2}\ln\left(\frac{1}{2}\sin(2x)\right)dx\\
&=\int\limits_{0}^{\pi/2}\ln\left(\sin(2x)\right)dx-
\int\limits_{0}^{\pi/2}\ln(2)dx\\
&=
\frac{1}{2}\int\limits_{0}^{\pi}\ln(\sin(x))dx-\frac{\pi}{2}\ln 2
\end{aligned}
$$
and hence
$$\int\limits_{0}^{\pi}\ln (\sin(x))dx =-\pi\ln 2$$
Comment: I know that it's right, but I need to think twice what I ignored for the limit, thanks for your help and answer.

$\int^{\pi}_0 \log{\sin{x}}dx$


mySQL, Error 1215 - foreign key contraint

Question: My last foreign key (FK_kunde_id) in the bottom I get the following error: 1215 Cannot add foreign key constraint. This is my secound day of SQL programming so I'm trying my best solving it, but gotten completly stuck.
* I've searched through many forums for foreign key problems. But as it's exatcly the same as FK_film_id I would assume this should work as film_id is the primary key in film.film_id
* The speeling is exactly the same.
Anyone know what creates this error from the provided code underneath:

create database utleie
create table utleie.kunder (
    kunde_id mediumint not null auto_increment,
    fnavn varchar(45) not null,
    enavn varchar(45) not null,
    mobil int(8) null,
    epost varchar(45) null,
    gate varchar(45) null,
    gatenr varchar(5) null,
    postnr int null,
    primary key (kunde_id) );
create table utleie.postnummerr (
    postnr int not null,
    poststed varchar(45) not null,
    primary key (postnr) );
create table utleie.film (
    film_id int not null auto_increment,
    tittle varchar(45) not null,
    årstall int(4) null,
    regisor varchar(45) null,
    genre varchar(3) null,
    primary key (film_id) );
create table utleie.genre (
    genre_code varchar(3) not null,
    genre varchar(45) not null,
    primary key (genre_code) );
alter table kunder add constraint FK_postnr foreign key (postnr) references postnummerr(postnr);
alter table film add constraint FK_genre foreign key (genre) references genre(genre_code);
create table utleie.utleie_oversikt (
    utleie_id int not null auto_increment,
    film_id int not null,
    kunde_id int not null,
    primary key (utleie_id) );
alter table utleie_oversikt
add constraint FK_film_id
foreign key (film_id) references film(film_id);
alter table utleie_oversikt
add constraint FK_kunde_id
foreign key (kunde_id) references kunder(kunde_id);
Answer: Foreign key references must be the exact same type. In this case, you are using mediumint and int, which are not the same size.
You'd actually need to change your create statement
create table utleie.utleie_oversikt (
    utleie_id int not null auto_increment,
    film_id int not null,
    kunde_id mediumint not null,
    primary key (utleie_id) );

or, you can change it to an int on your kinder table.


Run Drupal in localhost then migrate to online once it's finalized

Question:
Possible Duplicate:
How to migrate from test environment to production environment?

I'm sure a lot of template designers work in localhost before going online. My question is what's the best way to take your installation online once you're done playing around with it? Do you redo everything or do you just copy your localhost db then import it online?
I'm using XAMPP in case it matters. :-)
Answer: Since this is mostly likely a one time move (because the online version with likely be your master now) I wouldn't worry too much about perfecting the process. Just...

Dump the mySQL DB and place within the root.
Zip/Tar the codebase, including the files directory.
Move it to the server (via SCP or FTP), unzip/untar the whole thing.
Import the DB via: mysql -hHOST -uUSER -pPASS DBNAME < db.mysql
Bam!

For continual workflow I usually use:

Backup & Migrate to create database backups.
Git to move the code around (.gitignore your files directory)
Answer: For a first installation, just exporting/importing a database dump usually works fine. See Copying Drupal to a webhosting service for more details.
After that, it gets tricker, have a look at other questions like How to migrate from test environment to production environment?.


mysql | Format the CONCAT function to have small brackets

Question: i have select in query
IFNULL(GROUP_CONCAT(DISTINCT CONCAT(ED.dependent_name, ED.date_of_birth))," No Dependents ") AS Dependents

The Result i get is like this..

Data is fine but problem with this is, it look untidy, i want to have date of birth in brackets
e-g for Employee E-02, i want record something like this, means enclose the date in small braces.
Muhammad Zubair (1998-12-15) ,Amir Khan (2000-12-15)

Is there any way i can update the above select statement and get the result like i want to have or any other better way to achieve a good looking result.?
MY Query:
SELECT
  `E`.`employee_code` AS Employee_Code,
  E.full_name AS NAME,
  E.father_name AS Father_Name,
  IFNULL(
    GROUP_CONCAT(
      DISTINCT CONCAT( ED.dependent_name '(', ED.date_of_birth, ')')), " No Dependents " ) AS Dependents
FROM
  (`employee` E)
  INNER JOIN `employee_project` EP
    ON `EP`.`employee_id` = `E`.`employee_id`
  INNER JOIN `permanant_contacts` PC
    ON `PC`.`employee_id` = `E`.`employee_id`
  INNER JOIN `ml_district` MLD
    ON `MLD`.`district_id` = `PC`.`district`
  LEFT JOIN `dependents` ED
    ON `ED`.`employee_id` = `E`.`employee_id`
    AND ED.trashed = 0
WHERE `E`.`trashed` = 0
GROUP BY `E`.`employee_id`

Answer: Have youy tried
CONCAT(ED.dependent_name, '(', ED.date_of_birth, ')')

Answer: Try
CONCAT(ED.dependent_name,CONCAT('(',CONCAT(ED.date_of_birth, ')')))

Comment: `CONCAT` takes an arbitrary number of arguments: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_concat. There's no reason to call it so many times, as depicted in the other answer.


How to add frontend form using custom content type?

Question: I new to Drupal and I created a custom content type which has few fields, like donation name, value, size, etc.
I want to add these fields as a form for user which they can fill in the frontend. I want to know there are existing for this task or it can be done through core module
Answer: This is usually done by giving the user permission to add the content type and presenting them with the /node/add/{content_type} page, letting them create their own page content.
Comment: Go to /admin/people/permissions
Comment: can you pls explain how i can give the user permissions..
Comment: try http://nodeone.se/en/learn-drupal-7-with-nodeone for a good start, it covers all of the basics like this question.
Answer: An ideal solution for your problem would be to use the webform module, which is used in similar scenarios and has many features out of the box.

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

It also has a very good documentation which will help you to get started.
Comment: The problem is it would not directly create content in his content type. [Entityforms](http://drupal.org/project/entityform) would be closer, but with his position in the Drupal learning curve, the core Content Types solution is the easiest for him to work with.
Comment: @Triskelion OP mentioned he takes data like _donation name_, _value_, _etc_, which might mean that there is a requirement for the OP to collect information of the donations made, which might contain sensitive information. And I don't find it logical to save the details of the (donating) user as a node. And with his position in the learning curve, I don't think learning webform is a bad idea if it suits his use case.


Why am I wrong: counting polynomials with degree at most $d$ in $\pmod p$ using value representation

Question: When working with polynomials in mod $p$ (restricting the coefficients and $x$-values to numbers in $\{0,\ldots, m-1\}$ where $p$ is prime), I am getting that the number of polynomials of at most degree $d$ where $d>p$ is greater than $p^{d+1}$, and am wondering what I am doing wrong.
I am considering polynomials as objects rather than as functions here. First of all, I know that the number should be $p^{d+1}$ as there are $d+1$ coefficients with $p$ possibilities each. However, when I count by value representation of a polynomial (specifying its value at $d+1$ points to uniquely determine a polynomial of at most $d$), I am seeing that the number should be greater. I see that each polynomial can be evaluated at $d+1$ points to uniquely determine the function corresponding to this polynomial object- when considering the number of value representations given fixed $x$ (such as $x=0,1,\ldots d$) there are $p^{d+1}$ possibilities for the value representation. However, each of these value representations corresponds to a unique polynomial function (as a function can't have 2 different values at the same input), and we know there is a polynomial of at most degree $d$ corresponding hereto because of Lagrange Interpolation- so there are at least $p^{d+1}$ polynomial functions in this field. However, each polynomial function corresponds to at least one polynomial object, and there exists polynomial functions which correspond to different polynomial objects, as by Fermat $x^p \equiv x \pmod p$, which we comprehend by having $d>p$. Therefore there are more polynomial objects of at least $d$ than polynomial functions in this field, meaning more than $p^{d+1}$ of them.
What have I done wrong?
Comment: It is *essential* to understand the difference between *formal* polynomials and polynomial *functions*, e.g. see [here](https://math.stackexchange.com/q/98345/242).  Many of the stumbling blocks in your recent questions are because you are trying to run before you have learned to walk, i.e. you have not yet studied ring theory but the questions are essentially ring theoretic. These matters will be much clearer once you learn rudimentary ring theory.
Comment: $m$ needs to be prime or none of what you've written is true. With that assumption, $x^d \equiv x^0 \bmod m$ only holds when $x \neq 0$. When $x = 0$ they differ. So they actually are different and $m^m$ is the correct count, of polynomial *functions* (again, when $m$ is prime). One has to distinguish between polynomials and polynomial functions here, also.
Comment: @QiaochuYuan did you mean to say $m^{d+1}$ rather than $m^m$? Also, combinatorically how do we count coefficients when sometimes $x^d$ and $x^0$ are the same, but sometimes they are not? Thanks
Comment: Well, $d = m-1$ so those are the same thing, I don't know why you're using two different variables here. Formally you can show that the polynomial functions $1, x, x^2, \dots x^{m-1}$ are linearly independent $\bmod m$; this amounts to showing that if a polynomial function of degree $\le m-1$ vanishes then its coefficients are identically zero.
Answer: For Lagrange interpolation, you need to specify the values of the polynomial at $d+1$ points for a polynomial of degree $d$. But if $d > p$ (or in fact, even if $d \ge p$), then even if you specify at all the elements in the field of integers mod $p$ , then you have only specified $p$ elements which is not enough. So Lagrange interpolation doesn't apply.


Links no javascript

Question: Bom dia pessoal, estou com um problema ao chamar um link no javascript, no php tenho uma regra onde todas vez que colocar #URL#link.... ela substitui pelo endereço do servidor. Exemplo #URL#public ele substitui para http://localhost/public, no javascript não consegui fazer funcionar. Se alguém puder me dar uma ajuda, vou colocar minha regra em php, e abaixo o javascript onde preciso ajustar.
php.config
date_default_timezone_set('America/Sao_Paulo');
error_reporting(E_ALL);
ini_set('display_errors',true);
define('URL','http://'.$_SERVER['HTTP_HOST'].'/sistema/');
define('DS', DIRECTORY_SEPARATOR);
define('PATH', getcwd().DS );
define('TEMPLATE', PATH.'view'.DS.'template.html');

Javascript que precisa ser ajustado
CKEDITOR.editorConfig = function(config) {
    config.filebrowserBrowseUrl = '#URL#sistema/public/plugin/ckeditor/kcfinder/browse.php';
    config.filebrowserImageBrowseUrl = '#URL#sistema/public/plugin/ckeditor/kcfinder/browse.php?type=images';
    config.filebrowserFlashBrowseUrl = '#URL#sistema/public/plugin/ckeditor/kcfinder/browse.php?type=flash';
    config.filebrowserUploadUrl = '#URL#sistema/public/plugin/ckeditor/kcfinder/upload.php?type=files';
    config.filebrowserImageUploadUrl = '#URL#sistema/public/plugin/ckeditor/kcfinder/upload.php?type=images';
    config.filebrowserFlashUploadUrl = '#URL#sistema/public/plugin/ckeditor/kcfinder/upload.php?type=flash';
};

Answer: Na página onde carrega o script do CKEditor, coloque isso

Algum outro script que utilize uma variável de nome igual poderá conflitar. Então, por isso nesse exemplo usamos um nome que dificilmente colidiria com outro em uso.
Algo mais elegante e "seguro" seria aplica namespace, mas o exemplo tornaria-se mais complicado. Caso tenha interesse em aprimorar os seus scripts, procure por javascript orientado a objeto.
Continuando, no script do CKEditor, trocaria para isso:
CKEDITOR.editorConfig = function(config) {
    config.baseHref = ckeditor_global_url;
    config.filebrowserBrowseUrl = 'public/plugin/ckeditor/kcfinder/browse.php';
    config.filebrowserImageBrowseUrl = 'public/plugin/ckeditor/kcfinder/browse.php?type=images';
    config.filebrowserFlashBrowseUrl = 'public/plugin/ckeditor/kcfinder/browse.php?type=flash';
    config.filebrowserUploadUrl = 'public/plugin/ckeditor/kcfinder/upload.php?type=files';
    config.filebrowserImageUploadUrl = 'public/plugin/ckeditor/kcfinder/upload.php?type=images';
    config.filebrowserFlashUploadUrl = 'public/plugin/ckeditor/kcfinder/upload.php?type=flash';
};

Aqui apenas definimos um valor para a propriedade config.baseHref.
Por fim, há formas diferentes para resolver. Como não deu muitos detalhes de como estão as suas páginas, quais as circunstâncias, etc, é inviável palpitar qual o melhor modo ou ao menos qual o modo mais apropriado para o seu caso.
Comment: Esse método não consegui adaptar. Daí fui tentando e consegui arrumar. Obrigado.
Answer: Consegui resolver dessa maneira.
CKEDITOR.editorConfig = function(config) {
        config.filebrowserBrowseUrl = url+'public/plugin/ckeditor/kcfinder/browse.php';
        config.filebrowserImageBrowseUrl = url+'public/plugin/ckeditor/kcfinder/browse.php?type=images';
        config.filebrowserFlashBrowseUrl = url+'public/plugin/ckeditor/kcfinder/browse.php?type=flash';
        config.filebrowserUploadUrl = url+'public/plugin/ckeditor/kcfinder/upload.php?type=files';
        config.filebrowserImageUploadUrl = url+'public/plugin/ckeditor/kcfinder/upload.php?type=images';
        config.filebrowserFlashUploadUrl = url+'public/plugin/ckeditor/kcfinder/upload.php?type=flash';
    };

Links no javascript


Estimate of a sample size of a search algorithm

Question: I am trying to estimate the order of the sample size of a probabilistic search algorithm. The problem is the following:
I have a counting problem where an oracle can identify the right solution, i.e. returns $1$ if the sample is a solution to the problem and $0$ otherwise. We assume there are $N$ items (search space) to check and $M$ are correct (the solution to our search problem).
During the procedure the algorithm can draw only $k$ samples from the search space which will lead to a series of oracle outputs $X_1, \ldots, X_k$ (hence a sequence of $1$s and $0$s). The algorithm then returns the estimate $S = N \cdot \sum_j X_j /k $
I now want to find the standard deviation of this algorithm in order to find the the number of samples for which the probability of estimatimating $M$ within an error of $\sqrt{M}$ is at least $3/4$.
Can anyone help me how to calculate it? I started with $(\Delta S)^2 = \sum_i \left( \left<S \right> - S_i \right)$ where $i$ is the number of all possible samples (i.e. $N$ over $k$ i suppose). But when plugging in $S$ i didn't know how to proceed. I know the right solution of the std has to be $\Delta S = \sqrt{M(N-M)/k}$ but i can't see neither how to get there nor how to proceed.
Comment: To my understanding you are not interested in the change of the standard deviation but the moment standard deviation as the sample size grows. This could be achieved by computing the current standard deviation using the samples at each step of the algorithm, assuming that the number of samples grow with each iteration. There are faster ways to find a treshold though. For example, using accelerated stochastic approximation. Did I understand your question correctly?
Answer: The variance, which is the square of the standard deviation, is $\sigma^2=\overline{S^2}-(\overline{S})^2$.
The expected value of $S$ is $\overline S=\sum_i\frac NkE(X_i)=\sum_i\frac Nk\frac MN$.
The expected value of $S^2$ is $$\overline{S^2}=\frac{N^2}{k^2}\left(kE(X_i^2)+k(k-1)E_{i\neq j}(X_iX_j)\right)$$
That is because there are $k^2$ terms in $S^2$, $k$ of these terms involve the square of the same $X_i$, and the other $k(k-1)$ involve a pair of different $X_i$.
What is the average value of $X_i^2$?  What is the average value of $X_iX_j$ when we know they are different samples?  Hint: Count the possibilities.
Comment: Thanks for the description! So i would say the following, but I am far from certain:
Since we deal with boolean values ($0$ or $1$) the expectation value of $X_i$ should be equal to the expectation value of $X_i^2$ so $\frac{M}{N}$, while the expectation value of $X_i X_j$, since they are independent samples we have a probability for each of the k values to be $1$ of  $M/N$. I was thinking about the sum of the binomial distribution, but I think I am not heading in the right direction there?
Comment: Since $X_i\neq X_j$, the probability is $M(M-1)/N(N-1)$
Comment: Hmm, okay, that makes sense of course if I draw those $X_i X_j$.
Sorry I was thinking that the $k$ matters as well. Hmm would it be different if the $k$ would be bigger than the $M$? (Just for me to comprehend it a bit better).
Do you have any hint how to proceed with the estimate of the guessing the right $M$ then?


c# Bluetooth LE - write configuration error - ValueChanged never called

Question: So I try to connect my c# WPF program to a BLE device and this is the code to connect to the device:
private async Task ConnectToWatcher(DeviceInformation deviceInfo) {
        try {
            // get the device
            BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);

            // get the GATT service
            Thread.Sleep(150);
            var gattServicesResult = await device.GetGattServicesForUuidAsync(new Guid(RX_SERVICE_UUID));
            service = gattServicesResult.Services[0];

            // get the GATT characteristic
            Thread.Sleep(150);
            var gattCharacteristicsResult = await service.GetCharacteristicsForUuidAsync(new Guid(RX_CHAR_UUID));
            characteristic = gattCharacteristicsResult.Characteristics[0];

            // register for notifications
            Thread.Sleep(150);

            characteristic.ValueChanged += (sender, args) => {
                Debug.WriteLine($"[{device.Name}] Received notification containing {args.CharacteristicValue.Length} bytes");
            };

            GattWriteResult result =
            await characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
            Debug.WriteLine($"Characteristics write result: status={result.Status}, protocolError={result.ProtocolError}");

        } catch (Exception ex) when ((uint)ex.HResult == 0x800710df) {
            Debug.WriteLine("bluetooth error 1");
            // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on.
        }
    }

The line
 Debug.WriteLine($"Characteristics write result: status={result.Status}, protocolError={result.ProtocolError}"

creates the output
Characteristics write result: status=protocolError, protocolError=3
I couldn't find anywhere whats that supposed to mean. The effect is the Method characteristic.ValueChanged never gets called.
Do I have to do more to have the characteristic configurated? And has anybody any idea why the method isn't called or what that error message means?
Thanks a bunch.
Answer: Apparently, some Windows 10 builds have a COM security bug.
Solution was to register for Windows-Insider-Program and update Windows.
Update:
There are two more solutions to this:
1) Calling CoInitializeSecurity from outside your c#-code (didn't bring it to work)
- or-
2) Writing two new keys into the windows registry. You cann create a file "Bluetooth.reg", which will add those two keys on a doubleklick. This answer from https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/bluetooth-bluetoothledevicefromidasync-does-not-complete-on-10015063?forum=wdk was my solution:

Hi Kamen, I have experienced exactly same issue. You can give a quick try of the following:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}]
  "AccessPermission"=hex:01,00,04,80,9c,00,00,00,ac,00,00,00,00,00,00,00,14,00,\
    00,00,02,00,88,00,06,00,00,00,00,00,14,00,07,00,00,00,01,01,00,00,00,00,00,\
    05,0a,00,00,00,00,00,14,00,03,00,00,00,01,01,00,00,00,00,00,05,12,00,00,00,\
    00,00,18,00,07,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00,00,\
    00,18,00,03,00,00,00,01,02,00,00,00,00,00,0f,02,00,00,00,01,00,00,00,00,00,\
    14,00,03,00,00,00,01,01,00,00,00,00,00,05,13,00,00,00,00,00,14,00,03,00,00,\
    00,01,01,00,00,00,00,00,05,14,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,\
    20,02,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\YOURAPP.exe]
  "AppID"="{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}"

Copy above content to a text file.
Replace 'YOURAPP.EXE' with your executable name
Optionally replace GUIDs (I have created a new one for you)
Save text file with an extension as .reg
Double click on the file.
You would see a message 'The Keys and values contained in ..... .reg have been successfully added to the registry.'

With this, I don't need to call CoInitializeSecurity from my app.
Answer: I was getting the Characteristics write result: status=protocolError, protocolError=3 error when calling the function below in C#.
await characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify)

The issue was the BLE Characteristic that I was trying to get Notify data from did not have a BLE Descriptor.
ESP32 C++ from the BLE Bluetooth server/device:
BLEService *service = pServer->createService(SERVICE_UUID);
BLECharacteristic* characteristic = service->createCharacteristic(
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_NOTIFY);

// This code was missing and causing the error
BLEDescriptor *descriptor = new BLEDescriptor((uint16_t)0x2902);
descriptor->setValue("The Descriptor Is No Longer Missing");
characteristic->addDescriptor(descriptor);

Answer: you need to call CoInitializeSecurity before
more info here. couple of weeks I spent looking for solution :)
https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/17707088)
Comment: Hello Eriawan, I think essential info is to **call CoInitializeSecurity**. that alone provide solution to the problem. By marking this answer negative you are might cause other people spend their time on wrong solutions.