Placing one image over another image in android

Question: I have a imageButton in android which user clicks. Then after his click I want t0 show a tick or a cross image on the toip of it.
How is it possible?
            <ImageButton android:layout_width="wrap_content"
            android:text="Button" android:id="@+id/button1"
            android:layout_height="wrap_content" android:layout_gravity="center_horizontal"
            android:background="@drawable/rhino" android:layout_marginRight="20dp"></ImageButton>

Comment: There is no way to set a transparent image on the top of it?
Comment: I think you have to make two images for that one with tick image and another one is without tick image . First you have to set the without tick image and after click on it you have to change image of ImageButton (Tick Image).
Answer: put your ImageButton and the tick image in a FrameLayout and make the visbility of the Tick image "Invisible" . So when you click on the ImageButton then change the state of Tick Image to Visible.
Answer: Get a reference to your ImageButton and then use one of its setImage methods, such as setImageResource.
Comment: but that will replace the image, isn'it? I want to put this tick image over it.
Comment: Sorry you are right, I missed the part about putting a tick or cross over it.
Answer: You can achieve the same using ImageView. Use ImageView
testimage = (ImageView) findViewById(R.id.imageview);

testimage.setOnClickListener(listener);

write the logic to set both type of image to imageview in onclick event
public OnClickListener listener=new OnClickListener(){
        @Override
        public void onClick(View arg0) {
            System.out.println("..set image button..");

            Drawable[] layers = new Drawable[2];
            layers[0] = getResources().getDrawable(R.drawable.btn_call);
            layers[1] = getResources().getDrawable(R.drawable.blue_unfocus);
            System.out.println(layers[1]+"...Drawable..."+layers[0]);
            LayerDrawable layerDrawable = new LayerDrawable(layers);
            testimage.setImageDrawable(layerDrawable);

        }
    };

Thanks
Deepak


NFSv4 through portforward

Question: I would like to reach my NFSv4 servers though port forward. The big plan will be a cluster of NFSv4 servers loadbalanced with HAProxy running on localhost. But this isn't really important now.
At the server the /etc/exports looks like this
/mnt/x  192.168.0.0/16(rw,sync,no_subtree_check,no_root_squash,fsid=1)

I can connect from my client to the server on TCP 2049 and mount the share like this
mount -t nfs4 -o proto=tcp,port=2049 192.168.2.25:/mnt/x /mnt

I tested that NFVs4 is happy with only this one TCP port open by filtering all other communication between the two machines.
So I think NFS works well.
But when I forward a port for example with redir on the client to the server like
redir --lport=3049 --cport=2049 --caddr=192.168.2.25

and want to mount it as follows
mount -t nfs4 -o proto=tcp,port=3049 127.0.0.1:/mnt/x /mnt

i get
mount.nfs4: Operation not permitted

What I miss? I can't see any relevant information in the server logs.
Update:
I captured both the good and the bad connection attempt, at the beginning they are the same then the client sends a
PUTROOTFH,GETFH,GETATTR

command. In the good case the servers responds
PUTROOTFH-NFS4_OK,GETFH-NFS4_OK,GETATTR-NFS4_OK

in the bad (forwarded) case it responds
PUTROOTFH-NFS4_OK,GETFH-NFS4_OK,GETATTR-NFS4ERR_PERM

This point I changed the export to
/mnt/x  0.0.0.0/0.0.0.0(rw,sync,no_subtree_check,no_root_squash,fsid=1)

but the error is the same.
In the good case the server logs are
rpc.mountd[1711]: nfsd_export: inbuf '0.0.0.0/0.0.0.0 /'
rpc.mountd[1711]: nfsd_export: found 0x12dfeb0 path /
rpc.mountd[1711]: nfsd_export: inbuf '0.0.0.0/0.0.0.0 /mnt'
rpc.mountd[1711]: nfsd_export: found 0x12e2810 path /mnt

in the bad case
rpc.mountd[1711]: nfsd_export: inbuf '0.0.0.0/0.0.0.0 /'
rpc.mountd[1711]: nfsd_export: found 0x12dfeb0 path /

Comment: There is no SELinux or any other MAC on the machines.
Comment: Forwarding `2049/tcp` is not enough, there are several ports involved in NFSv4 protocol operation. Check the `/etc/sysconfig/nfs` file (or equivalent if not in RHEL) for the default values.
Comment: That will almost certainly be an SELinux issue. But it's also not a good test, since in production you'll be forwarding port 2049 from one machine to port 2049 of another machine. Set up a test with exactly those parameters instead.
Comment: @dawud A pure NFSv4 environment only needs ports 2049 and maybe 111. Though I think maybe even that is unused as well; my firewall on my NFsv4 server records no traffic on that port.
Comment: In my tests I dropped everything between the two machines but 2049 and the mount was successful. See the top of my question.
Comment: @Stone does `redir` keep the source IP intact before redirecting? Or IOW, is the client using the 192.x.x.x IP address to contact the server? anything useful in the NFS server logs? Can you capture (`tcpdump`) a connection attempt?
Comment: @dawud `redir` terminates the TCP in it's one side and opens a new TCP to the other side. So in both cases the client address is the same.
Answer: My colleague spotted the solution in the tcpdump, that the only other difference between the good and bad connection attempts is the source port.
Then Google told me that I need the insecure option to the export, because after the forward the source port is above 1024 and in the normal case it is below 1024 and insecure tells to the server that it can accept clients with source port above 1024.
Comment: Huh, that did the trick. That's one hell of a braindead default option! I guess some guy really thought that clients that use a privileged port number are somehow more "secure"  ¯\\_(ツ)_/¯
Comment: Thanks for sharing. It solved this problem for me also.

NFSv4 through portforward


Injectivity of the exponential map of compact connected Lie groups

Question: I am trying to learn Lie Algebra with a little knowledge of Differential Geometry. I have read that the exponential map of compact connected Lie groups is always surjective. So I am wondering about the injectivity of the exponential map for compact connected Lie groups. I think it can not be injective and the multiplication of 1-torus with 1-sphere($T^1\times S^1$) is a counter example. Is this true? If so how can I prove it in a proper way?
Comment: As Tsemo Aristide's answer shows, the easiest (non-trivial) example is the easiest counterexample, $G= S^1$, where the exponential is basically the quotient map $\mathbb R \rightarrow \mathbb R/\mathbb Z$.
Answer: If $G$ is compact, then $G$ has a subgroup isomorphic to the circle, therefore the exponential is not injective.
Comment: Maybe exclude $\mathcal{G}=\{0\}, G=\{1\}$ for pedants like me.
Comment: The exponential map is *not*, in general, a local diffeomorphism.  For example, on $SU(2)$, the exponential map has conjugate locus consisting of a $2$-sphere of radius $\pi$ in $\mathfrak{su}(2)\cong \mathbb{R}^3$.  (I'm implicitly assuming $SU(2)$ is equipped with a bi-invariant metric scaled in such a way that the Riemanian exponential map coincides with the group exponential map, but this can always be done on a compact Lie group.)  It *is* diffeomophism onto its image when restricted to a small enough neighborhood of $0$.


Are the rules of voice leading and the rules of counterpoint ever at odds with one another?

Question: I was practicing composing in an SATB setting.  I had the chords voiced the way I wanted to, but there was not much rhythmic interest (everything in whole notes).  So, I began subdividing the notes here and there, using neighboring tones, passing tones, repeated triad tones etc.  I kept in mind some basic rules from counterpoint about the do's and donts of this practice.   Before I knew it, however, I realized that (for moments here and there) the voicing of the chords I diligently chose are disregarded.  "This triad doesn't have a root for half the measure!"  "This triad just lost it's third!"  "Oh no!  Did I just double the fifth?"  Things got out of hand very quickly.  What is the relationship between voice leading and counterpoint?  Are well-constructed (according to "the textbook") compositions expected to follow the rules of both frameworks simultaneously?
Thanks.
Comment: They aren't separate things. The rules of voice leading are designed to create effective counterpoint.
Answer: Voice leading and counterpoint are the same thing.
I think what you are trying to compare is harmonic structure and decorative movement. The structure is conceptual, a template, while the decorative movement is the concrete actual music.
Some basic things to manage when you fill out a harmonic structure are:

hit the important tones of the harmonic structure on the strong beats, the decorative tones are then smaller subdivisions of the beat, an older term for this is diminution, dividing a long note into shorter rhythmic values (that's the diminishing, the smaller durations)
mind the relative motion of the decorative lines, if you aren't careful you can introduce bad motion like parallel fifths.
don't overload the basic structure to too much decoration, with a basic harmonic rhythm of one chord per beat, and four part harmony, something like just one or two decorative voices is plenty. Using ratios for subdivisions of the beat, where 1:1:1:1 means all four voices moving in quarter notes, decorate at a levels like 1:1:1:2, 1:1:1:4, 1:1:2:2, 1:1:2:4, leave two voices undecorated.

Take a basic harmonic structure...

Decorate just one of the parts...

...I think this is your main concern, because it seems to throw off balanced voicing - all three triad tones present, tonal degrees doubled - but it should be OK if you make sure the initial harmony of the strong beats is balanced.
Avoid bad, unintended relative motion in the decorative movement...
Comment: Have to disagree that voice leading and counterpoint are "the same thing". Counterpoint is more general, you can write music that doesn't conform to standard voice leading at all and yet can be classified as species counterpoint.
Comment: @leftaroundabout, can you give an example of what you mean? The sameness, to me, could just be called _relative motion_, which will apply to _any_ group of voice when pitches change, regardless of stylistic things like "standard" voice leading or species counterpoint.
Comment: The most striking example I could think of would be Penderecki's _Threnody to the Victims of Hiroshima_.
Comment: Besides being completely inappropriate stylistically to the question, how is _Threnody_ , which of course is not standard voice leading, classified as species counterpoint?
Comment: Well, no, this one doesn't fit any of the species, but it still is counterpoint in concept and has even been described as _fugal_, which is pretty much the pinnacle of counterpoint techniques.
Comment: @leftaroundabout, then I think you should post an answer using that example to explain things to the OP.


How to match elements in a list with elements in a list of lists

Question: Suupose I have the following data structure
input = ["the","elephant","sneezed"]
g = {'S': [['VP', 'NP']], 'NP': [['N', 'DET']], 'N': [['elephant']], 'DET':[["the"]]}
stack = [['VP','N','the']]

How can I now compare the first element in input (the) with the last element in stack to see if there is a match? And if there is a match, remove both elements out of each list?
if input[0] == stack[-1]:
    i = input.pop()
    s = stack.pop()
    print(i)
    print(s)

Desired output:
input=["elephant","sneezed"]
stack=[["VP","N"]

Comment: do you mind providing your desired output?
Comment: What does `g` have to do with your question?
Comment: As far as I can tell, you essentially have the solution, except do del input[0] instead popping the element. And stack shouldn't be a list of list.
Answer: First of all, since stack is a list of lists, you have to use stack[0][-1] instead of stack[-1] while comparing (Basically, the last element of the first element of stack). By default pop() removes the last element of a list. Since we are removing the first element of input, we have to provide the index to remove which is 0 i.e., input.pop(0).
input = ["the","elephant","sneezed"]
g = {'S': [['VP', 'NP']], 'NP': [['N', 'DET']], 'N': [['elephant']], 'DET':[["the"]]}
stack = [['VP','N','the']]

if input[0] == stack[0][-1]:
    i = input.pop(0)
    s = stack[0].pop()
    print(i)
    print(s)


Por que meu while não funciona?

Question: Estou estudando estrutura de repetições e em um dos exercícios eu tinha que verificar o sexo digitado, então fiz o seguinte código:
sexo = input("digite m ou f: ")
while sexo != 'f' or sexo != 'm':
   sexo = input("digite m ou f: ")

No entanto, não funciona.
O que eu estou fazendo de errado?
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Neste caso deve usar um and e não um or. Na forma atual a condição sempre será verdadeira porque pelo menos uma das duas sub-expressões será verdadeira, é impossível algo ser igual a duas coisas diferentes, sempre uma será diferente. Se a letra for f ela será diferente de m e se for m, será diferente de f se for outra coisa, ambas serão verdadeiras, mas nem importa, basta uma ser que tudo fica verdadeiro.
O desejado é ser diferente das duas ao mesmo tempo, isto se dá com o and, assim ambas precisam ser verdadeiras para continuar no laço e é impossível ambas serem verdadeiras se digitar ou f ou m.
sexo = input("digite m ou f: ")
while sexo != 'f' and sexo != 'm':
     sexo = input("digite m ou f: ")
print(sexo)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para futura referência.
Veja a tabela verdade para entender a diferença entre os operadores. E os operadores lógicos em ação.
Eu entendo a confusão porque você quer aceitar que uma ou outra letra sejam aceitáveis. O que confunde é que o laço está pedindo o inverso, ele não está testando se aceita uma ou outra, ele está testando se não é uma ou outra, aí tem que inverter o operador. Se sentir mais confortável pode escrever de outra forma que usa o or, muitos vão considerar que exprime melhor a intenção:
sexo = ''
while not (sexo == 'f' or sexo == 'm'):
    sexo = input("digite m ou f: ")
print(sexo)

Note que eu fiz outra melhoria. O input estava repetido, assim não fica mais e o resultado é o mesmo.
Comment: kkkkkk é verdade. Mds como eu sou burro!!!
Comment: Não é essa a questão, é só entender o funcionamento dos operadores, como eles costumam ser novos para a maioria das pessoas, não se ensina na matemática, apesar de ser totalmente matemático as pessoas confundem. O `or` é como se fosse uma soma, o `and` é como se fosse uma multiplicação, sempre fazendo com 0 e 1.
Answer: Sua condição de parada é a seguinte: while sexo != 'f' or sexo != 'm':, ou seja, quando o usuário digitar algo diferente de 'f' ou de 'm', continua no laço, e ele nunca digitará uma letra igual as duas.
Para que ele saia com uma das opções aceitas, sua condição deve ser para continuar enquanto ele não digitar uma ou outra:
sexo = input("digite m ou f: ")
while sexo != 'f' and sexo != 'm':
     sexo = input("digite m ou f: ")
print(sexo)

Answer: Não funciona por causa da condicional do while que você colocou.
Não tem como sua string "sexo" ser igual a "f" e igual a "m" ao mesmo tempo, ou seja, ou é igual a um ou é igual ao outro; sendo assim, ela sempre será diferente de  pelo menos um dos dois, fazendo com que a condicional do while seja sempre verdadeira. A substituição do "or" por "and" resolve o problema.

Por que meu while não funciona?


Dynamic callback URL with mod_auth_mellon pingfederate

Question: We configured our SPA with mod_auth_mellon and the SP Initiated setup works well.
We now want to add the ability to dynamically route to SPA URL which initiated the SSO SAML call.
Below is the current flow

User opens the URL http://foo.com/user/1
Session is expired, so the SP initiates SSO handshake and redirects user to IDP (Ping Federate).
User logins on IDP and after successful authentication is redirect to http://foo.com/sso_callback

In Step(3) we now want to redirect back to http://foo.com/user/1.
What configuration changes should I make in SP / IDP configuration to enable dynamic routing?
Answer: If you are using SAML 2.0 then you want to use the RelayState. When creating your AuthN request in step 2, you will want to make sure that you as the Service Provider are including your desired RelayState. The value you provide to the IDP for RelayState will be carried through the transaction and given back to you as a URL parameter in Step 3 when the user POSTs to your ACS @ http://foo.com/user
Here is an example flow:

User opens the URL http://foo.com/user/1
Session is expired, so the SP redirects the user to the IDP with an AuthN token AND a RelayState value of http://foo.com/user/1
IDP Authenticates user
IDP directs the user to POST a SAMLResponse token to the SP ACS @ http://foo.com/sso_callback, and also includes an additional URL Parameter for RelayState
SP consumes and validates SAMLResponse at the ACS, and if successful then redirects the now active sessioned user to the value contained in the RelayState parameter

On the off chance you are not doing SP init SSO and are instead doing a generic redirect to an IDP initiated SSO Url from PingFederate, you can add the url parameter TargetResource to your IDP initiated SSO redirection to then receive it back with the SAMLResponse later.


Alexandroff compactification: continuous function extension

Question: Let $(X, \mathcal{T})$ be a non compact topological space, $\infty \notin X$ and $(X^* := X \cup \{\infty\}, \mathcal{T}^* := \{U \subseteq X^*\mid U \cap X \in \mathcal{T} \land (\infty \in U \implies X \setminus U \mathrm{\ compact)}\})$ the Alexandroff compactification of $X$.
Let $(Y, \mathcal{S})$ be a Hausdorff space, and let $f: X \to Y$ be a continuous function. Prove that the following statements are equivalent:
(1) $\operatorname{stack}\{f(X \setminus K) \mid K \subseteq X \mathrm{\ compact}\}$ converges
(2) There exists a unique continuous function $f^*: X^* \to Y$ with $f^*\vert_X = f$
My attempt:
$(1) \implies (2)$ Suppose $\operatorname{stack}\{f(X \setminus K) \mid K \subseteq X \mathrm{\ compact}\} \to y \in Y$
Define $f^*$ as the extention of $f$ such that $\infty \mapsto y$. This seems the only thing I can do now. I now have to show that this function is continuous, and I have no clue how I should do this. I also have to show this is unique, and I think I can use an argument that any image of $\infty$ other than $y$ will make the continuity of $f^*$ fail in that particular point.
$(2) \implies (1)$ Probably this follows from the fact that for any filter $\mathcal{F}$ on $X^*$, $\mathcal{F} \to x \implies \operatorname{stack}f({\mathcal{F}})\to f^*(x)$, by continuity of $f^*$, but I cannot see what filter to use. If I would make an educated guess, I would say that $\{f(X \setminus K) \mid K \subseteq X \mathrm{\ compact}\}$ is a filter that converges to $\infty$.
Can anyone fill in the gaps?
Comment: What do you mean by $stack(\mathcal{M})$ when $\mathcal{M}$ is a suitable family of subspaces of $Y$? Is it the filter generated by $\mathcal{M}$?
Comment: Usually a space $X$ is called compact if (1) it is Hausdorff and (2) every open cover has a finite subcover. If we only require (2), the space is called quasi-compact. This is what you mean in your question. But, admittedly, notation is not completely standardized in the literature. Anyway, we should be aware that the space $X$ in your question is not required to be Hausdorff.
Comment: With compactness, I mean what you call quasi compact. There are no restrictions on $X$, just that it is not "quasi-compact"
Comment: Exactly that yes.
Answer: By construction $X$ is a dense open subset of $X^\ast$.
$(1) \Rightarrow (2)$ $f^\ast$ is defined as in your attempt. Since $X$ is open in $X^\ast$, $f^\ast$ is continuous in all points of $X$. To show that it is also continuous in $\infty$, let $V$ be a neighborhood of $y$ in $X^\ast$. Since $\text{stack}\lbrace f(X \backslash K) \mid K \subset X \text{ compact} \rbrace \to y$, we know that $V \in \text{stack}\lbrace f(X \backslash K) \mid K \subset X \text{ compact} \rbrace$. Hence there exists a compact $K$ such that $f(X \backslash K) \subset V$. But $X^\ast \backslash K$ is an open neighborhood of $\infty$ since $X \backslash (X^\ast \backslash K) = K$ is compact, and clearly $f^\ast(X^\ast \backslash K) \subset V$. Uniqueness of $f^\ast$ is due to the well-known fact that the set of points where two continuous maps $u,v : Z \to Y$ agree is closed in $Z$ provided $Y$ is Hausdorff (recall that $X$ is dense in $X^\ast$).
$(2) \Rightarrow (1)$ $\mathcal{F} = \lbrace X^\ast \backslash K \mid K \subset X \text{ compact} \rbrace$ is a filter-base in $X^\ast$ which converges to $\infty$. By continuity of $f^\ast$, $f^\ast(\mathcal{F})$ converges to $y$. But $f^\ast(X^\ast \backslash K) = \lbrace y \rbrace \cup f(X \backslash K)$ so that $\text{stack}\lbrace f(X \backslash K) \mid K \subset X \text{ compact} \rbrace \to y$.
You see that you came very close to this.
Comment: I understand almost everything in your answer but why is $X^*\setminus K$ open? I.e., why is $X \cap (X^*\setminus K)$ open in $X$?
Comment: @Math_QED We have $\infty \in X^\ast \backslash K$ and $X \backslash (X^\ast \backslash K) = K$ which is compact.
Comment: Look at the topology. There are two conditions to be open.
Comment: @Math_QED Yes, my fault! This means that (1) has to be replaced by (1') $\text{stack}\lbrace f(X \backslash K) \mid K \subset X \text{ closed and compact} \rbrace$ converges. This tightened condition is automatically satisfied for Hausdorff $X$. With the original condition I don't see how to get a proof.
Comment: Many thanks! That's explains a bunch!


Tomcat ignoring post parameters request

Question: I have an Apache Tomcat server to read request from my webapp.
In my webapp I have a form that is submitted and posts a large number of POST parameters, around 8k~
However when I try to debug the entrypoint, where the HttpServletRequest, I always receive exactly 6841. The inputs from the form are created iterating over a number of elements, meaning that the last ones are exactly the same form as the other that are succeding
I can't show code for NDA reasons.
I discarded the frontend as an issue because with a sniffer I was able to see that the complete post param list is sent.
I believe I'm on the right track, I think Tomcat is dropping the other post params. the post size limit is well beyond the size of the request, and we don't have a post parameter count configured on server.xml (defaults to 10,000 and I don't hit that amount).
All answers I have found are about not sending parameters at all or errors being thrown, in this case they are simply ignored by Tomcat.
Comment: In this case, I suggest you debug tomcat code itself.
Comment: Is it working with less than 6841, let's say 5k POST parameters?
Comment: @AlexBaban yes, 2, 3, 4, 5k, 2k. but drops the others after that odd number of 6841
Comment: I understand. If possible, you could try to combine the data into JSON or even XML and pass it as payload in the body of the request.
Comment: Thanks @AlexBaban, i wasn't trying to be sarcastic, sorry about that. Uhm, maybe the solution is not to solve it but change it, i'll try converting that data into JSON and pass it in the body request. If i recall correctly the standards is to convert the post parameters from a form into a URL encoded separated with ampersands.
Answer: Increasing the number of POST parameters (not size of post) to 20,000 fixed the issue in my case. This was done in the tomcat server.xml configuration using maxParameterCount:

The maxParameterCount attribute controls the maximum number of
  parameter and value pairs (GET plus POST) that can be parsed and
  stored in the request. Excessive parameters are ignored. If you want
  to reject such requests, configure a FailedRequestFilter.
Comment: Might be helpful to include the new parameter/attribute value from server.xml.
Comment: Thanks. Better late than never :-)
Comment: I have a related error  in Tomcat 6: `Parameter count exceeded allowed maximum: 512` When adding  `maxParameterCount=10000` to server.xml it does nothing. Any ideas?
Comment: Your tomcat instance might be grabbing the default server.xml instead of yours? not sure tbh.

Tomcat ignoring post parameters request


Bayesian probability question and conditional probability based on falsehoods

Question:
I'm having trouble understanding how to compute (a), if it's not a Bayes theorem problem. Why bother telling me about $A$ and $A^C$ compliment in that case?
How does this help me compute parts (b) and (c)?
Thank you!
Answer: Part a) is just the law of total probability:
$P(\text{actually seen Nessie}) = P(\text{actually seen Nessie}|A).P(A) + P(\text{actually seen Nessie}|A^c).P(A^c)$
$P(\text{actually seen Nessie}|A) = 1 $       since they always tell the truth
$P(\text{actually seen Nessie}|A^c) = 1/1000 $ since they always say that they see it, so it is the probabiltiy that Nessie is seen in a given day
$P(\text{actually seen Nessie}) = 1. 0.99 + 0.01 . 1/1000$
and from now on you use this probability for part c for example


Index out of range SwiftUI

Question: I have declared a struct, which should have an id and a litereal
struct Lit: Identifiable, Codable {
    var id      : Int
    var literal : String
}

Here is my code where I decode a JSON file into a list:
The JSON file contains 3 items
[{"id":0,"literal":"arda"},{"id":0,"literal":"mecho"},{"id":0,"literal":"dossi"}]

class Literal: ObservableObject {

  @Published var lit = [Lit]()

  init() {
    loadLiteral()
  }
  func loadLiteral(){

    guard let url = URL(string: "http://biobeehive.com/Dossi.json") else {return}

    URLSession.shared.dataTask(with: url ) { (data,_,_) in
      guard let data = data else {return}

      let pokemon200 = try! JSONDecoder().decode([Lit].self, from: data)

      DispatchQueue.main.async  {
        self.lit  = pokemon200
        print("\(self.lit[0].literal)")
      }
    }.resume()

  }
}

Bellow, I want to print the literal at index 0, it should print "arda", but instead of that I get an error.( Fatal error: Index out of range: file ), even though I see that all the 3 items exist and have been passed.
struct ContentView: View {

  @ObservedObject var literal = Literal()

  var body: some View {

    VStack {

      Text("\(literal.lit.count)")   // Output is 3
      Text("\(literal.lit[0].literal)") //Crashing here

    }
}

Would you please tell me how to fix that?
Comment: The reason it crushes is because the `lit` array is empty before the network request with the JSON data completes. So, the first time the view renders, it attempts to access `[0]` of an empty array
Answer: try this:
reason: the async loading takes some time and the data is not loaded when view appears, so it crashes because there is no data at all.
struct ContentView: View {

    @ObservedObject var literal = Literal()

    var body: some View {

        VStack {
            if literal.lit.count > 0 {
                Text("\(literal.lit.count)")   // Output is 3
                Text("\(literal.lit[0].literal)") //Crashing here
            } else {
                Text("still loading...")
            }
        }
    }
}

Comment: Thank you very much for your answer. It helped me a lot. My confusion was because I was loading 3 and therefore I was thinking that it has been already loaded.

Index out of range SwiftUI


strucchange::breakpoints giving implausible results

Question: I'm trying to detect the breakpoints in Facebook's stock price with strucchange::breakpoints.
library(quantmod)
library(ggplot2)
library(strucchange)
FB <- getSymbols("FB", auto.assign = FALSE)
Y <- FB$FB.Adjusted
bp <- index(Y)[breakpoints(Y ~ 1)$breakpoints]
ggplot(data = Y, aes(x = index(Y), y = Y)) +
  geom_line(color="#3078EA") +
  stat_smooth(color = "#3F5A93", method = "loess") +
  ylab("Facebook's adjusted close price") + xlab("Time") +
  geom_vline(xintercept=bp, linetype=2)

The result is

Major breakpoints such as 2018-03-17 and 2018-07-25 are undetected. Instead, I got four seemingly insignificant breakpoints: 2013-08-22, 2014-09-15, 2015-10-22, and 2017-04-21.
How do I locate the shocks? As a side note, this is for my Bayesian final project, so if you have alternative Bayesian methods for detecting structural breaks in your mind, feel free to share them with me.
Answer: The first reason for this is due to the default parameter that gives the minimal segment size (a segment is the gap between two breakpoints)

h: minimal segment size either given as fraction relative to the sample size or as an integer giving the minimal number of observations in each segment.

By default h is set to be $0.15$. Since you have $1{,}784$ data points and $15\%$ of this is $267.6$, the breakpoints function will only detect a change if the effect of it is still noticeable $268$ days later. The two breakpoints you mentioned in your question don't satisfy this criterion so they will not be reported. The minimum h value that you can use is $2$ because there must be at least $2$ data points in a segment to fit the linear model.
If I run the following code: (this will take some time to run!)

bp <- index(Y)[breakpoints(Y ~ 1, h = 2, breaks = 35)$breakpoints]

[Here the breaks parameter gives the maximum number of breaks to look for - if you don't set a maximum it will set it to the maximum possible and the code will take an extremely long time to run. I've capped it at $35$ just because it was taking a long time but if you set it higher it will uncover more breakpoints]
I get the following output:

bp
[1] "2012-07-26" "2012-11-20" "2013-07-24" "2013-09-05" "2013-12-12"
[6] "2014-01-30" "2014-03-25" "2014-05-23" "2014-07-22" "2015-02-18"
[11] "2015-06-22" "2015-10-21" "2016-02-24" "2016-04-27" "2016-07-26"
[16] "2016-11-02" "2017-01-10" "2017-02-21" "2017-04-24" "2017-07-17"
[21] "2017-10-26" "2018-03-19" "2018-04-25" "2018-05-30" "2018-07-05"
[26] "2018-07-25" "2018-09-04" "2018-10-09" "2018-11-09" "2019-01-07"
[31] "2019-01-30" "2019-04-01" "2019-04-22" "2019-05-30" "2019-06-13"

So it can detect the changes that you mentioned as well as many others. The plot for these breakpoints is below.

The second reason is that the model you are using with

breakpoints(Y ~ 1)

chooses a set of breakpoints $(\tau_1, \tau_2, \dots, \tau_k)$ assuming that the data are generated according to the following model:
$$Y_t = \begin{cases}
      \mu_1 + \epsilon_t & \text{if } 0 < t \leq \tau_1,\\
      \mu_2 + \epsilon_t & \text{if } \tau_1 < t \leq \tau_2,\\
      \dots & \dots \\
      \mu_{k + 1} + \epsilon_t & \text{if } \tau_k < t \leq n.
    \end{cases}$$
So the underlying mean of the process should be a step function. Based on the curve that you can fit to the data I'm not sure this is a good model for all of your data - something like a linear model with auto-correlated errors may be a more appropriate model.
The breakpoints method chooses the number and positions of breakpoints that minimise the Bayesian Information Criterion (BIC). If you want a more Bayesian choice of both the number of breakpoints and their positions then you would need to specify a prior distribution on both of these. One way to do the sampling would be using reversible jump MCMC as pioneered in
Peter Green's 1995 paper, Reversible jump Markov chain Monte Carlo computation and Bayesian model determination , but this might be too much work for your project. If the number of breakpoints is known then Gibbs sampling can be used to estimate the distribution of the breakpoints, as in Carlin, B. P., A. E. Gelfand, and A. F. M. Smith (1992). Hierarchical Bayesian analysis of changepoint problems. Journal of the Royal Statistical Society, Series C (Applied Statistics) 41(2), 389–405.
Comment: It depends on what you want to detect - if you're just looking to detect shocks then you could work with log-returns, which is a common technique in finance. Apply $y_t \rightarrow \log(y_t)$ to each data point, and then look at $\Delta y_t = y_t - y_{t-1}$. In this case, the series $\Delta y_t$ will be roughly normally distributed with some notable outliers that correspond to shocks.
Comment: I agree that it doesn't make sense to have a universal rule that you must log-transform the data before you do anything else. In this data set there is a clear trend if you don't log-transform the data so feel free to leave it as it is.
Comment: Thanks for the detailed answer!  Do you think detrending the data first (with linear regression or differencing), and then applying `strucchange::breakpoints` would be a good idea? The Bayesian methods you mentioned are a little too complicated, since breakpoint detection is just the very first step of my project, but I'll take a closer look at them later.
Comment: One more question: do you think it's necessary to apply a log transformation to the data before doing any further analysis (like forecasting)? It seems that this is a convention when working with financial data, but Facebook's stock price looks really, really linear.
Answer: I don't think of breakpoints as being a natural way to analyze this, but rather would fit a flexible nonlinear function and get Bayesian credible interval bands to represent uncertainty in the function estimate.  For example, you could use a regression spline with lots of knots.  If you think of a structural change as a change in the first derivative of this function, you could easily differentiate the fit and show a credible interval for the first derivative.  Likewise for the second derivative (acceleration) and third derivative (jolt).


Continuous random variable transformations

Question: Let $Y$ be a continuous random variable with $f_Y(y)=\frac{1}{2}(1+y).$  Define $W_1=-4Y+7$.  Find $f_{W_i}.$
I'm just checking the following solution:
$F_{W_1}(w)=P(W\leq w)=P(-4Y+7\leq w)=P\left(\frac{7-w}{4}\leq Y\right)=F_Y\left(\frac{7-w}{4}\right)=\frac{-1}{4}f_Y\left(\frac{7-w}{4}\right)=\frac{-1}{4}[\frac{1}{2}(1+\frac{7-w}{4})]=\frac{-1}{32}(11-w).$
This is nonzero between $11\leq w \leq 3$
Comment: I don't understand the step $F_Y\left(\frac{7-w}{4}\right)=\frac{-1}{4}f_Y\left(\frac{7-w}{4}\right)$. You are supposed to compute $F_Y()$ instead and replace
Comment: abet means, $F_W(w) = \mathsf P(Y\geq \tfrac 1 4(7-w)) = 1- F_Y(\tfrac{1}{4}(7-w)) \\ \implies f_W(w) = -\frac{\mathrm d}{\mathrm d y}f_Y(\tfrac{1}{4}(7-w)) = \tfrac 1 4 f_Y(\tfrac{1}{4}(7-w))$
Answer: Assuming that the support for $f_y$ is $[-1,1]$, then you are nearly correct:
$$\begin{align}
F_W(w) & = \mathsf P(7-4Y\leq w)
\\[1ex] & = \mathsf P(Y\geq \tfrac 1 4(7-w))
\\[1ex] & = 1- F_Y(\tfrac{1}{4}(7-w))
\\[2ex] \implies f_W(w) & = -\frac{\mathrm d}{\mathrm d y}f_Y(\tfrac{1}{4}(7-w))
\end{align}$$
However, you don't need to involve the cumulative density function at all. Just transform the density function, via:
$$\begin{align}
f_Y(y) & = \tfrac 1 2(1+y)\quad\mathbf 1_{[-1,1]}(y)
\\[2ex]
 w & = 7-4y
\\[2ex]\therefore
f_W(w) & = f_Y(\tfrac 1 4(7-w))\cdot\left|\frac{\mathrm d \tfrac 1 4(7-w)}{\mathrm d w}\right|
\\[1ex] & = \tfrac 1 2(1+\tfrac 1 4(7-w))\cdot \tfrac{1}{4}\quad\mathbf 1_{[-1,1]}(\tfrac 1 4(7-w))
\\[1ex] & = \tfrac 1 {32}(11-w)\quad\mathbf 1_{[3,11]}(w)
\end{align}$$
Notice: The transformation multiplied by the absolute value of the derivative to ensure that the probability density is always positive over the support.


HP SmartArray E200i - convert one non-RAID disk to RAID-1

Question: Is it possible to convert one non-RAID disk to RAID-1 by adding a disk, without losing data or reinstalling Windows Server 2003? HP ACU cannot install, so I figured to do it from BIOS, but wanted to check with you guys. I am using HP ProLiant DL360 G5 with SmartArray E200i.
Cheers,
Dusan
Answer: There is no need to install ACU, you can start it from the bootable HP SmartStart CD (you should have received it with your server). If I remember correctly, you will find it under Maintenance section in SmartStart.
BIOS utility (ORCA) doesn't have all the features in ACU.
Comment: I'd forgotten you could do that Groo, that said I'm still worried why he can't install it properly, wonder if this means the whole PSP install failed????
Answer: Yep, you can do it but only via ACU sorry (it's just a straightforward raid migration), so the question is why can't you get ACU working...have you got the latest firmware pack and PSP?


Parameter upcasting in Drupal 8 with Form Controller

Question: I have created a custom module with mymodule.routing.yml in which I am using own parameter {my_menu}. I have created a mymodule.services.yml file too in which I have used class for param conversion. Parameter conversion class is calling properly but I am not able to get the parameter in Form Controller class.
Code that I have written :
mymoudle.routing.yml :
entity.my_menu.mymodule:
  path: '/node/{my_menu}/mytab'
  defaults:
    _title: 'My Title'
    _form: '\Drupal\mymodule\Form\MyModuleformControllerForm'
  requirements:
    _permission: 'edit my page'
    _entity_access: 'my_menu.update'
  options:
    _node_operation_route: TRUE
    parameters:
      my_menu:
        type: my_menu

mymoudle.services.yml :
services:
  my_menu:
    class: Drupal\mymodule\ParamConverter\MyModuleParamConverter
    tags:
      - { name: paramconverter }

src/ParamConverter/MyModuleParamConverter.php :
/**
 * {@inheritdoc}
 */
public function convert($value, $definition, $name, array $defaults) {
  dsm($value); // Node id that exists.
  return Node::load($value);
}

/**
 * {@inheritdoc}
 */
public function applies($definition, $name, Route $route) {
  return (!empty($definition['type']) && $definition['type'] == 'my_menu');
}

src/Controller/MyModuleformControllerForm :
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  dsm($node); // It is null here
}

Answer: Your variable needs to be called my_menu, check ControllerResolver


autocmd check filename in vim?

Question: I want to write some autocmd's that check if the filename is this or that..
I've been trying:
autocmd VimEnter * if % is "preamble" | Explore | endif
autocmd VimEnter * if %=="preamble" | Explore | endif
autocmd VimEnter * if &filename == "preamble" | Explore | endif

but none of this works?
WHat should I do?
(this example is over-simplified, note that I'd also like to have an else statement).
Comment: I doubt whether VimEnter is the best event to trigger this autocmd.  VimEnter happens once when you start a Vim instance and not after that.  BufRead happens each time a buffer is opened, regardless of whether Vim was open already or not (and likewise with BufNewFile).
Comment: This is what I'm using to change the color scheme except if the current buffer is a MiniBufExpl bufer and it seems to be working: `autocmd BufEnter * if bufname("%") !=? '-MiniBufExplorer-' | colorscheme default | endif`
Comment: Yeah I'm actually using `BufNew` to make it work
Comment: Thank you all for your swift responses!
Answer: You should get the current file name as @%. For e.g., echo @% will give you the filename, whereas echo % will not. However, for actions on the file, use %, e.g. source %.
This should probably work for what you want to do:
autocmd VimEnter * if @% == 'preamble' | echo 'hello' | else | echo 'world' | endif

Comment: Is it possible to do more than one thing in 'if' part or 'else' part? e.g. `autocmd VimEnter * if @% == 'preamble' | echo 'hello1'; echo 'hello2' | else | echo 'world1'; echo 'world2' | endif
`
Answer: autocmd BufRead,BufNewFile preamble Explore

Comment: Ok this works.. I would also like to have an `else` statement. Is this possible?
Comment: @romeoevs: For effect of an `else` one way is to just create another autocmd that matches everything except 'preamble'.  I think this would do it: `autocmd BufRead, BufNewFile [^\(preamble\)] function_here`  (See my separate Answer for info on what you were doing wrong and how the file-slot in autocmd works.)
Answer: There are two problems with the examples in the original post:

Neither the % nor &filename will return the filename as you've used them.
Look at the help for the expand() function to see how to get the filename: :h expand()

You're ignoring the slot in autocmd where a file-matching-pattern would ordinarily be specified. The third slot in the autocmd (* in your versions) is actually a pattern to match filenames. See :h autocmd-patterns. It should work okay if you want to ignore the pattern slot, but if so, you've got to fix the problem in paragraph 1 above.  E.g.,
autocmd BufRead,BufNewFile * if expand('%') =~ "preamble" | Explore | endif
Answer: Additional Info Using '@%' with autocmd
Some autocmd events do not support the @% named register to read the current file name. In these cases it is better to use <afile>:
expand('<afile>')

autocmd check filename in vim?


proof for series to the power of 5 is divisible by n+1 for even n and n congruent to 3 mod 4

Question: I really need help with this:
$$\sum_{x=1}^{n} x^5 $$ is divisible by $n+1$ when $n$ is even, and when $ n \equiv 3 \pmod{4} $.
What I first did was proving by induction that $$\sum_{x=1}^{n} x^5 = \frac{n^2 (1 + n)^2 (-1 + 2n + 2n^2)}{12}  $$ is right and then argued that because the term includes the factor $n+1$, it is divisible by $n+1$. However, this would imply divisibility for all n, which is not true, as it is not divisible, for example, when $n=5$. Can someone help me and tell how to proceed?
Comment: Don't forget the factor $12$ in the denominator.
Answer: Write
$$\sum_{x=1}^{n} x^5=\frac{n^2(n+1)^2\left[(2n+1)^2-3\right]}{24}$$
Then for all of the given cases
$$\frac{n^2(n+1)\left[(2n+1)^2-3\right]}{24}\in\mathbb{Z}$$
Comment: Can I ask why the term (n+1)^2 is allowed to become (n+1)?
Comment: We need to keep the other $n+1$ for the divisibility criteria, We are checking $0,2,3,4,6,7,8,10,11\pmod {12}$ and only one $n+1$ is needed.
Answer: Note that, given a positive integer $n$, your sum is equal to $\frac{n^2(n+1)^2 (2n^2 + 2n - 1)}{12}$. Proving this using induction should be straightforward.
If $n$ is even, then $4|n^2$, and if 3 does not divide $n$, then $3|(n+1)(2n^2+2n-1)$. That means $n+1$ is a factor of the sum. Similarly, one can analyze the other case.
Comment: I'm sorry I´m really stuck rn, can you clarify more? I just don´t really get how i prove my question with it.
Comment: If you don't mind dealing with cases, then try with the following: $n=6k,6k+2,6k+4$ and $n=4k+3$, $k\in\mathbb{N}$. For each of these cases, the numerator of the sum would be divisible by 12.
Answer: You want to show that $n+1$ divides $\sum\limits_{x=1}^{n} x^5 = \dfrac{n^2 (1 + n)^2 (-1 + 2n + 2n^2)}{12}  .$
Equivalently, $12(n+1)$ divides ${n^2 (1 + n)^2 (-1 + 2n + 2n^2)}$.
Equivalently, $12$ divides ${n^2 (1 + n) (-1 + 2n + 2n^2)}$.
Can you see that $3$ divides $n, 1 + n,$ or $-1 + 2n + 2n^2$, if $n\equiv0,2,$ or $1\pmod3$, respectively?
Can you see that $4$ divides $n^2 (1 + n)$ when $n$ is even or  $ n \equiv 3 \pmod{4} $?


Is there any scale that contains eight different notes?

Question: Today while praticing guitar I've played the following notes on the fretboard, one after another:
E F G G# A B C D# E
It didn't sound wrong, in fact, it sounded like Harmonic Minor with something else. Nevertheless I could not find anything about what this pattern could be.
Anyway, is there any kind of scale that contains eight different notes? If the answer is yes, what is the purpose of these "aditional" notes?
Comment: And let us not forget the 12-note chromatic scale. Used extensively in a functional way by 'modern classical' music, more as decoration in popular music.
Answer: The scale you mentioned appears to be a double harmonic with a flat 3rd added.  This flat 3rd, in combination with the flat 2nd of the double harmonic, can give it a kind of phrygian mode feel, but then there's the leading tone too, so it's not completely phrygian mode.
Ely was right in that octatonic scales contain 8 notes.  However, not all octatonic scales are structured the same way.  The specific one described in that answer can be called a diminished scale, since it includes the eight notes of two adjacent fully diminished seventh chords.  This scale is also neat in that it is a symmetric scale, which allows the "center" to be transposed, or shifted around, while still keeping the intervals in the same order.
Another example of an octatonic scale would be the bebop scale, which is basically the dominant scale (minor 7th) plus a major 7th.  This is interesting, since it has the capability to have a dominant feel as well as a leading tone.
Some wikipedia links if you want to read more about this stuff:

http://en.wikipedia.org/wiki/Octatonic_scale
http://en.wikipedia.org/wiki/Bebop_scale

(I can't post more than two links, but also check out the page titled "Modes of limited transposition" for some awesomeness about symmetric scales.)
Answer: The octatonic scale contains 8 different notes. It follows an alternating whole/half step pattern. So: C, Db, Eb, Fb, Gb, Abb, Bbb, Cbb C I think.
Comment: D# and Eb are the same.Did you mean C, D, Eb, F, Gb, Ab, A, B. With only 7 letter names, and 8 notes,2 will have to share the same letter. This is the whole/half diminished scale.With simplified note names !
Comment: There we go, sorry.
Answer: Typical 8 note scales are the bebop scale which has the #7, and the diminished scale.
Answer: Barry Harris (1929-2021) taught the following eight-note scales, which can be harmonised by two chords (and their inversions) only; the tonic chord and the second chord which is the leading-note diminished seventh chord.
C D Eb F G Ab A B, chords Cm6 and Bdim7 (minor sixth diminished scale, bebop melodic minor scale
C D E F G Ab A B, chords C6 and Bdim7 (major sixth diminished scale, bebop major scale)
C D E F Gb Ab Bb B, chords C7b5 and Bdim7 (seventh flat 5 diminished scale)
C D E F G Ab Bb B, chords C7 and Bdim7 (dominant seventh diminished scale)
C D Eb F Gb Ab A B, chords Cdim7 and Bdim7 (whole step/half-step diminished scale)
These scales have also another thing in common - they are made from whole tones and half tones only. In other words they do not contain augmented second, i.e. there is no "three-halfsteps-space" between the neighbour notes (as it is e.g. in the A harmonic minor seven-note scale between F and G#).
If we apply this "no augmented second" constraint to the selection process, there are five more eight-note scales made from whole tones and half tones only. They are again harmonised by two chords only, however the second one on the leading note is not the diminished seventh chord.
C D E F# G# A Bb B, chords C7#5 and Bm7
C D E F# G G# A B, chords C6 and Bm6
C D E F G A Bb B, chords C7 and Bm7b5 (bebop dominant scale)
C D E F# G A Bb B, chords C7 and Bm7
C D E F# G G# Bb B, chords C7 and Bm6


How do I programmatically place a block?

Question: From UI you can add a block in a region in that way:

Go to Admin -> Structure -> Block layout (/admin/structure/block).
Click on "Place block" button besides the region name.

I want to do the same thing but programmatically. How do I add an existing block to a region and save it? This block should then be displayed in that region and be  available in the Block layout page.
Comment: After creating the block you can rearrange position of the block from : https://site_name/admin/structure/block
Comment: I assume you mistyped "assign a block to a region".
Comment: @IcecreamJelly what I'm trying to do it's to do this programmatically. cilefen, yes that it's what I mean %-)
Comment: @ShawnConn thanks, that's similar, but not exactly the same. I've found the answer somewhere else.
Answer: To provide a plugin block you can build an array of settings and pass it off to \Drupal\block\Entity\Block::create() to create the Block object and save the instance.
For example if you wanted to add a Devel Execute PHP block to the Seven theme:
$values = array(
  // A unique ID for the block instance.
  'id' => 'devel_execute_php_1',
  // The plugin block id as defined in the class.
  'plugin' => 'devel_execute_php',
  // The machine name of the theme region.
  'region' => 'content',
  'settings' => array(
    'label' => 'Execute PHP',
  ),
  // The machine name of the theme.
  'theme' => 'seven',
  'visibility' => array(),
  'weight' => 100,
);
$block = \Drupal\block\Entity\Block::create($values);
$block->save();

Comment: Hi, I need help. I have created a custom block using UI and want to place in footer region programatically for testing purpose. I don't know how to get plugin from custom blocks created by UI.. thanks
Comment: Ask this as another question. Comments aren't for asking questions.
Comment: its already there. http://drupal.stackexchange.com/questions/207042/how-to-get-block-plugin-id-when-block-created-using-block-type-entity
Comment: Whats the **id** here ? is it same as the block name ?
Comment: @RubberDuckIsKing I believe you can name the `id` anything you want as long as it is unique. For example, you might want to start it with the name of the module its in.
Comment: @ParagMagunia so whats the `plugin` ?
Answer: You ca use Twig tweak module:

Twig Tweak module provides a Twig extension with some useful functions
  and filters that can improve developer experience.

And then on your twig template region:
{{ drupal_block('block_id') }}

Comment: The problem with this solution is that twig tweaks still requires you to place the block and then 'disable' it.
Answer: Each instance of a block (which "block type", configuration and the placement) is a config entity: \Drupal\block\Entity\Block. So all you have to do is to create a new instance of this entity with the correct details and you're done.
This can be done but is crazy complex, you would need to understand the plugin system, block plugin system and a lot more.
You can take a look at \Drupal\block\BlockForm::submitForm to get a feel for this or \Drupal\simpletest\BlockCreationTrait::placeBlock. You might want to think about if this is something you really need, the visibility of the block is pretty complex.
Comment: Apart maybe from visibility conditions, I don't think it's that complicated. \Drupal\simpletest\BlockCreationTrait::placeBlock() is probably a better example to look at, you can also just import some exported configuration files.
Comment: @Berdir Thanks for the link to the test trait, added it. Since Drupal 8 is still so young, a lot of people don't know a lot about the plugin system and the documentation could use more use cases etc, which can give a lot of devs a hard time working with it.
Comment: Felix Eve has the best answer. It is not crazy complex.
Comment: @kratos The answer Felix has provided isn't actually solving the question of how to place a block "programmatically", but instead uses config files. Config can only be imported via through drush, config synchronization interface or module installation. If it needs to happen, during runtime, fx post save of a section frontpage node type etc, it would be useless to use this strategy :)
Answer: I found the answer thanks to How to manipulate an Entity:Block programmatically in Drupal 8.
use Drupal\block\Entity\Block;

$block = Block::load('sitebranding');
$block->setRegion('content');
$block->save();

Comment: This was precisely what I was looking for Thanks, @jmzea!
Answer: I'm just learning D8 but I seem to have found a much easier way to place a block programmatically (It seemed pretty intimidating after reading googletorp's answer!)
When I enabled my custom module that defined the block I wanted the block to automatically be placed in the correct region. Steps I used to achieve this are:

Enable the module and place the block using the UI at /admin/structure/block
Go to the Single Item config export page at admin/config/development/configuration/single/export
Select Configuration type block and for the Configuration name select the block that you just placed using the UI and then copy the generated code.
In your module create the folder /config/install/
Under the generated code textarea it tells you the filename you need to use. Create this file in the /config/install directory and copy the code in there.
Now when you uninstall your module and then re-enable it the block will automatically be placed.
Comment: wouldn't you have to remove UUID for this to work for other developers or environments?
Comment: Yep - removing the UUID would be a good idea.
Comment: You could also use Drupal console, which takes care of automating some of these tasks: https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/config-export-single.html
Answer: The example above is close enough but still not correct. The idea is that you have to come up with your own id of the block instance (in my case devel_execute_php_1112 (maybe because I tried to make it work 1112 times, it will remain mystery)) and then the actual block id (the one that is declared for the custom blocks in the annotation) and the theme. Then just set the region and you are good to go. Created an instance of a block under the desired region.
$blockEntityManager = \Drupal::service('entity.manager')->getStorage('block');
$block = $blockEntityManager->create(
  array(
      'id'=> 'devel_execute_php_1112',
      'plugin' => 'devel_execute_php',
      'theme' => 'seven'
  )
);
$block->setRegion('content');
$block->save();

edit1:
I actually checked later the comment above - and it is right. It is just not clear that the id is something that you have to come up with.
As a redemption for my lame comment I will post a solution on how to create a block instance of a custom block entity:
$blockEntityManager = \Drupal::service('entity.manager')->getStorage('block');
$block = $blockEntityManager->create(
  array(
      'id'=> 'ggggggggsssssss',
      'plugin' => 'block_content:79d53b4e-9e60-4f97-befc-101da919bb7a',
      'theme' => 'visitb_he_theme'
  )
);
$block->setRegion('content');

basically the same but for a plugin you write block_content:uuid_of_custom_block_entity_instance


Move only the first .txt file from a folder using c#

Question: Simple question,I know you can use FileMove to move a file from one path to another.My question is,how can you move from a folder full of any sort of files ( .mp3 , .txt , .avi) only the first .txt file from folder 1 to folder 2?
Comment: What is your definition of "first"? Alphabetically?
Comment: What do you mean with "the first file"? Do you want to move the alphabetically first .txt file of a directory or do you want to move all .txt files of the directory? I do not fully understand the question, I'm sorry.
Comment: first alphabetically,sorry ,forgot to specify that.
Answer: You can pass a wildcard to Directory.EnumerateFiles():
string filename = Directory.EnumerateFiles("Your search folder here", "*.txt").Min();

if (filename != null)
{
    // ... Do something with filename
}

Enumerable.Min() will return the 'minimum' string in the sequence (i.e. the first in alphabetical order), or null if the sequence is empty.
This is efficient because when you pass a wildcard such as *.txt to Directory.EnumerateFiles() it calls a Windows API method that only returns '.txt' files.
Comment: Does `EnumerateFiles` return the files sorted in an alphabetical order?
Comment: @mxscho Nope. I just noticed that the OP has changed his specification... Sigh.
Comment: You can just add a sorting step after `EnumerateFiles` and still have the best solution I guess.
Comment: Sure, makes sense.
Answer: Directory.GetAllFiles(@"path/to/files")
         .Select(f => new FileInfo(f))
         .First(f => f.Extension == "txt");

This will explode if there are no files in the directory. It will also explode if there are no text files in the directory. This also depends on your definition of "First"
Answer: You can use GetFiles
string[] files = System.IO.GetFiles(@"C:\users\youruser\documents\", *.txt);
if(files.GetLength(0) != 0)
{
    System.IO.File.Move(files[0],pathyouwanttomoveitto);
}


How to upload image from gallery to android?

Question: I am working on an app which include uploading pictures, I am able to select pictures using following. By this it is directly taking me to gallery, how can I display an alert(like whatsapp profile pic change) before it taking me to gallery.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, PICK_IMAGE_R);

Answer: You could pop up a dialog fragment when a user clicks your button or whatever to select a photo:
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Set a Profile Photo");

        final String[] Items={"Select a Profile Photo"}; // You can add more choices here
        builder.setItems(Items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i == 0){
                    // Your code to launch gallery here

                }
            }
        });
        builder.setCancelable(true);
        AlertDialog dialog=builder.create();
        dialog.show();

Check out more examples here: https://github.com/msandroid/AndroidUsefulExample_AlertDialog
Comment: When I've implemented that code it is taking me to gallery, but when I press on Back button while it is in the gallery window it is taking me to starting activity of the page instead of the activity where we clicked to upload an image


About $\sum_{n=1}^{\infty}\frac{(-1)^n}{n+(-1)^{n+1}}$

Question: Determine if the following series is converges or diverges
$$\sum_{n=1}^{\infty}\frac{(-1)^n}{n+(-1)^{n+1}}$$
I suspecting that we need rewrite $ \frac{(-1)^n}{n+(-1)^{n+1}} $ somehow, but how?
Thanks!
Answer: It often helps to write out a few terms to try to see what's going on:
$$-\frac12+\frac11-\frac14+\frac13-\frac16+\frac15-\frac18+\frac17-+\ldots$$
If you calculate even-numbered partial sums, you're going to get sums like
$$s_8=\left(-\frac12+\frac11\right)+\left(-\frac14+\frac13\right)+\left(-\frac16+\frac15\right)+\left(-\frac18+\frac17\right)\;,$$
for instance. With a bit of thought you can work out that
$$\begin{align*}
s_{2n}&=\left(-\frac12+\frac11\right)+\left(-\frac14+\frac13\right)+\ldots+\left(-\frac1{2n}+\frac1{2n-1}\right)\\\\
&=\sum_{k=1}^n\left(-\frac1{2k}+\frac1{2k-1}\right)\\\\
&=\sum_{k=1}^n\frac1{2k(2k-1)}\;,
\end{align*}$$
and
$$s_{2n+1}=s_{2n}-\frac1{2(n+1)}=\sum_{k=1}^n\frac1{2k(2k-1)}-\frac1{2(n+1)}\;.$$
The original series converges if the sequence of these partial sums converges. Concentrate on the even-numbered ones, and worry about the odd-numbered ones afterwards. Does
$$\sum_{k=1}^\infty\frac1{2k(2k-1)}$$
converge? If it doesn't, the sequence of even-numbered partial sums of your original series doesn't converge, so the series cannot converge. If it does, the sequence of even-numbered partial sums of your original series does converge, and you have only to check that the odd-numbered partial sums don't misbehave.
Comment: Brian! I appreciate this! Thank you!
Comment: @17SI.34SA: You're very welcome.
Answer: This is a rearrangement of   the Alternating series, but a rather simple one. What it amounts to is grouping terms of the Alternating series and rearranging the terms within each group.
Naively:
$$\eqalign{
1-{1\over 2}+ {1\over 3}-{1\over4}+\cdots
&=
1-{1\over 2}+ {1\over 3}-{1\over4} +\cdots\cr
&=\Bigl( 1-{1\over 2}  \Bigr) +\Bigl( {1\over 3}-{1\over4}\Bigr) +\cdots\cr
&=\Bigl(  -{1\over 2} +1 \Bigr) +\Bigl( -{1\over 4}+{1\over3}\Bigr) +\cdots\cr
}
$$
Is this justified? Yes it is:
Let $S_n$ denote the $n$'th Partial sum of the Alternating series and $T_n$ denote the $n$'th partial sum of the OP's rearranged series. Then for $n>1$, we have $|S_n-T_n| \le{1\over n }-{1\over n+1}={1\over n(n+1)}$. Thus for any $n$
$$
S_n-{1\over n( n+1)}\le T_n \le S_n+{1\over n(n+1)}.
$$
From this and the fact that $S_n$ converges, it follows that $T_n$ converges (and to the same limit as $S_n$).
Comment: Ausgezeichnet! Very nice, indeed. +1
Answer: Hint: let $a_n=\frac{(-1)^n}{n+(-1)^{n+1}}$ and let $(b_1,b_2,b_3,b_4,b_5,b_6,\ldots)=(a_2,a_1,a_4,a_3,a_6,a_5,\ldots)$, then $\sum_{n=1}^\infty b_n=\sum_{n=1}^\infty \frac{(-1)^{n-1}}{n}$, which is convergent by the alternating series test. So, ...
Comment: You can't reorder a conditionally convergent series as you like.
Comment: @mrf But   for this particular reordering, you can.
Comment: @mrf There is no need to reorder the series at all. The point is to show that the partial sum $\sum_{n=1}^k a_n$ converges. When $k$ is even, it is equal to the partial sum $\sum_{n=1}^k b_n$; when $k$ is odd, it is equal to $(\sum_{n=1}^{k-1} b_n)+a_n$.


How to deal with identical p-values with the Benjamini-Hochberg method for correcting for multiple testing

Question: I'm testing for mutations in DNA and I'm using the Benjamini-Hochberg method to modify the threshold I'm testing my p-values against. The method is basically to rank the p-values and compare them to a new threshold defined by
$q(k) = k/n*\alpha$,
where $\alpha$ is your original threshold, commonly 0.05, $k$ is the rank of the p-value you compare with, and $n$ is the total amount of p-values (== total amount of tests).
Due to the nature of my data, many p-values are identical. The following ordered set of p-values could be an example:
$p_1$ = 0.01
$p_2$ = 0.03
$p_3$ = 0.03
$p_4$ = 0.03
$p_5$ = 0.09
Assuming a threshold of $\alpha$ = 0.05, what I have to compare my values to are:
$q_1$ = 0.01
$q_2$ = 0.02
$q_3$ = 0.03
$q_4$ = 0.04
$q_5$ = 0.05
And thus I accept the second test and reject the third and fourth even if they have the same original p-value. I tried to search the literature for a solution to this, but nothing came up. Is there an established method for this? And, if not, what is your preferred ad hoc solution?
Answer: Verifying also in the multtest package from Bioconductor, I would suggest to give them the same rank - and very importantly - increment the rank by one for the following p-value(s) rather than using their index+1 in an array! This would have the following result:
considering your examplemulttest's BH would rank $r_1$: 1,
$r_2$: 2,
$r_3$: 2,
$r_4$: 2,
$r_5$: 3
rather than  of
$r_2$: 2,
$r_3$: 2,
$r_4$: 2,
$r_5$: 5
Comment: Thank you. I accept this answer although it is essentially the same as the one by Maciej because of the extra detail.
Comment: Thank you - I effectively picked up on the comment of Maciej. I often miss the possibility to accept more than one answer!
Comment: I doubt that it is correct. In practice very rarely one can get two equal p-values.
Comment: @dmeu this answer is incomplete and unclear (and incorrect). How did you use `multtest` to find out these ranks?
Comment: @SextusEmpiricus I wish I'd remember, This was ten years ago! If the answer is objectively wrong, could you provide a correction? Do I need to unlock community wiki or similar or can you edit the answer?
Comment: @dmeu I wouldn't able to correct the answer as I don't know how the `multtest` provides the ranks and what it means by it. However for the computation of p-values it should be the higher rank values that need to be used. $r_1$: 1,
$r_2$: 4,
$r_3$: 4,
$r_4$: 4,
$r_5$: 5
Answer: Possible ad hoc solution is to give repeated p-values the same rank.
Comment: I've just exploring my `multtest` package results and I see that I have a subset of the same FDR corrected values `[1] 0.08199 0.08199 0.08199 0.08199 0.08199 0.08199 0.08199 0.08199 0.08199 [10] 0.08199
` So maybe it is as I wrote.
Answer: All answers here are misleading:
considering your p-values are:
p1 = 0.001 p2 = 0.03 p3 = 0.03 p4 = 0.03 p5 = 0.09
Then, BH would rank them: r1 = 1, r2 = 4, r3 = 4, r4 = 4, r5 = 5
Means the ranks for identical p-values will be the max index of them in the sorted list of p-values.
Verified with R using the p.adjust function:
p.adjust(c(0.001, 0.03, 0.03, 0.03, 0.09), method = 'BH')
Yielding the next adjusted p-values:
0.0050 0.0375 0.0375 0.0375 0.0900
Note that for the identical p-values, we got an adjusted p-value of:
0.03 * n / k where n = 5 (as the number of p-values) and k = 4 which is the max index of the identical p-values in the sorted list of p-values...
Accordingly, the adjusted values of alpha are:
alpha * k / n yielding:
q1 = 0.001 q2 = 0.04 q3 = 0.04 q4 = 0.04 q5 = 0.05
Added this part after I was asked:
multtest does the same thing using the same ranks as I mentioned:
using mt.rawp2adjp(c(0.001, 0.03, 0.03, 0.03, 0.09), 'BH') yields the same p-values as the p.adjust function, therefore it ranks identical p-values by the max index of them in the sorted list of p-values. The output of the relevant function from multtest is:
      rawp     BH
[1,] 0.001 0.0050
[2,] 0.030 0.0375
[3,] 0.030 0.0375
[4,] 0.030 0.0375
[5,] 0.090 0.0900

Where the rawp column stands for the original p-values and BH stands for the adjusted p-values. From the adjusted p-values you can calculate the respective alphas as I did above.
Comment: Hi, I added an additional part to my answer related to ```multtest```. I hope I managed to understand your question properly.
Comment: I believe your criticism is right. I looked it up as well and it seems indeed that the highest rank counts.  I wonder what went different in the other answers.
Answer: These procedures can be confusing. This nice post by spätzle explains the Benjamin Hochberg procedure very well

The Benjamini-Hochberg method is as follows:

Order the p-values $p_{(1)},...,p_{(m)}$ and then respectively the hypotheses $H_{0,(1)},...,H_{0,(m)}$
Mark as $i_0$ the largest $i$ for which $p_{(i)}\le \frac{i}{m}\alpha$
Reject $H_{0,(1)},...,H_{0,(i_0)}$

So if you have several $p_{(i)}$ with the same value, then all that counts is the largest rank. If $p_{(i)}\le \frac{i}{m}\alpha$ for some rank $i$ then also $p_{(j)}\le \frac{j}{m}\alpha$ for some rank $j>i$.
See in the image below for a visual explanation of the method. What counts is the highest ranked p-value that is still below the line. In this case it is the 10-th p-value. All the previous hypothesis tests will be rejected (even if they are above the line). So when you have identical p-values, then what counts is the highest rank.

The following ordered set of p-values could be an example:
$p_1$ = 0.01
$p_2$ = 0.03
$p_3$ = 0.03
$p_4$ = 0.03
$p_5$ = 0.09
Assuming a threshold of $\alpha$ = 0.05, what I have to compare my values to are:
$q_1$ = 0.01
$q_2$ = 0.02
$q_3$ = 0.03
$q_4$ = 0.04
$q_5$ = 0.05
And thus I accept the second test and reject the third and fourth even if they have the same original p-value.

You can not have the situation where you accept the second ranked hypothesis while rejecting the third and fourth. You decide on some boundary and all the tests below it are rejected and all the test above it are accepted.
In the BH procedure the second test for which you got $p_2 > q_2$ will be rejected as well.


How to implement interactive rotation operations in a decent way

Question: Recently, I want to achieve interactive rotation operations as can be done in meshlab:

Basically, it achieves rotation of three degrees of freedom. I visualize these operations as following codes with the help of GLFW:
static void mouse_move_callback(GLFWwindow* window, double xpos, double ypos){
...
do{
        //perform rotation operations only if keeping the right mouse key pressed
        if(glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_RELEASE) {
            g_clr_right_mouse = true;
            break;
        }
        /*clear mouse state once transferred from release state
          to pressed state to prevent from a instant flicker*/
        if(g_clr_right_mouse){
            g_lastX = xpos;
            g_lastY = ypos;
            g_clr_right_mouse = false;
        }

        float xoffset = xpos - g_lastX; //let movement from down to top positive
        float yoffset = g_lastY - ypos;
        g_lastX = xpos;
        g_lastY = ypos;

        //do counterclockwise rotation around x-asis with movement in y direction
        glm::mat4 r1 = glm::rotate(glm::mat4(), glm::radians(-yoffset * 0.5f), glm::vec3(1.0f,0.0f,0.0f));
        //do counterclockwise rotation around y-asis with movement in x direction
        glm::mat4 r2 = glm::rotate(glm::mat4(), glm::radians( xoffset * 0.5f), glm::vec3(0.0f,1.0f,0.0f));
        glm::mat4 tmp = r2 * r1 * g_model;
        for(int i=0; i<3; i++)
            g_model[i] = tmp[i];
        return ;
    }while(false);
}

These codes are located here, and the whole project can be found here which can be downloaded and built. Finally, it performs as follows:

However, my implementation can only achieve rotation operations of 2 DOF, I add a keyboard callback to achieve rotation around the z axis:
void keyboard_callback(GLFWwindow* window, int key, int scancode, int action, int mod){
    if(glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS){
        glm::mat4 r3 = glm::rotate(glm::mat4(), glm::radians(3.0f), glm::vec3(0,0,1.0f));
        glm::mat4 tmp = r3 * g_model;
        for(int i=0; i<3; i++)
            g_model[i] = tmp[i];
    }else if(glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS){
        glm::mat4 r3 = glm::rotate(glm::mat4(), glm::radians(-3.0f), glm::vec3(0,0,1.0f));
        glm::mat4 tmp = r3 * g_model;
        for(int i=0; i<3; i++)
            g_model[i] = tmp[i];
    }
}

So my question is how to decently achieve interactive rotation operations of 3 DOF only with mouse movement?
Comment: how about these [OpenGL ray OBB intersection](https://stackoverflow.com/a/52905600/2521214) and [Compute objects moving with arrows and mouse](https://stackoverflow.com/a/50908533/2521214)
Answer: You kinda need to draw the ball to make it intuitive.
On mouse down, you put an anchor on the ball directly under the mouse pointer.  If the click is outside the ball, then you use the closest point on the ball.
As the mouse moves, you rotate the ball so that the anchor point follows the shortest path so that it remains directly under the mouse pointer.  If the mouse pointer is off the ball, then the closest point on the ball is used.
Maybe this will help.
Answer: When dragging the mouse, the object must be rotated around an axis that is perpendicular to the direction of movement of the mouse. The pivot is the origin of the model.

Rotate the mouse movement vector by 90 ° in the XY plane of the view. Since this is a vector in view space, the vector must be transformed from view space into world space. The matrix that transforms a vector from view space to world space is the inverse matrix of the upper left 3x3 of the view matrix:
vec2 drag_start;
vec2 drag_end;

glm::mat3 to_world = glm::inverse(glm::mat3(view_matrix));
glm::vec2 drag_vec = glm::vec2(drag_end.x - drag_start.x, drag_start.y - drag_end.y);
glm::vec3 axis_vec = glm::normalize(to_world * glm::vec3(-drag_vec.y, drag_vec.x, 0));

Create a rotation matrix around the axis. The angle depends on the length of the vector (height is the height of the viewport in pixels):
GLfloat angle = glm::length(drag_vec) / height / 2 * M_PI;
drag_rotation = glm::rotate(glm::mat4(1.0f), angle, axis_vec);

Compute a rotation matrix while dragging the mouse. Concatenate the rotation matrix and the model matrix after the drag ends:
glm::mat4 view_matrix(1.0f);
glm::mat4 model_rotation(1.0f);
glm::mat4 drag_rotation(1.0f);
glm::vec2 drag_start(0.0f);
bool drag = false;

void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
    if (button != GLFW_MOUSE_BUTTON_LEFT)
        return;

    if (action == GLFW_PRESS)
    {
        drag = true;
        double xpos, ypos;
        glfwGetCursorPos(window, &xpos, &ypos);
        drag_start = glm::vec2(xpos, ypos);
    }
    else if (action == GLFW_RELEASE)
    {
        drag = false;
        model_rotation = drag_rotation * model_rotation;
        drag_rotation = glm::mat4(1.0f);
    }
}

void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
    if (!drag)
        return;

    glm::mat3 to_world = glm::inverse(glm::mat3(view_matrix));
    glm::vec2 drag_vec = glm::vec2(xpos - drag_start.x, drag_start.y - ypos);

    glm::vec3 axis_vec = glm::normalize(to_world * glm::vec3(-drag_vec.y, drag_vec.x, 0));
    GLfloat angle = glm::length(drag_vec) / height / 2 * M_PI;

    drag_rotation = glm::rotate(glm::mat4(1.0f), angle, axis_vec);
}

The model matrix is the concatenation of drag_rotation and model_rotation:
glm::mat4 model = drag_rotation * model_rotation;

See also Orbit

Complete example:

#include <GL/glew.h>
#include <GL/gl.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GLFW/glfw3.h>
#include <vector>
#include <string>
#include <stdexcept>
#include <iostream>
#define _USE_MATH_DEFINES
#include <cmath>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

std::string sh_vert = R"(
#version 460 core

layout (location = 0) in vec4 a_position;
layout (location = 1) in vec3 a_uvw;

out vec3 v_uvw;

layout (location = 0) uniform mat4 u_projection;
layout (location = 1) uniform mat4 u_view;
layout (location = 2) uniform mat4 u_model;

void main()
{
    v_uvw = a_uvw;
    gl_Position = u_projection * u_view * u_model * a_position;
}
)";

std::string sh_frag = R"(
#version 460 core

out vec4 frag_color;
in vec3 v_uvw;

vec3 HUEtoRGB(in float H)
{
    float R = abs(H * 6.0 - 3.0) - 1.0;
    float G = 2.0 - abs(H * 6.0 - 2.0);
    float B = 2.0 - abs(H * 6.0 - 4.0);
    return clamp(vec3(R, G, B), 0.0, 1.0);
}

void main()
{
    frag_color = vec4(HUEtoRGB(v_uvw.z), 1.0);
}
)";

class ShaderProgram
{
public:
    GLuint programObject;
    static ShaderProgram newProgram(const std::string& vsh, const std::string& fsh);
private:
    GLuint compileShader(const std::string& sourceCode, GLenum shaderType);
    void linkProgram(std::vector<GLuint> shObjs);
    void compileStatus(GLuint shader);
    void linkStatus();
};

class VertexArrayObject
{
public:
    GLuint vaoObject = 0;
    GLsizei noOfVertices = 0;
    GLsizei noOfIndices = 0;
    static VertexArrayObject newCube();
    static VertexArrayObject newCircles();
    static VertexArrayObject newVAO(const std::vector<GLfloat>& varray, const std::vector<GLuint>& iarray);
};

int width = 800, height = 600;
glm::mat4 view_matrix(1.0f);
glm::mat4 model_rotation(1.0f);
glm::mat4 drag_rotation(1.0f);
glm::vec2 drag_start(0.0f);
bool drag = false;

void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
    if (button != GLFW_MOUSE_BUTTON_LEFT)
        return;

    if (action == GLFW_PRESS)
    {
        drag = true;
        double xpos, ypos;
        glfwGetCursorPos(window, &xpos, &ypos);
        drag_start = glm::vec2(xpos, ypos);
    }
    else if (action == GLFW_RELEASE)
    {
        drag = false;
        model_rotation = drag_rotation * model_rotation;
        drag_rotation = glm::mat4(1.0f);
    }
}

void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
    if (!drag)
        return;

    glm::mat3 to_world = glm::inverse(glm::mat3(view_matrix));
    glm::vec2 drag_vec = glm::vec2(xpos - drag_start.x, drag_start.y - ypos);

    glm::vec3 axis_vec = glm::normalize(to_world * glm::vec3(-drag_vec.y, drag_vec.x, 0));
    GLfloat angle = glm::length(drag_vec) / height / 2 * M_PI;

    drag_rotation = glm::rotate(glm::mat4(1.0f), angle, axis_vec);
}

int main(void)
{
    if (glfwInit() == GLFW_FALSE)
        throw std::runtime_error( "error initializing glfw" );

    glfwWindowHint(GLFW_SAMPLES, 8);
    GLFWwindow * window = glfwCreateWindow(width, height, "OGL window", nullptr, nullptr);
    if (window == nullptr)
    {
        glfwTerminate();
        throw std::runtime_error( "error initializing window" );
    }
    glfwSetMouseButtonCallback(window, mouse_button_callback);
    glfwSetCursorPosCallback(window, cursor_position_callback);
    glfwMakeContextCurrent(window);

    if ( glewInit() != GLEW_OK )
        throw std::runtime_error( "error initializing glew" );

    auto progam = ShaderProgram::newProgram(sh_vert, sh_frag);
    auto cube = VertexArrayObject::newCube();
    auto circles = VertexArrayObject::newCircles();
    glUseProgram(progam.programObject);
    glEnable( GL_DEPTH_TEST );
    glClearColor(0.1f, 0.3f, 0.2f, 0.0f);

    view_matrix = glm::lookAt(glm::vec3(0.0f, 0.0f, 7.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
    glUniformMatrix4fv(1, 1, GL_FALSE, glm::value_ptr(view_matrix));

    while (!glfwWindowShouldClose(window))
    {
        glfwGetFramebufferSize(window, &width, &height);

        float ascpect = (float)width / (float)height;
        glm::mat4 project = glm::perspective(glm::radians(60.0f), ascpect, 0.1f, 20.0f);
        glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(project));
        glm::mat4 model = drag_rotation * model_rotation;

        glViewport(0, 0, width, height);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

        glUniformMatrix4fv(2, 1, GL_FALSE, glm::value_ptr(model));
        glBindVertexArray(cube.vaoObject);
        glDrawElements(GL_TRIANGLES, cube.noOfIndices, GL_UNSIGNED_INT, nullptr);

        glUniformMatrix4fv(2, 1, GL_FALSE, glm::value_ptr(glm::scale(model, glm::vec3(2.5f))));
        glBindVertexArray(circles.vaoObject);
        glDrawElements(GL_LINES, circles.noOfIndices, GL_UNSIGNED_INT, nullptr);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}

ShaderProgram ShaderProgram::newProgram(const std::string& vsh, const std::string& fsh)
{
    ShaderProgram program;
    auto shObjs = std::vector<GLuint>
    {
        program.compileShader(vsh, GL_VERTEX_SHADER),
        program.compileShader(fsh, GL_FRAGMENT_SHADER),
    };
    for (auto shObj : shObjs)
        program.compileStatus(shObj);
    program.linkProgram(shObjs);
    for (auto shObj : shObjs)
        glDeleteShader(shObj);
    return program;
}

GLuint ShaderProgram::compileShader(const std::string& sourceCode, GLenum shaderType)
{
    auto shaderObj = glCreateShader(shaderType);
    const char* srcCodePtr = sourceCode.c_str();
    glShaderSource(shaderObj, 1, &srcCodePtr, nullptr);
    glCompileShader(shaderObj);
    return shaderObj;
}

void ShaderProgram::linkProgram(std::vector<GLuint> shObjs)
{
    programObject = glCreateProgram();
    for (auto shObj : shObjs)
        glAttachShader(programObject, shObj);
    glLinkProgram(programObject);
    linkStatus();
}

void ShaderProgram::compileStatus(GLuint shader)
{
    GLint status = GL_TRUE;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    if (status == GL_FALSE)
    {
        GLint logLen;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLen);
        std::vector< char >log(logLen);
        GLsizei written;
        glGetShaderInfoLog(shader, logLen, &written, log.data());
        std::cout << "compile error:" << std::endl << log.data() << std::endl;
    }
}

void ShaderProgram::linkStatus()
{
    GLint status = GL_TRUE;
    glGetProgramiv(programObject, GL_LINK_STATUS, &status);
    if (status == GL_FALSE)
    {
        GLint logLen;
        glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &logLen);
        std::vector< char >log(logLen);
        GLsizei written;
        glGetProgramInfoLog(programObject, logLen, &written, log.data());
        std::cout << "link error:" << std::endl << log.data() << std::endl;
    }
}

VertexArrayObject VertexArrayObject::newCube()
{
    static const std::vector<GLfloat> vertices{ -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1 };
    static const std::vector<GLfloat> uv{ 0, 0, 1, 0, 1, 1, 0, 1 };
    static const std::vector<size_t> faces{ 0, 1, 2, 3, 1, 5, 6, 2, 5, 4, 7, 6, 4, 0, 3, 7, 3, 2, 6, 7, 1, 0, 4, 5 };

    std::vector<GLfloat> varray;
    std::vector<GLuint> iarray;
    for (auto si = 0; si < faces.size() / 4; si++)
    {
        for (auto qi = 0; qi < 4; qi++)
        {
            varray.insert(varray.end(), vertices.begin() + faces[si * 4 + qi] * 3, vertices.begin() + faces[si * 4 + qi] * 3 + 3);
            std::vector<GLfloat> uvw{ 0, 0, (GLfloat)si * 4.0f / (GLfloat)faces.size() };
            varray.insert(varray.end(), uvw.begin(), uvw.end());
        }
        std::vector<GLuint> indices{ 4u * si, 4u * si + 1, 4u * si + 2, 4u * si, 4u * si + 2, 4u * si + 3 };
        iarray.insert(iarray.end(), indices.begin(), indices.end());
    }

    return newVAO(varray, iarray);
}

VertexArrayObject VertexArrayObject::newCircles()
{
    const GLuint noC = 360;
    std::vector<GLfloat> varray;
    std::vector<GLuint> iarray;

    for (int i = 0; i <= noC; i++)
    {
        GLfloat angle = static_cast<GLfloat>(i * 2 * M_PI / noC);
        GLfloat c = cos(angle), s = sin(angle);
        std::vector<GLfloat> va{ 0, c, s, 0, 0, 0, s, 0, c, 0, 0, 1.0f / 3.0f, c, s, 0, 0, 0, 2.0f / 3.0f };
        varray.insert(varray.end(), va.begin(), va.end());
    }
    for (GLuint ci = 0; ci < 3; ci++)
    {
        for (GLuint i = 0; i <= noC; i++)
        {
            std::vector<GLuint> ia{ i * 3 + ci, ((i + 1) % noC) * 3 + ci };
            iarray.insert(iarray.end(), ia.begin(), ia.end());
        }
    }

    return newVAO(varray, iarray);
}

VertexArrayObject VertexArrayObject::newVAO(const std::vector<GLfloat>& varray, const std::vector<GLuint>& iarray)
{
    VertexArrayObject vao;
    vao.noOfIndices = static_cast<GLsizei>(iarray.size());
    vao.noOfVertices = static_cast<GLsizei>(varray.size() / 6);

    GLuint bufferObjects[2];
    glGenBuffers(2, bufferObjects);;
    glGenVertexArrays(1, &vao.vaoObject);

    glBindVertexArray(vao.vaoObject);
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, bufferObjects[0]);
    glBufferData(GL_ARRAY_BUFFER, varray.size() * sizeof(*varray.data()), varray.data(), GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(*varray.data()), 0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(*varray.data()), (void*)(3 * sizeof(*varray.data())));
    if (vao.noOfIndices > 0)
    {
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObjects[1]);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, iarray.size() * sizeof(*iarray.data()), iarray.data(), GL_STATIC_DRAW);
    }
    glBindVertexArray(0);
    glDeleteBuffers(2, bufferObjects);

    return vao;
}


Pagination on Wp-Property not working

Question: I have a Wordpress site that is using Wp-Property and the pagination isn't working, can anyone help fix this please. Please see below the pagination part from the function page.
<?php if($use_pagination) { ?>
    if(!wpp_pagination_<?php echo $unique_hash; ?>) {
      jQuery("#wpp_shortcode_<?php echo $unique_hash; ?> .wpp_pagination_slider_wrapper").each(function() {
        var this_parent = this;
        /* Slider */
        jQuery('.wpp_pagination_slider', this).slider({
          value:1,
          min: 1,
          max: <?php echo $pages; ?>,
          step: 1,
          slide: function( event, ui ) {
            /* Update page counter - we do it here because we want it to be instant */
            jQuery("#wpp_shortcode_<?php echo $unique_hash; ?> .wpp_current_page_count").text(ui.value);
            jQuery("#wpp_shortcode_<?php echo $unique_hash; ?> .wpp_pagination_slider .slider_page_info .val").text(ui.value);
          },
          stop: function(event, ui) {
            wpp_query_<?php echo $unique_hash; ?> = changeAddressValue(ui.value, wpp_query_<?php echo $unique_hash; ?>);
          }

        });

        /* Fix slider width based on button width */
        var slider_width = (jQuery(this_parent).width() - jQuery(".wpp_pagination_back", this_parent).outerWidth() - jQuery(".wpp_pagination_forward", this_parent).outerWidth() - 30);
        jQuery(".wpp_pagination_slider", this_parent).css('width', slider_width);

        jQuery('.wpp_pagination_slider .ui-slider-handle', this).append('

1

');

      });
      wpp_pagination_<?php echo $unique_hash; ?> = true;
    }
    <?php } ?>
  });
</script>
<?php
$js_result = ob_get_contents();
ob_end_clean();

ob_start(); ?>
<div class="properties_pagination <?php echo $settings['class']; ?> wpp_slider_pagination" id="properties_pagination_<?php echo $unique_hash; ?>">

      <?php
      if(function_exists('WPPFL_getNumberOfFavorites')) {
          $num_of_favorites = WPPFL_getNumberOfFavorites();
      } else{
          $num_of_favorites = 0;
      }

      $currentTemplate = "";
      if (isset($wpp_query['template'])) {
        $currentTemplate = $wpp_query['template'];
      }
      ?>
      <?php if ($currentTemplate==TEMPLATEPATH . "/list-my-property-content.php") { ?>

              <?php global $post;
              $post_name = $post->post_name; ?>
              <?php $class='class="active"'; ?>

                  <li <?php if($post_name == 'list-my-property') { echo $class; } ?>>
                      <a href="<?php echo get_bloginfo('url'); ?>/list-my-property/">
                          View Listed Properties

                  <li <?php if($post_name == 'add-new-property') { echo $class; } ?>>
                      <a href="<?php echo get_bloginfo('url'); ?>/list-my-property/add-new-property/">
                          Add New Property

      <?php } else { ?>

Search results

My Favourites(<?php echo $num_of_favorites; ?>)

      <?php } ?>

  <?php if($use_pagination) { ?>

        Pages
        <?php
        if ($pages < 10) {
            for($i=1; $i<=$pages; $i++) {
                echo ''.$i.'';
            }
        } else {
            for($i=1; $i<=$pages; $i++) {
                if (($i < 4) || ($i>$pages-3)) {
                    echo ''.$i.'';
                }
                if ($i==4) {
                    echo '...';
                }
            }
        }?>

<?php _e('Prev', 'wpp'); ?>

<?php _e('Next', 'wpp'); ?>

  <?php } ?>

<?php
$html_result = ob_get_contents();
ob_end_clean();

Thank you in anticaption.
Answer: The first thing which can cause your issue is some of third party plugins or your theme. So try firstly to deactivate third party plugins and switch theme to default one to be sure that issue doesn't relate to any of them.
Such request you can also send here
https://wordpress.org/support/plugin/wp-property
or on our site
https://usabilitydynamics.com/contact-us/
Regards.
Usability Dynamics Support

Pagination on Wp-Property not working


OpenSUSE 11 AD auth works, but not netbios

Question: I've setup a desktop machine with OpenSUSE 11.4 and have Active Directory authentication working properly. I can ping, rdp and ssh to'/from other machines. I can access windows shares from OpenSUSE and samba shares from Windows. However, the hostname won't resolve from any machine on the domain. I can ping other machines on the LAN from OpenSUSE using hostnames, but from the other machines I can only use the IP of the new machine. What am I missing?
Answer: You need to register your host with the DNS system - either from updates by the DHCP server or by manually entering the correct A and PTR entries so that other domain members can resolve.
NetBIOS name resolution is (hopefully) not used anymore as it is everything that the gods have forbidden.
Comment: Take a look at this post. It has good information about a netbios "free" network: http://serverfault.com/questions/119253/netbios-free-network
Answer: I had similar problem and solution I found realy simple but it is in dhcp server.
The problem is windows server does not use dhcp server to maintain dns records by default, and uses it's own way. You need to setup account for dhcp server in AD, like dhcp4dns, and include it in group DNS Update Proxy, then in DHCP server in properties setup account for DHCP to interact with DNS, and you're done.
Answer: Have you allowed NetBios in the firewall?
You can update this in two ways:

In the Administrator Settings (YaST), look for Firewall (probably under Security and Users). Run this, and select the Allowed Services item. Under the Service to Allow, select Netbios server, and add it to the list.
In the Administrator Settings (YaST), look for Samba Server (probably under Network Services). Run this, and in the Start-Up tab, select the Open Port in Firewall option.


Ansible Naming Rules for Roles and Collections (dash, underscore)

Question: Does Ansible have naming rules for roles and collections regarding the use of - (dash) and _ (underscore)?

I noticed that since around 2019, geerlingguy only uses underscores for role names (snake_case), but the names of his older roles contain dashes (kebab-case).

For one role in the Ansible Galaxy, I encountered the following note:

NOTE: This role has been renamed from acme-sh to acme_sh to fullfill Ansible Galaxy requirements.

I then looked through the Ansible Galaxy documentation, but only found naming conventions (limitations) for namespaces, but not for role or collection names. The example on the Creating Roles page of the Ansible Galaxy documentation also uses dashes in the name: test-role-1.

I am aware that all Ansible Builtin modules use underscores only, so strictly snake_case (as far as I have seen so far). There are probably modules that allow parameters via alias also in kebab-case (e.g. apt), but rather few.

In the Role Names section, I found this hint in the first note:

Role names are limited to lowercase word characters (i.e., a-z, 0-9) and '_'.

However, it is unclear to me for which places or operations this applies, because there are quite a few roles in the Ansible Galaxy with dashes in the name, likewise an ansible-galaxy role init my-super-role works without problems and without any hint.

Are there any Ansible or Ansible Galaxy requirements for using dashes or underscores?
Or are there official recommendations or even technical restrictions?
Is there a recommendation in general?
Answer: You're asking a number of somewhat related questions, so I'll try to break them apart and address each one individually.
Does Ansible have naming rules for roles?
Not exactly. It has technical constraints, including that the role name must be a valid filename and representable as a YAML string.
Does Ansible have naming rules for collections?
Yes. These again arise from technical constraints, but they are more well-defined and considerably stricter. The namespace, collection name, and all collection content (including roles) must be valid Python identifiers (containing only A-Z, a-Z, _, 0-9, or a subset of Unicode characters, but not beginning with a numeral.)
Does Ansible Galaxy have naming rules for roles?
Yes. Role names are limited to a-z, 0-9, and _. During import, any . and - characters contained in the repository name or role_name will be replaced with _.
Does Ansible Galaxy have naming rules for collections?
Yes. Collection names and content are limited to Python identifiers containing a-z, 0-9, and _. Import will fail if the uploaded collection artifact contains names that Galaxy does not allow.
Why does Ansible Galaxy contain roles that don't meet their naming rules?
The rules have changed over time, and forcibly removing or renaming content that existed before these rules were in place would break things for people who were using that content.
Comment: In summary, it makes sense to use only `a-z`, `0-9` and `_` for role names and for collection names to be compatible with all requirements and limitations.


Web API calls with RestSharp - prepends application/json to body causing null parameter on action

Question: I have a Web API service that I'm trying to access via the console using RestSharp.  My RestSharp code looks like this:
            RestClient client = new RestClient(baseUrlString);
        RestRequest request = new RestRequest("controllername/actionname");
        request.RequestFormat = DataFormat.Json;

        ProcessQuestion model = new ProcessQuestion()
        {
            Id = "123456",
            InstanceId = "123",
            UniqueId = "bfb16a18-d0d6-46ab-a5b3-2f0ebbfe8626",
            PostedAnswer = new Dictionary<string, string>() { { "question_7907_1", "selected" }, { "question_7907_2", "selected" } }
        };
        request.AddBody(model);

        var response = client.Execute(request)

My Web API action takes a model that has the same parameters as the above model.  When the call executes, the binding fails and the parameter is null.  I suspect this is due to the RestRequest.AddBody method prepending application/json to the body value as shown below:
{application/json={"Id":"123456","InstanceId":"123","UniqueId":"bfb16a18-d0d6-46ab-a5b3-2f0ebbfe8626","PostedAnswer":{"question_7907_1":"selected","question_7907_2":"selected"}}}

If I post using Fiddler the body binds to the model properly.  Below is the body value I provided in Fiddler:
{'Id':'123456','InstanceId':'123','Uniqueid':'bfb16a18-d0d6-46ab-a5b3-2f0ebbfe8626','PostedAnswer':{'question_7907_1':'selected','question_7907_2':'selected'}}

Note that the body value in fiddler is the same with the exception of prepending the application/json key.
Also to note: I've tried what seems like everything...I've separated the parameters out in the action, used FromBody and FromUri attributes, tried custom DictionaryModelBinder's, tried custom ValueBinders, tried changing the way I'm using RestSharp (AddParameter with a RequestBody parameter, AddObject, different URL styles, etc.).
Has anyone else encountered this, and if so, did you solve it?  I chose Web API for this service with hopes the model binding would work as it does in MVC, but I'm seeing that isn't the case.
Thanks
EDIT (resolved):
RestSharp automatically uses the JsonSerializer for objects passed in the AddBody method. I figured I was missing something simple, and indeed I was... Adding the Method.Post parameter to the RestRequest instantiation solved the problem.
Answer:
Specify the method when creating the request:
RestRequest request = new RestRequest("controllername/actionname", Method.POST);
Not sure what the default serializer is for body - you can try making it explicit:
request.AddBody(request.JsonSerializer.Serialize(model));
I'm not sure where the 'application/json' is coming from - that's the Content-Type header you should be sending with your request, definitely not part of the body. So do this instead:
request.AddHeader("Content-type", "application/json; charset=utf-8");
If this doesn't help, try making your code as similar to the example on their site as possible. Try removing complexity (even if it means changing the required functionality) - get it to a point when it works and build additional functionality on that.

http://restsharp.org/
Comment: RestSharp automatically uses the JsonSerializer for objects passed in the AddBody method.  I figured I was missing something simple, and indeed I was... Adding the Method.Post parameter to the RestRequest instantiation solved the problem.  Thanks.


why $E-F=W-E^c?$

Question: From Rudin book Real and complex analysis ,page no : $48$

$\bf 2.17\ $ Theorem $\ $ Suppose $X$ is a locally compact, $\sigma$-compact Hausdorff space. If $\frak M$ and $\mu$ are as described in the statement of Theorem $\it 2.14$, then $\frak M$ and $\mu$ have the following properties:
$(a)\ \ $ If $E\in\frak M$ and $\epsilon>0$, there is a closed set $F$ and an open set $V$ such that $F\subset E\subset V$ and $\mu(V-F)<\epsilon$.
$(b)\ \ $ $\mu$ is a regular Borel measure on $X$.
$(c)\ \ $ If $E\in\frak M$, there are sets $A$ and $B$ such that $A$ is an $F_\sigma$, $B$ is a $G_\delta$, $A\subset E\subset B$, and $\mu(B-A)=0.$

In the third paragraph proof  Rudin say that apply this to $E^c$ in place of $E$ :There is an open set  $W \supset E^c $ such that $\mu(W-E^c)  < \epsilon /2.$If $F= W^c $, then $F \subset E$ and $E-F=W-E^c$. Now $(a)$ follow
Im confused that  why $E-F=W-E^c?$
Here $F=W^c$ so  it should be  $E-F=E-W^c $
Answer: $p \in E - W^c$ if and only if it is in $E$ and it is not in $W^c$. Not being in $W^c$ is the same as being $W$. I.e., $$E - W^c = E \cap W$$
I'll assume I don't need to go further.

why $E-F=W-E^c?$


a non trivial example: $G/H$ is isomorphic to $G$

Question: I need a non trivial  examples of group isomorphism that maps $G\to H$ such that
 $G/H \cong G$.
Comment: By $G\setminus H$, do you mean the quotient $G/H$? And do you want it to be isomorphic to $G$ (as in your title) or $H$ (as in your body)?
Comment: sorry for mistake , yes I meant the quotient groups  by G/H
& I want isomorphic to G @ChrisEagle
Comment: There are examples that aren't direct products. Such a the [prufer group](http://en.wikipedia.org/wiki/Quasicyclic_group) but these are more complicated in nature.
Comment: The same question has been asked 10 times on math.SE ;)
Answer: For both the title and the text of the question, you can take $G=\mathbb Z\times\mathbb Z\times\mathbb Z\times\mathbb Z\times\dots$ (an infinite product) and
$H=\mathbb Z\times\{0\}\times\mathbb Z\times\{0\}\times\dots$.  Then all three of $G$, $H$, and $G/H$ are isomorphic.  (You can replace all the $\mathbb Z$'s by your favorite other group to get more examples.)
Comment: E is my favourite group :(
Answer: The first finitely generated example found was the Baumslag-Solitar group $G = \langle x,y \mid y^{-1}x^2y = x^3 \rangle$, with $H$ equal to the normal closure in $G$ of $w^2x^{-1}$, where $w=x^{-1}y^{-1}xy$.
So $G/H \cong \langle x,y,w \mid y^{-1}x^2y = x^3, w = x^{-1}y^{-1}xy, x=w^2 \rangle$.
Eliminating $x$, using $x=w^2$, gives
$G/H \cong \langle y,w \mid y^{-1}w^4y = w^6, w = w^{-2}y^{-1}w^2y \rangle = \langle y,w \mid y^{-1}w^2y=w^3 \rangle \cong G$
(because $y^{-1}w^2y=w^3$ implies $y^{-1}w^4y = w^6$, so that relation is redundant).
That's all reasonably straightforward but, although it seems very plausible that $H$ is a nontrivial subgroup of $G$, that does need to be proved, and you need the theory of HNN extensions to prove it.
Answer: One additional example, as the OP asked for a group defined without direct products: fix a prime $p$ and let $T_p=\{z\in\mathbb{C}:\exists n\hspace{3pt}z^{p^n}=1\}$. Let $\varphi:T_p\to T_p$ be defined by $\varphi(z)=z^p$. Then $\varphi$ is a epimorphism (surjective homomorphism) which is not injective, i.e. $\ker(\varphi)\neq\{1\}$, and $T_p/\ker(\varphi)\cong T_p$.