Angular, Java Service REST

Question: Estou tentado fazer a persistência (inserir dados) usando AngularJS e WebService REST em Java, quando clico em Inserir, no console, aparece o seguinte erro:

POST http://localhost:8080/Cast_Frotas/rest/curso/insert 415 (Unsupported Media Type).

O que poderia ser?
//WEB.XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID"
         version="2.5">

  <display-name>Cast_Frotas</display-name>

  <servlet>
    <servlet-name>Jersey RESTfull</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>br.com.Cast_frotas.service</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Jersey RESTfull</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

//MEU CONTROLE EM ANGULAR
$scope.inserir = function (){
    $http.post(linkservice + "insert", $scope.curso).then(function(data){
        alert('Curso inserido com sucesso!');
    });
}

//CLASSE CURSO
public class Curso {
    private int id;
    private String nome;
    private String descricao;

    public Curso() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }
}

//CLASSE CtrlCURSO
public class CtrlCurso {

    public boolean insert(Curso c){
        return CursoDB.getInstance().insert(c);
    }

    public List<Curso> getList(){
        return CursoDB.getInstance().getListAll();
    }
}

//MEU SERVIÇO
@POST
@Path("/insert")
public void inserirCurso(Curso c){
    new CtrlCurso().insert(c);
}

Comment: Qual biblioteca você está usando para processar o JSON na seu Java WebService?
Comment: Felipe, estou usando JSONObject
Answer: Você precisa adicionar a anotação @Consumes(MediaType.APPLICATION_JSON):
@POST
@Path("/insert")
@Consumes(MediaType.APPLICATION_JSON)
public void inserirCurso(Curso c){
    new CtrlCurso().insert(c);
}

Comment: Felipe, obrigado por responder, mais uma vez. Eu estou conseguindo inserir, porém, o objeto chega nulo pro meu serviço, ou seja, insiro tuno nulo. Eu não preciso acessar os valores do json e colocar em variáveis?
Comment: meu código:  @POST
 @Path("/insert")
 @Consumes(MediaType.APPLICATION_JSON)
 public void inserirCurso(){
  Curso c = new Curso();
  System.out.println(c.getDescricao());
  try{
   new CtrlCurso().insert(c);
  }catch(Exception e){
   e.printStackTrace();
  }
 }
Comment: @MatheusMinguini Por que você você tirou o parâmetro `Curso` do método? É esse parâmetro `Curso` que você vai receber na requisição do Angular. O que você fez no código acima foi criar uma nova instância do objeto `Curso` e não atribuir nenhum valor a suas propriedades. Quando você diz que "insere nulo" seria sobre o seu `getListAll` não retornar nada?
Comment: Retorna sim, retorna um JSON normal! Realmente, eu não me atentei que avia tirado o parâmetro de recebimento da função, porém, após colocar o parâmetro, o erro 415 (Unssuported MediaType) retornou. Mas sim, a minha função getListAll() pega os dados do banco e retorna os mesmos em formato JSON
Comment: @MatheusMinguini Edite sua pergunta e coloque o seu `pom.xml`, `web.xml` e suas classes `CtrlCurso`, `Curso` e `CursoService, por favor.
Comment: editei. Eu não possuo o pom.xml, esse arquivo é para projetos com Maven, certo?
Comment: @MatheusMinguini Sim, é. Você está adicionando todas as dependências na mão? Que coragem! Poderia listá-las para eu testar aqui? Além disso, coloque a classe `CursoService` completa por favor.
Comment: Feipe, eu consegui aqui! Mas muito obrigado, você esteve me ajudando durante o dia todo! Eu estava tentando receber um objeto curso, quando na verdade deveria receber uma String, passá-la para JSON e depois, construir um objeto a partir dos atributos do JSON. OBrigado mesmo, muito sucesso pra você! Como faço para postar o código resolvido?
Comment: @MatheusMinguini Como você tem menos que 100 de reputação, você precisa esperar 8 horas para responder sua pergunta. Além disso, para marcá-la como correta, você precisa esperar 48 horas. [fonte](http://pt.stackoverflow.com/help/self-answer). Quanto a receber como uma `String`, isso não é necessário. O Jersey consegue converter o JSON para um objeto. Você só precisa aplicar uma pequena configuração (que varia de acordo com o processador de JSON que você estiver usando) para que ele faça isso para você. Dê uma olhada [nesse link](https://jersey.java.net/documentation/latest/media.html).

Angular, Java Service REST


Repairing cymbals?

Question: I have a bunch of cymbals that are in various fairly poor states of repair. One has a few small cracks near the rim. One is just bent out of shape entirely (I don't know how that happened).
Is it possible to hammer a bent cymbal back into shape? If so, what's the best way, and what tools should I use?
What should be done about cracks? At the moment, mine are only small, but they are affecting the sound, and I don't want them to get bigger. I was thinking of drilling holes in the ends, to prevent the crack from continuing, and then trimming the sides of the cracks, and smoothing with a dremel. Does that sound sensible, or are there other suggestions?
Comment: once your cymbals has cracked, it will never be or sound the same again:(. If you try to fix the crack with patch works, will more alter the sound of the cymbal.
Answer: Yes, drilling the end of each crack will stop it from spreading.
As far as bent cymbals go, simply hammering it back will cause additional tonal change (an possibly cause a crack, or section to chip off).  It is possible to repair the shape, but the sound will never be the same.
If you have access to vice-grip or a table vice, I would recommend the following:  Wrap the bent section in cloth, or thin sheet-foam. Put that section in the vice, and tighten it to a point where the cymbal will not fall out (but not so tight you cannot wiggle it a little).  Make sure you are wearing safety glasses  Then, slowly, bend the cymbal back to shape.   Do not use any sort of heating element, or blow torch - heating metal to a point that it is malleable will alter the tonal properties even more, and can be very dangerous
As "gurney alex" mentioned, two cymbals will not ever sound identical over time.  As you play a cymbal it's tonal response will start to change as certain areas take more wear than others...
Answer: A dented or bashed cybal is repairable - just get it hammered out.
Cracks are permanent, though, altering the sound. If you want your original sound back you will need to buy new ones.
Cracks can give you an interesting sound though, so don't throw them away - your idea to prevent the cracks spreading is good though, remove the point of stress by drilling holes or widening the end point of each crack. That way you can 'fix' the cracks where they are, and preserve the current tone to some extent.
Of course, you may get new cracks... :-)
Answer: An oft-used repair is to cut around the crack with a band saw, or similar.
Carefully done, with the raw edges filed so they're no longer ragged, will give new life to the poorly cymbal. It may not sound exactly the same as previous, but will still be very usable, just won't look as good as it did. But it certainly saves junking it. I've done it successfully a few times.

Repairing cymbals?


Approximate Metropolis algorithm - does it make sense?

Question: Some time ago Xi'an asked What is the equivalent for cdfs of MCMC for pdfs? The naive answer would be to use "approximate" Metropolis algorithm in form

Given $X^{(t)} = x^{(t)}$
    1. generate $Y \sim q(y|x^{(t)})$
    2. take $$ X^{(t+1)} = \begin{cases}   Y & \text{ with probability } & \min\left(  \frac{F(Y+\varepsilon) - F(Y-\varepsilon)}{F(x^{(t)}+\varepsilon) - F(x^{(t)}-\varepsilon)} , 1 \right)\\
x^{(t)} & \text{ otherwise.} \end{cases} $$

where $F$ is a target CDF and $\varepsilon$ is some small constant. This enables us to use Metropolis algorithm with CDF's.
The question is: is there any reason why this may actually be a bad idea?
Comment: Have you seen [my answer](http://stats.stackexchange.com/a/211831/80479) to Xi'an question? I think we are proposing a similar thing (you don't even need to use Metropolis, in fact, since you have the CDF). The problems are listed at the end of my answer (the cost of evaluating the approximation is exponential in the number of dimensions).
Comment: @lacerbi thanks. I know that since I have CDF I do not need it, it's just curiosity. Anything besides the cost?
Comment: @Tim: thank you for the proposal. A potential solution when $X$ is multidimensional is to proceed by Gibbs sampling and take $\epsilon$-derivatives one direction at a time.
Comment: @Xi'an yes this could be easily extended to Gibbs, M-H etc.
Answer: No, I don't see why this is a bad idea. It seems to me that it is a natural (and interesting) extension to draw samples from a CDF.
However, I believe that the acceptance should be
$$ \min\left(  \frac{F(Y+\varepsilon) - F(Y)}{F(x^{(t)}+\varepsilon) - F(x^{(t)})} , 1 \right) $$
because by definition
$$ \lim_{\varepsilon\rightarrow 0}\frac{F(x + \varepsilon) - F(x)}{\varepsilon} = PDF(x)$$
Nevertheless, it is the first time I see this. With a strong case for sampling from a non-trivial CDF, this could become an interesting publication.
Comment: The acceptance criterion proposed by OP is motivated by the central difference expression of the derivative as $\lim_{\epsilon\rightarrow 0} (F(x+\epsilon) - F(x-\epsilon)) / (2\,\epsilon)$, see for example http://math.stackexchange.com/a/888280/104295. (I have no idea whether there are some reason to believe either of these approximations to work better in this case).
Comment: @JuhoKokkala +/- approach also treats boundary cases evenly.


Postfix/Dovecot relay or proxy?

Question: I'm trying to figure it out how to reverse proxy based on condition email servers or how to deal with sending/receiving emails from different servers on only 1 public IP address?
My current configuration is as below:

I have successfully managed to proxy web servers (OpenLiteSpeed) based on condition with OPNsense + HAproxy e.g. domain1.com -> Web Server1; domain2.com -> Web Server2; etc.
A records of every domain is pointed at my public IP address and web traffic is handled by OPNsense and HAproxy to specific local server based on conditions.
The problem is that i can't make it work to do the same thing with Postfix/Dovecot. So every mail server e.g. mail.domain1.com, mail.domain2.com etc. A record and MX record is also pointed at my public IP address but handled internally by separated server.
I know i can port forward, 25,465,993 etc. from my dedicated server to specific mail server but that works only at specific server and others will be unable to handle mails.
Any idea how to solve this?
I just read about that but not sure if it can work as it should ->
global
    # ... (unchanged)

defaults
    # ... (unchanged)

frontend email_frontend
    bind *:993 ssl crt /path/to/ssl_certificate.pem # IMAPS
    bind *:995 ssl crt /path/to/ssl_certificate.pem # POP3S
    bind *:25  ssl crt /path/to/ssl_certificate.pem # SMTP
    mode tcp
    tcp-request inspect-delay 5s
    tcp-request content accept if { req_ssl_hello_type 1 }

    acl is_domain1 req_ssl_sni -i domain1.com
    acl is_domain2 req_ssl_sni -i domain2.com

    use_backend backend_domain1 if is_domain1
    use_backend backend_domain2 if is_domain2

backend backend_domain1
    mode tcp
    server mail_server_domain1 172.16.0.2:993 check # IMAPS
    server mail_server_domain1 172.16.0.2:995 check # POP3S
    server mail_server_domain1 172.16.0.2:25  check # SMTP

backend backend_domain2
    mode tcp
    server mail_server_domain2 172.16.0.3:993 check # IMAPS
    server mail_server_domain2 172.16.0.3:995 check # POP3S
    server mail_server_domain2 172.16.0.3:25  check # SMTP

Comment: Why do you need multiple mail servers?
Comment: @vidarlo because I have different VMs (Servers) running on CyberPanel and each server have its own mail server. And Cyber Panel handle GUI for email management, TLS certificates and other stuff automatically...
I don't know how to deal with that in any other way....
Answer: TL;DR: You can use HAproxy in front of SMTP servers that are MX hosts only to do load balancing. You can not use it to select which server to route a request to based on some domain name. All the backends should be similar, in particular, all of them must introduce themselves with the same server name in the initial greeting. This is all due to the nature of SMTP protocol and various expectations of the SMTP server behaviour the world is converged on.
Caution: Having multiple distinct mail servers (that introduce themselves differently) behind single public IP is a very bad idea. For example what will happen: you'll get that IP blacklisted.
Overall, if I understand your intention correctly, it is impossible to achieve what you want.

You have three ways to have a load balanced setup for various email-related services:

For RAW TLS ports (465, 993, 995): strip TLS/SSL on HAproxy, but then you need to use their unencrypted counterparts for backends: a SMTP submission backend will go to 587 (instead of 465, where HAproxy front-end should be listening), an IMAP to 143 (instead of 993) and POP3 to 110 (instead of 995). Then you need a certificate and a key on the HAproxy machine.
For RAW TLS ports: don't strip TLS, but parse unencrypted TLS headers and act accordingly  (as you do with acl ... req_ssl_sni ...). In that case, your backend will need to have a certificate configured, and HAproxy doesn't need it.
For any port: don't strip and don't parse TLS, and let HAproxy just handle TCP streams; all the TLS/SSL handling will be done on back-end servers. In this case, you should not set up any certificates on HAproxy, but set them up on the real back-end servers.

Port 25 is not a RAW TLS port; the set-up as in options 1 or 2 above are not available (at least, that easy). SSL/TLS here is only supported in so called STARTTLS mode. Instead of ClientHello, the conversation starts as usual SMTP, e.g. first server sends a greeting, and then client sends EHLO, and if server indicates the support for STARTTLS, the client may (or may not) issue the STARTTLS command and only then ClientHello appears. Totally the same works 587. Ports 110 and 143 work in a very similar manner: client waits for server indication for STARTTLS and then issues the STARTTLS command, the only difference is that conversation starts as usual POP3 and IMAP, respectively.
Unfortunately, this is not the scheme HAproxy expects. You can not expect it to follow the SMTP conversation, find the TLS within it, and extract the SNI on the port 25, as you have it in configuration. The other three client-related ports you can not expose at all, using their raw TLS counterparts (for which options 1 or 2 are available); but, for the port 25 this is impossible and you have to process SSL for it in-band, using STARTTLS, on the real mail servers. There is no RAW counterpart for that service, for compatibility reasons. The only option available for it is option 3 from above: don't do any TLS-related processing on the HAproxy at all.
This also implies you can't have "purely name-based SMTP virtual hosts on the single IP" as you do with HTTPS through SNI.

A side note: I wrote about ports 465 and 587, but I don't see them in your configuration. It seems you don't use a dedicated submission/smtpd service for client e-mail submissions and I suspect you are doing authenticated submissions on port 25. This is not a good and secure setup and it's way harder to get managed correctly. Make your life easier: remove any authentication support on port 25; it's only for reception of mail from other mail servers. Enable submission or/and smtps services in master.cf and only support authentication for these, and update client configurations in a similar way to only use submission service for submitting mail.
Another side note: are you really using POP3? Why? Anything you can do using POP3 you can do through IMAP. Just don't set it up, as if it never existed :)
Answer: The multiplexing is handled by the application protocol. Haproxy knows HTTP so it can deal with the HTTP traffic. OTOH it doesn't speak SMTP. While you could route the traffic based on Postfix transport maps, Postfix has explicit functionality to act a relay at the receiving end. But this would require some DNS gymnastics to provision a split zone reporting the internal address as the MX. I'd be using a Postfix recipient map, something like:
recipient_canonical_maps = hash:/etc/postfix/mydomains

Where the latter contains....
@domain1.com @vm1.internalzone
@domain2.com @vm3.internalzone
...

NB some caution - you need additional config to prevent this becoming an open relay (relay_domains should work). Make sure you test the config.
But I can't help feeling that this is essentially a bad architecture - tying the the domains to specific instances. I would be more tempted to consolidate by function. And based on the information provided, the opensense VM is adding no value to the service.
Answer: With postfix you don't need to reverse proxy, postfix can handle multiple domains
In your postfix main.cf you create
transport_maps = hash:/etc/postfix/transport

And also specify for which domains this server will be accepting mail
mydestination = example.com example2.com example3.net

And in the transport file you specify the mail server responsible for each domain
example.com    smtp:[mailserver1.example.com]
example2.com   smtp:[mailserver2.example.com]

Then run postmap /etc/postfix/transportand restart or reload postfix
Comment: Also, this relay must be made a smarthost for all those internal servers: if they happen to send mail outside directly, the IP will be blacklisted *for certain*.
Comment: While a good suggestion overall, this has an obvious downside that the mail for unknown recipients can no longer be rejected right away, because such a relay won't have the list of valid recipient addresses for each domain. Without precautions this solution will lead to backscatter, and, eventually, again, blacklisting the IP. I am sure it's the idea of having a dedicated server for each domain is what is flawed. In general, the best is probably still to run a single full-blown virtual domain server for all domains, which will be the final destination for all these domains.

Postfix/Dovecot relay or proxy?


Notice: Undefined index: 1 in user_node_load()

Question: I deleted the user uid 1 and successively I created another user as admin.
Now appeared a number of errors like these:
<code>Notice: Undefined index: 1 in user_node_load() (line 3641 of /mysite/modules/user/user.module).
Notice: Trying to get property of non-object in user_node_load() (line 3641 of /mysite/modules/user/user.module).
Notice: Undefined index: 1 in user_node_load() (line 3642 of /mysite/modules/user/user.module).
Notice: Trying to get property of non-object in user_node_load() (line 3642 of /mysite/modules/user/user.module).
Notice: Undefined index: 1 in user_node_load() (line 3643 of /mysite/modules/user/user.module).
Notice: Trying to get property of non-object in user_node_load() (line 3643 of /mysite/modules/user/user.module).
Notice: Undefined index: 1 in user_node_load() (line 3641 of /mysite/modules/user/user.module).
Notice: Trying to get property of non-object in user_node_load() (line 3641 of /mysite/user/user.module).
Notice: Undefined index: 1 in user_node_load() (line 3642 of /mysite/modules/user/user.module).
Notice: Trying to get property of non-object in user_node_load() (line 3642 of /mysite/modules/user/user.module).
</code>
This user.module code.
<code>  // Add these values back into the node objects.
  foreach ($uids as $nid => $uid) {
    $nodes[$nid]->name = $user_fields[$uid]->name;
    $nodes[$nid]->picture = $user_fields[$uid]->picture;
    $nodes[$nid]->data = $user_fields[$uid]->data;
  }
</code>
Can u help me?
Comment: You should never delete user 1. Even if you create another user with Admin role is not going to be the same. Some rule looks for uid 1.
Comment: Sorry to hear that. Best this would be to restore from a previous back up. Have you tried to recreate it manually?
Comment: thx Durden but anyone have hacker my site and cancel my admin account.
Comment: The issue is handled in [Warnings in user_node_load() for deleted users](https://www.drupal.org/project/drupal/issues/2653342).
Answer: I have change uid to 1 of new admin user in database and all sound good.
Comment: Now you should review all security concerns of your site to prevent from hackers.


How to find a class in a list of Nuget packages

Question: My team is using more and more NuGet packages as a way to break the system into smaller pieces and share things between parts. We have adopted a sort of SRP principle for packaging, creating small and hopefully cohesive packages that do just one thing (logging, auditing, security stuff, etc).
Ideally they should be so cohesive and self-contained that it would be straightforward to know what package will contain what you need. However we are not yet there and sometimes is difficult to know what package you should add to access some functionality.
My question is: is there any way to publish and navigate package content information? Like, for instance, in MSDN you can see what assembly contains a class. Would it be possible to know something like that, at the package level?
Thanks.
Answer: It's a very localised version, but there is a package searcher for the ASP.NET 5 packages hosted on NuGet. It might be possible to host a version that looks at a wider scope at some point.
https://packagesearch.azurewebsites.net/
Answer: The closest functionality I can think of is implemented in ReSharper. However it can only search the packages in nuget.org(closed issue on GitHub). Since packages don't expose type info, JetBrains built a custom index and that's the only data source it can query.


Need help with understanding the Fifth of a chord

Question: I'm trying to figure out what is the fifth of a chord, in order to determine which note to play for alternating bass line technique with guitar.
According to wikipedia:

the fifth factor of a chord is the note or pitch five scale degrees above the root

For example, if the chord is C, then the fifth of it is G. But as I count, G is only 4 step above C. D=1, E=2, F=3, G=4.
If we count as C=1 and C to D = 2, then G will end up to be the 5th. But that also mean D is 2 steps above C, and 1 step above C is still C. It doesn't make sense.
Comment: Wikipedia is changed.
Comment: It's the difference between inclusive and exclusive counting. Ultimately, it's why two thirds don't add up to make a sixth, but rather a fifth.
Comment: Wikipedia is wrong because you don't count intervals with scale degrees, you count the notes, inclusively (So to find the fifth of C you would count C as 1 and D as 2 and so on, til you got to G, the fifth.)
Comment: First degree of scale is counted as 1.
Answer: The other answers have explained where the misunderstanding was, but on guitar (or bass) an alternating 1-5-1-5 is so simple, it's not even necessary to know what the 5 note is. Others will doubtless say the opposite, but here it is anyway. If the 1 is on the bottom string ( and you will know what 1 is, even if you don't know what 5 is) the 5 is on the 5th string, 2 frets higher. If 1 is on the 5th string, 5 has two homes - same fret 6th string, or two frets up on the 4th string.
It'll be there always, unless it's a dim or aug 5, which won't happen very often. Only kidding about the importance of knowing notes, but in this case, on guitar or bass, I doubt if anyone actually thinks about the name of the 5th. Just play!
Check out a previous question - 'Why intervals are not named after distance'.
You asked about if the bass note is D open 4th. Well, the 5th of it is the open A string - same 'fret', one string lower. There is another D at 5th fret 5ths string, and yet another at 10th fret, 6th string. Or, next string higher (in pitch) 2 frets up, gives 3rd string 2nd fret, like I said.
The bottom string is what we call low E - the fattest string.
Comment: You are on the right track. Except that we're talking diatonic, as in the notes from a particular key. So, if B is the 1, then in the key of B, F# is 5. F is 5 if 1 is Bb. Believe me, it's far simpler and works well to use the strings and frets idea. It works, without involving theory, which has been known to befuddle intelligent people.
Comment: Thanks for the tip, but I'm not quite understand. What do you mean by bottom string? How can your rule apply to this case: D chord bass is 4th string, and its 5th is A-5th string, same fret (open). Also I found that if the bass line is B-5th string 2nd fret, then its 5th is indeed same fret 6th string, which is F#. But I thought if we count up from B, should it be F instead of F#?
Answer: When you count intervals (such as fifths) it's inclusive; you count the starting note.
So the finding the fifth of C is gonna look like

C(1) D(2) E(3) F(4) G(5)

The letters represent the note names (obviously) and the numbers represent the iteration of counting, and, consequently, the interval.
You could keep going, of course (now I feel like I'm trying to teach you how to count. "You know how to count, right? I guess I should stop now." - Annoying Mother)
Comment: The *names* of intervals are inclusive, but that doesn't justify saying "the fifth factor of a chord is the note or pitch five scale degrees *above* the root".
Comment: @topomorto Woah, hold on a second, are chord factors and intervals entirely separate concepts? Because if so, I repent. I'm just explaining the "right" way to do it.
Comment: From the looks of it, the original poster is counting intervals by counting the steps in between the notes, which is not correct. I was trying to explain the correct way to count intervals.
Comment: Yes, sorry, I wasn't contradicting what you wrote - I just thought we should be clear that Wikipedia was "taking it too far".
Comment: @topomorto Aha! I see. Sorry, I have a bit of a phobia of being wrong on Stack Exchange. They aren't as forgiving on SO...
Answer: Just to add to the other answers you call C to D a second because from the root note that is exactly that, the second interval. The Unison is actually the first interval from the root note and then you get the second and so on and so forth.
Answer: As this recent question and other answers here have highlighted, intervals are named 'inclusively'...
... but that's a red herring here, because

"... is the note or pitch five scale degrees above the root"

doesn't mention the interval name; it states that the interval in question is the fifth degree above the root. As such, it was a wrong statement; just as wrong as saying 'the root of a chord is the note one scale degree above the root'.
So you were correct to be confused! At the time of writing, the page has now been corrected (by margalo) to say

the fifth factor of a chord is the note or pitch that is the fifth scale degree, counting the root or tonal center.
Comment: I still think it's more important to correctly explain the "right" way to do it.


It's possible to append Cursors?

Question: I'm looking to add the content of an Cursor to an existing Cursor.
Comment: yes. use a MergeCursor.
Comment: OR... you can use the `UNION` clause in your queries, to get an already "merged" cursor.
Answer: Yes as @njzk2 already suggested you can use a MergeCursor like this:
final Cursor mergedCursor = new MergeCursor(new Cursor[] {
        firstCursor,
        secondCursor
});

After that you can use the merged Cursor like you would use any other. getColumn() and getColumnIndex will return the values of the item at the current position. Here you can find some documentation.
Of course you can always JOIN tables or use UNION in your SQL queries.

It's possible to append Cursors?


How to show $\frac12\cdot\frac34\cdot\frac56\cdots\frac{99}{100}<\frac{1}{12}$?

Question: How can I show that $$\frac12\cdot\frac34\cdot\frac56\cdots\frac{99}{100}<\frac{1}{12}?$$
Comment: One is tempted to write a computer program to calculate the product.  It will surely run in a tiny fraction of the time required to write the program (which might be only a matter of minutes, depending on your expertise or familiarity with Excel, for example).
Comment: Easy proof: Take $A=\frac{1}2\ldots \frac{99}{100}$. Then $A^2 = (\frac{1}2\ldots \frac{99}{100})(\frac{1}2\ldots \frac{99}{100}) < (\frac{1}2\ldots \frac{99}{100})(\frac{2}3\ldots \frac{98}{99})$ and cancel out equal terms from numerators and denominators.
Answer: For $m,n\in\mathbb{N}$ with $m\leq n$, let $S_{m,n}:=\prod_{i=m}^n\,\frac{2i-1}{2i}$.  Then, $$S_{m,n}^2=\prod_{i=m}^n\,\left(\frac{2i-1}{2i}\right)^2 \leq \prod_{i=m}^n\,\left(\frac{2i-1}{2i}\right)\left(\frac{2i}{2i+1}\right)=\prod_{i=2m-1}^{2n}\,\frac{i}{i+1}=\frac{2m-1}{2n+1}\,.$$
Therefore, $S_{m,n}\leq\sqrt{\frac{2m-1}{2n+1}}$.  In particular, $S_{4,50}\leq\sqrt{\frac{7}{101}}$.  Now, $S_{1,50}=\frac{1}{2}\cdot\frac{3}{4}\cdot\frac{5}{6}\cdot S_{4,50}$.  Hence,
$$S_{1,50}\leq\frac{15}{48}\sqrt{\frac{7}{101}}<\frac{1}{12}\,.$$
You can also show that $S_{m,n}\geq\sqrt{\frac{m-1}{n}}$, so $S_{1,50}\geq\frac{1}{2}\cdot\frac{3}{4}\cdot\frac{5}{6}\cdot\frac{7}{8}\cdot\sqrt{\frac{4}{50}}=\frac{7}{64\sqrt{2}}$.  This will give you $\frac{1}{13}<S_{1,50}<\frac{1}{12}$. Asymptotically, $S_{1,n}\sim\frac{1}{\sqrt{\pi n}}$.  Indeed, $$\frac{1}{\sqrt{\pi\left(n+\frac12\right)}}<S_{1,n}<\frac{1}{\sqrt{\pi n}}\,.$$
Answer: Assuming that you know factorials and their approximations, rewrite $$A=\frac12\times\frac34\times\frac56\times\cdots\times\frac{99}{100}=\frac12\times\frac22\times\frac34\times\frac44\times\frac56\times\frac66\times\cdots\times \frac{99}{100}\times \frac{100}{100}$$ $$A=\frac{1}{4^{50}}\frac{1\times2\cdots\times 100}{(1\times2\cdots\times 50)^2}=\frac{1}{4^{50}}\frac{100!}{(50!)^2}$$ At this point, we can use Stirling approximation of the factorial $$n!\approx \sqrt{2\pi n} \big(\frac n e\big)^n$$ So $$A_n=\frac{(2n)!}{4^n (n!)^2}\approx \frac{1}{\sqrt{\pi n}}$$ For the problem, use $n=50$.


Display Node Title field in Field group

Question: I can't find the solution to print (display) Drupal's Node Title in a field group? I want my Node Title in the field group (see image).

In this project I can't use Display Suite. I also can't find a template suggestion for a field group?
How do I manage to do this?
Answer: A solution would be to install the Display Suite module.
Once both Display Suite and Display Suite UI modules are enabled you must go to the presentation, choose a layout at the bottom and save, then you will have a lot of fields that weren't available before. One of those fields is the node title.
Comment: yes I know DS has this option, but like I described in my question I can't use DS. Because I think DS will mess-up, the already themed and styled site. Is there a way doing it without DS? Or is there nothing to be afraid of using DS and add it to my already styled and themed website?
Comment: It may, or may not, mess this particular content type. But it shouldn't damage any other content type template. I'd do a backup, cross my fingers and try it.

Display Node Title field in Field group


MySQL date format functions in Drupal

Question: How can I do a MySQL date function in Drupal?
I have this now:
$select = db_select('someTable', 'st');
$select->addExpression('DATE_FORMAT(FROM_UNIXTIME(created), "%Y-%m")', 'createdMonth');

$date = $select->execute()->fetchAll();

When I run this I get an exception that says:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '%Y-%m' in 'field list'"

But if I print the $select object I see it should run
SELECT DATE_FORMAT(FROM_UNIXTIME(created), "%Y-%m") AS createdMonth FROM {someTable} st

And when I copy this to Sequel Pro it just runs.
What am I missing?
Comment: Take a look on this it may helps you http://cgit.drupalcode.org/month/commit/?id=a8b28ea
Answer: You're a 'victim' of MySQL's ANSI_QUOTES SQL mode:

Treat """ as an identifier quote character (like the "`" quote character) and not as a string quote character. You can still use "`" to quote identifiers with this mode enabled. With ANSI_QUOTES enabled, you cannot use double quotation marks to quote literal strings, because it is interpreted as an identifier.

Emphasis mine.
That explains why MySQL is trying to find a column called '%y-%m' rather than interpreting it as a string.
So you need to switch your SQL mode to something else, or (more reasonably), just use single quotes for literals:
$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(created), '%Y-%m')", 'createdMonth');

Many other DBMSs don't accept double quotes for string literals, so using single quotes is a good habit to get into anyway.
Comment: I think the Drupal coding standards suggest to use the double quotes for SQL strings exactly to avoid this problem. It has been a while since I was approving the CVS applications to become maintainer, so the coding standards could be changed, in the while. `:D`

MySQL date format functions in Drupal


Why isn't every method is a static method?

Question: If non-static functions are copied into the heap for each object that has that method, then why aren't all methods in Java static by default?  Why waste all of that heap memory this way?
A diagramic explanation would be more helpful for me to understand this.
Comment: As far as methods go, `static` keyword indicates that the method is at class level and does not pertain to any particular instance and has nothing to do be memory allocation, stack or heap memory.
Comment: This question begs another question -- have you read anything on OOP techniques?
Comment: @Hovercraft Full of Eels- I think that this question was phrased poorly when it was asked.  The question is not "why have nonstatic methods at all," but rather "it seems like nonstatic methods use way more space than static methods; why is this the default?"
Comment: @Andrew Thompson - AMEN!
Answer: Static methods cannot access an object's instance member variables... No state, no OOP.
Answer: Your question is for a comparison between procedural and object-oriented programming. http://en.wikipedia.org/wiki/Procedural_programming#Comparison_with_object-oriented_programming. The primary motivation for OO versus procedural is to have data structures capable of performing actions themselves.
As for the assumptions about memory allocation, methods are not copied to each object because Java does not support dynamic type modification. For example, if an object is of type Foo, then it will have all of the methods declared by type Foo. New methods cannot be added to instances of Foo without changing the type itself. Whenever a method is called on an object, behind the scenes it is run as a procedure.
Whenever you run this:
foo.say( "Hello, world!" );

Java actually does something like this:

Create the string "Hello, world!"
Look for the type declared for foo.
Look for a method with the signature say(String) in that type.
Run that method using the foo object's instance state.

Because methods maintain their own state, any non-static method can be implemented in a static way by passing the object instance in as a method parameter. In fact, step 4 above is likely implemented this way by the Java compiler.
Answer: Typically, Java methods are not implemented by copying the method onto the heap once per object.  Instead, methods are typically implemented using something called a virtual function table (or "vtable").  The idea is that there is exactly one copy of each method, whether it's a static or nonstatic method, and pointers to these methods are laid out into a table.  Each object in the heap then stores a pointer to the vtable for its object type.  This means that the size of any heap object does not depend on the number of methods the object has.  In fact, an object with 100 methods would be the same size an object with 1 method (assuming they have the same fields).  Each just stores a pointer to the vtable for its object type, of which there's only one copy.
This optimization was originally used in C++ to support fast virtual functions and has since been used in many other object-oriented languages.  It allows objects to be small, yet support dynamic dispatch.
In other words, methods don't need to be static by default because they don't contribute to the size of the objects in the heap.  Creating an object doesn't take longer for objects with more functions, or does it use more heap space.
Here's one possible diagram for the layout of some objects (apologies for ASCII art!).  Suppose that we have two classes, A and B.  Then in memory, objects of those types might look like this:
   A                      vtable for A
 +-------------+        +---------------+
 | vtable ptr  | --+->  | method one    |
 +-------------+   |    +---------------+
 |             |   |    | method two    |
 | fields of A |   |    +---------------+
 |             |   |    |     ...       |
 +-------------+   |    +----------------
                   |    | method N      |
   A               |    +---------------+
 +-------------+   |
 | vtable ptr  |---+
 +-------------+
 |             |
 | fields of A |
 |             |
 +-------------+

   B                  vtable for B
 +-------------+     +------------+
 | vtable ptr  | --> | method one |
 +-------------+     +------------+
 |             |     | method two |
 | fields of B |     +------------+
 |             |     |    ...     |
 +-------------+     +------------+
                     | method M   |
                     +------------+

Notice how both objects of type A share the same vtable, and how objects of types A and B only use the same amount of space for their vtable pointer, even if they have different numbers of methods.
Answer: Because if every method was static java would not be object-oriented.
You need to invoke a method on different objects, because they have different state.
As for the memory - each static invocation also goes on the stack.
Answer: The code of the method is not on the stack, it is in a part of the heap (the permanent generation, special-cased by the garbage collector). On the stack only the local variables of the method (and similar runtime-data, like return address) are located.
This is independent of them being static or non-static methods.
Also, the code of the method will not be copied for each object of the class - just when executing the method, it gets an additional argument, which points to the object on which it is invoked. This single argument is the only memory overhead between static and nonstatic methods.


Como definir várias variáveis de uma vez dentro de uma trigger no SQLServer

Question: Olá, estou criando uma TRIGGER onde devo fazer uma série de tratamentos após um UPDATE em uma tabela no SQLServer. Nessa TRIGGER, eu preciso definir algumas variáveis para que eu possa trabalhar com elas no resto do script, assim:
CREATE TABLE foo (
    id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    nome NVARCHAR(100) NOT NULL,
    telefone NVARCHAR(30) NOT NULL DEFAULT '',
    email NVARCHAR(100) NOT NULL DEFAULT ''
);

GO

CREATE TRIGGER [TR_foo_onUpdate] ON foo AFTER UPDATE AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @id BIT = (SELECT id FROM inserted),
            @nome NVARCHAR(100) = (SELECT nome FROM inserted),
            @telefone NVARCHAR(30) = (SELECT telefone FROM inserted),
            @email NVARCHAR(100) = (SELECT email FROM inserted);

    /* continuação do script aqui... */

END

minha questão é o seguinte, existe alguma forma de eu fazer o declare sem ter que fazer 4 SELECT's? A pergunta é mais para otimização pois com certeza pode ser usada em inúmeros outros scripts...
Comment: Sugestão de leitura: "Armadilhas na programação de procedimentos de gatilho" ->
https://social.technet.microsoft.com/wiki/pt-br/contents/articles/38010.armadilhas-na-programacao-de-procedimentos-de-gatilho.aspx
Answer: DECLARE @id BIT,
        @nome NVARCHAR(100),
        @telefone NVARCHAR(30),
        @email NVARCHAR(100);

SELECT @id = id,
       @nome = nome,
       @telefone = telefone,
       @email = email
  FROM inserted

Comment: Lol... sinceramente não achei que era tão simples como isso...


How can I use Rive animations in a WPF / XAML project?

Question: I have a <code>*.rive</code> file and I want to use that in my WPF app like a loading spinner.
There is any way to use rive file in WPF using Image, Media Element etc.
Do I need to convert it as gif?
Comment: @Bizhan Right, that was my first thought when I was reading about Rive, and I wondered how Rive was so _big_ as a brand if it's just yet another vector animation software tool, then I read their technical docs and saw that their real-value is exposing structured animations to host programs - so you can _easily_ do [things like this](https://codepen.io/m3eu/pen/VwYBbwO) with far less handwork.
Comment: First-off, please tell us what, exactly, a `RIV` file is.. I can't find any mention or description of it in any of the major file-types databases. e.g. https://fileinfo.com/search
Comment: Rive is a real-time interactive design and animation tool by Rive Inc.. Use the Rive editor to create vector based motion graphics that respond to different states and user inputs. Rive lets you create advanced timeline animations through animation mixing, interpolation and inverse-kinematics. Transition between animations using state machines. When we export it as .riv it generate a file with this extension. For more...(https://defold.com/extension-rive/)
Comment: `rive` is not `riv`.
Comment: If it is vector-based you can use Paths and Shapes and storyboard animations to recreate it in WPF. I am not aware of a nuget-package or native support of this filetype.
Comment: @DenisSchaf It would be a _lot_ of work to recreate a Rive animation in WPF using WPF's own features. For example, Rive includes skeletal animations whereas WPF does not... and probably will never.
Comment: I would start by exporting as HTML5 and continue from there
Comment: @Bizhan How is that going to help?
Comment: @Dai I thought it was obvious since the animation in HTML5 and WPF-XAML have great similarities.
Comment: @Bizhan It's not that HTML5 and WPF's animation features are similar (they really aren't, IMO), but that _in this case_ it's very incompatible: Rive animations aren't exported as CSS `@keyframes` animations:  you still need their Web runtime library. Maybe if they had SVG export as an option (does it? I don't know) then you could run that through an SVG-to-XAML converter but you lose all the _structured_ control over the animation.
Comment: @Dai I don't know either. I never worked with Rive. But I automatically assumed a "vector-based animation software" must have a vector output! If what you're saying is true then I would contact rive for a feature request.
Answer: Short answer: You cannot

Rive is not just an animation tool, but an animation framework that requires a specially written runtime for different kinds of hosts.
Rive's documentation says they only have first-party support for:

The web (and a first-party React wrapper).
iOS, Android, Flutter, Tizen
React Native
"C++"

Note the lack of WPF, XAML, WinUI, UWP, Jupiter, Silverlight, WinForms, etc.

Microsoft's desktop developer story in 2021 sure is fun, isn't it?

MS hasn't had a clear and consistent desktop story since Windows 7, it's depressing, and still awful.

I note that "C++" isn't a platform, just a language, so it's odd that they describe it like that. Anyway, their C++ runtime ships with a renderer for Skia, which isn't of much use
Long answer: You can, if you want to put the effort in

Clone and build their C++ runtime.
Replace the Skia renderer with a new renderer of your own creation that renders to WPF somehow.

You can host Skia within WPF, but it's an opaque surface: the structure and contents of the Rive animation wouldn't be rendered directly by WPF which would introduce inefficiencies.
Also, I think WPF is still stuck on DirectX 9, and there might be functionality in Rive that would benefit from being on DX12.

And the rest is an exercise for the reader.
Answer: I haven't tested it but
here is a runtime for rive in C# + UWP
https://github.com/rive-app/rive-sharp
here is a way how to display UWP in WPF
In WPF control - display a UWP app


Lilypond: How to write - when the left hand should play more than the number of notes per bar as per the time signature

Question: This is what I am aiming for:

How can I tell LilyPond that the c1 in the first three measures is to be played by the thumb of the left hand in parallel with the other three notes also played by the left hand?
   r4 a4_3 a4 a4 |
   r4 g4_4 g4 g4 |
   r4 f4_5 f4 f4 |
   c'2_1 c,2

Where do I put in those c1 notes?
Answer: A polyphonic passage can be coded in a number of different ways (see the documentation here).
For this case, I'd suggest writing it like this:
<< {c1^1} \\ {r4 a4_3 a4 a4}>> |
<< {c1} \\ {r4 g4_4 g4 g4}>> |
<< {c1} \\ {r4 f,4_5 f4 f4}>> |
c'2 c,2

Comment: @saraf Using <> implicitely creates new voices for each bit and applies voiceOne, voiceTwo, ... to them. So << c1 \\ { r4 a a a } >> is equivalent to << \new Voice { \voiceOne c1 } \new Voice { \voiceTwo r4 a a a } >>. As this question is a bit basic I suggest you read this part of the documentation to get a principle understanding of how polyphony works in Lilypond: http://lilypond.org/doc/v2.23/Documentation/notation/multiple-voices
Comment: Yup! That did the trick :-) Tnx
Comment: as I understand it, the double backslashes make both voices temporary, rather than just the second voice.  But different versions handle them differently for some reason
Comment: Thanks a lot - this works fine! But there are a couple of warnings warning: maybe input should specify polyphonic voices
warning: cannot have note heads and rests together on a stem ... For the sake of completeness - could you also please give the other way of adding this polyphony?
Comment: @saraf — That's strange, I'm not getting any warning. What version of LilyPond are you using? And what does the rest of your code look like?
Comment: Put the entire file here - http://pastie.org/p/2ERJnssC75W93lHivhSa2t
Comment: Using LilyPond 2.22.1 on Windows 10
Comment: https://imgur.com/fHoTSnb
Comment: @saraf try adding \\ between the voices as my updated code shows
Comment: What do the double backslashes stand for? OK - got it - they create temporary voices


MongoDB Transactions - Converting circular structure to JSON error

Question: For implementing transactions in mongoose or mongodb, do we need replica set? I am trying to implement transaction in mongodb using the below code
    const session = await mongoose.startSession();
      await session.startTransaction();
      try {
        // Writing to Invalid DB
        if (invalidData && invalidData.length) {
          const transformedData = this.transform(invalidData);
          // console.log('transformedData---------->', transformedData);
          const invalidOutput = await InvalidDataModel.insertMany([transformedData], { session });
        await session.commitTransaction();
        session.endSession();
      } catch (error) {
        console.log({ err: error.errmsg, result: error.result.result.writeErrors });
        await session.abortTransaction();
        session.endSession();
        throw error;
      }

But I am getting the error
022-07-19T10:05:00.940Z - error: uncaughtException: Converting circular structure to JSON
    --> starting at object with constructor 'Server'
    |     property 's' -> object with constructor 'Object'
    |     property 'coreTopology' -> object with constructor 'Server'
    |     ...
    |     property 's' -> object with constructor 'Object'
    --- property 'topology' closes the circle date=Tue Jul 19 2022 15:35:00 GMT+0530 (India Standard Time), pid=50111, uid=503, gid=20,

Need help with the issue?
Answer: This was happening because there was a JSON.stringify(query) due to which this circular error was happening. Removed it. Use flatted library and the error is not coming.


How to convert (F⇒(H⇒G))⇒(F⇒(G⇒H)) to Conjunctive Normal Form?

Question: I've expanded the formula to:
$$(F \wedge H \wedge\neg G) \vee (\neg F \vee\neg G \vee H)$$
but don't know how to switch the first set to or and the middle or to an and.
Answer: Use the distributive law: $(A \wedge B) \vee C = (A \vee C) \wedge (A \vee C)$.
Answer: Indeed distributive law is one approach, another method is use Absorption law:
\begin{align}
&(F∧H∧¬G)∨(¬F∨¬G∨H)\\
\equiv&(((F∧¬G)∧H)∨H)∨(¬F∨¬G)\tag*{Reordering}\\
\equiv&H∨(¬F∨¬G)\tag*{Absorption law}\\
\end{align}
Answer: \begin{align}
&\phantom{\equiv}(F\implies(H\implies G))\implies(F\implies(G\implies H))\\
&\equiv\neg(\neg F\lor(\neg H\lor G))\lor(\neg F\lor(\neg G\lor H))\\
&\equiv\neg(\neg F\lor \neg H\lor G)\lor(\neg F\lor \neg G\lor H)\\
&\equiv(F\land H\land \neg G)\lor(\neg F\lor \neg G\lor H)\\
&\equiv(F\lor (\neg F\lor \neg G\lor H))\land
(H\lor (\neg F\lor \neg G\lor H))\land
(\neg G\lor (\neg F\lor \neg G\lor H))\\
&\equiv(F\lor \neg F\lor \neg G\lor H)\land
(H\lor \neg F\lor \neg G\lor H)\land
(\neg G\lor \neg F\lor \neg G\lor H)\\
&\equiv 1\land
(\neg F\lor \neg G\lor H)\land
(\neg F\lor \neg G\lor H)\\
&\equiv\neg F\lor \neg G\lor H
\end{align}


How do I manage xen-hypervisor using virt-manager client?

Question: I've installed xen-hypervisor 4.11 on my debian 10 desktop. But, when I add xen connection to my virt-manager it shows this error.
<code>Unable to connect to libvirt xen:///.

Failed to connect socket to '/var/run/libvirt/libvirt-sock': Connection refused

Verify that:
 - A Xen host kernel was booted
 - The Xen service has been started

Libvirt URI is: xen:///

Traceback (most recent call last):
  File "/usr/share/virt-manager/virtManager/connection.py", line 1012, in _do_open
    self._backend.open(connectauth.creds_dialog, self)
  File "/usr/share/virt-manager/virtinst/connection.py", line 138, in open
    open_flags)
  File "/usr/lib/python3/dist-packages/libvirt.py", line 104, in openAuth
    if ret is None:raise libvirtError('virConnectOpenAuth() failed')
libvirt.libvirtError: Failed to connect socket to '/var/run/libvirt/libvirt-sock': Connection refused
</code>
Do I need a IOMMU compatible motherboard to use Xen-hypervisor? or something else?
Answer:
Install libvirt-daemon-driver-xen
Restart libvirtd service


Problem with "content access" (module) and permission "View own unpublished content"

Question: I have a problem since few days and i didn't find my answers.
When i install content access, the permission View own unpublished content doesn't work anymore.
Some explanation about my configuration:
I use workbench and workbench moderation to create a simple workflow (i didn't change any setting: so draft, in review, published)
I have 2 roles who manage all the content (editor, manager and another role admnistrator who has all the bypass etc.)
And now, i've juste discovered that i have a problem when i need to see nodes that are not published. Editor and Manager can't see them event if they have created this content.
They can't see unpublished content everywhere in the site (in workbench administration and in content section so it's not a views problem)
I made another installation in local to make some test. I re-created my role with a basic configuration (permissions):

Access administration menu
Access the content overview page
View own unpublished content
View the administration theme

So when my manager creates a content type and it's unpublished it works fine. But when i install content access, it doesn't work anymore.
I don't know what's going wrong in my site but the only way for the user to see unpublished content is to have that permission : Bypass content access control
Problem, if i give them that permission, an editor can published content. It's override the workbench permission (he can just use draft and in review, only manager can published)
The only setting for content access i saw are in the content type section.

I think i made a stupid mistake, forget a setting but i didn't see where.
Thxs for your help :)
Answer: I've just found some interesting information about my problem. Maybe it will help someone else.
In fact, it's seems impossible to resolve this problem in a proper way.
There is a very good article about that: Access Control module prevents View of user's own unpublished content, and an issue on drupal.org
If we want to see our own unpublished content in workbench, we have to go in view and make:

Go to query settings
and check Disable SQL rewriting option

It's not very good solution like he said but we can't do anything else for now.
Comment: Its working thanks ... hope we will find a better solution in future. Actually its not problem with only content access module even with-out installing it you will find same problem if your content access permission has been rebuilt by other modules like og-content-access, workflow, etc. I don't know where is the problem but after rebuilding (overriding) content access permission views became unable to show unpublished contents to no-administrative user roles.
Answer: I actually have an answer for you!
I had run in to this issue on a site and was about to just give everyone bypass access permissions, when it clicked that the only reason users can't see the unpublished items is because the view that's driving the default Content admin page doesn't know about Workbench Moderation's states.
The solution therefore is to override the default Content page, and the easiest and most effective way to do that is to install Administration Views.
Administration views replaces the default content view and ootb this view supports the permissions workbench moderation provides. Your problem is now fixed!
Note that Administration Views requires Views, Views Bulk Operations, Chaos Tools and Entity API, but if your site doesn't have most of those already you're probably doing Drupal wrong!
If you don't want to allow any of the VBO functions (because they tend not to play nice with Workbench Moderation in my experience) you can just hide that field in the view, or disable all the actions you don't want people to use.


Does the server hostname need to match the domain name of the email address you are sending from?  Does the hostname need to be verifiable with DNS?

Question: I am trying to diagnose why email won't send from a new RHEL v5.8 server.  Sendmail is up and running, but everything is stuck in the queue (confirmed with mailq) with connection timed out errors.
If I have the hostname of the server to:
natulwebserver01.bto.com

But try to send emails with PHP and set the 'from' email address to:
firstname.lastname@example.com

...this would cause the destination mail servers to block the emails right?
If so, does that mean the email address I set as a 'from' address in the PHP mail() function would have to match the server hostname exactly?  For example:
email@example.com

I have tried that and it doesn't work, but I want to ask just to confirm in theory.
Also - and maybe this is the real cause - does the hostname need to resolve to the IP address of the server in the destination mailserver's DNS before it will accept emails from it?
For example:
natulwebserver01.bto.com

...is an internally meaningful hostname, but it is not a publicly registered domain name. i.e. if you ping natulwebserver01.bto.com it will not return the IP address of the server.
Does it make sense that the destination mailservers would block email from my server as it is reporting a hostname that cannot be verified with DNS?
*I have modified the actual hostnames/domains involved for the purposes of this question.
Answer: The domain in the 'From' address need not be the same as the hostname of the smtp server, but the hostname should be publicly registered and match reverse DNS of the IP on which sendmail is running.
Comment: Thank you Tatul.  Is it the full subdomain that needs to be registered, like 'natulwebserver01.bto.com', or just 'bto.com' would be enough for the validation?
Comment: You'll want to add an MX record for the subdomain, I believe.
Comment: Ok I tried it and it worked without the full 'natulwebserver01.bto.com' hostname needing to be registered - just the 'bto.com' was enough.


Is random splitting of a time series suitable for neural networks training when temporal aspects are important?

Question: Is random splitting of a time series, e.g., into 80/10/10,  suitable for neural networks (NARX) training when temporal aspects are important?
To the best of my knowledge ANNs can generalize that means that after learning data from a sample, ANNs can correctly infer the unseen part of a population. But, on the other hand, "a variation caused by different resamplings is higher than a variation caused by network conditions."
Answer: Roberts, David R., et al. "Cross‐validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure." Ecography 40.8 (2017): 913-929.

Ecological data often show temporal, spatial, hierarchical (random effects), or phylogenetic structure. Modern statistical approaches are increasingly accounting for such dependencies. However, when performing cross‐validation, these structures are regularly ignored, resulting in serious underestimation of predictive error. One cause for the poor performance of uncorrected (random) cross‐validation, noted often by modellers, are dependence structures in the data that persist as dependence structures in model residuals, violating the assumption of independence. Even more concerning, because often overlooked, is that structured data also provides ample opportunity for overfitting with non‐causal predictors. This problem can persist even if remedies such as autoregressive models, generalized least squares, or mixed models are used. Block cross‐validation, where data are split strategically rather than randomly, can address these issues. However, the blocking strategy must be carefully considered. Blocking in space, time, random effects or phylogenetic distance, while accounting for dependencies in the data, may also unwittingly induce extrapolations by restricting the ranges or combinations of predictor variables available for model training, thus overestimating interpolation errors. On the other hand, deliberate blocking in predictor space may also improve error estimates when extrapolation is the modelling goal. Here, we review the ecological literature on non‐random and blocked cross‐validation approaches. We also provide a series of simulations and case studies, in which we show that, for all instances tested, block cross‐validation is nearly universally more appropriate than random cross‐validation if the goal is predicting to new data or predictor space, or for selecting causal predictors. We recommend that block cross‐validation be used wherever dependence structures exist in a dataset, even if no correlation structure is visible in the fitted model residuals, or if the fitted models account for such correlations.


Entering folder based on name in python

Question: In my code, I'm able to search through a directory for a file with a specific name.  How could I edit the code so that it first searches for folders with names ending with the word "output".  In the below code, when I tried to include the commented out line, the whole thing refused to run.  Any help on what I'm missing would be greatly appreciated
def test():
    file_paths = []
    filenames = []
    for root, dirs, files in os.walk('/Users/Bashe/Desktop/121210 p2/'):
        for file in files:
                #if re.match("output", file):
                    if re.match("Results",file):
                        file_paths.append(root)
                        filenames.append(file)
    return file_paths, filenames

Comment: Try to use `os.path.dirname(file).endswith('output')`.
Comment: @1st1: your expression is always false. `file` is relative to `root`.
Answer: To search files that are in a folder with name ending with the word "output":
for dirpath, dirs, files in os.walk(rootdir):
    if not dirpath.endswith('output'):
       continue # look in the next folder
    # search files
    for file in files: ...

If you don't want even to visit any directories that are not ending with "output":
if not rootdir.endswith('output'):
    return # do not visit it at all
for dirpath, dirs, files in os.walk(rootdir):
    assert dirpath.endswith('output')
    dirs[:] = [d for d in dirs if d.endswith('output')] # edit inplace
    # search files
    for file in files: ...

Entering folder based on name in python


if each figure is visible within a scrollabe div

Question: I have a list of items within a scrollable (jQuery tools)...
It's shows 3 items/figures at a time, when clicking the next button, it's shows the 3 next...
The thing im trying to do, is that i want do for example call a webservice, when the items that are showed within the scrollable area, the items that arent showed in the scrollable area, should do nothing - Only when clicking the next button, and the 3 next items are showed...
My HTML output looks like this:

        next
        prev

                        Skarp

og lige til

                    <input type="hidden" name="ctl10$phadlist_0$hiddenFieldAdGuid" id="ctl10_phadlist_0_hiddenFieldAdGuid" value="B2A276D78E764528900B723F144117A7" />

                        Forbrugsforeningen 2

har det hele

                    <input type="hidden" name="ctl10$phadlist_1$hiddenFieldAdGuid" id="ctl10_phadlist_1_hiddenFieldAdGuid" value="75011C876D04465D865B34FA6DC2CBE3" />

                        Skarp

og lige til

                    <input type="hidden" name="ctl10$phadlist_2$hiddenFieldAdGuid" id="ctl10_phadlist_2_hiddenFieldAdGuid" value="B2A276D78E764528900B723F144117A7" />

                    <input type="hidden" name="ctl10$phadlist_3$hiddenFieldAdGuid" id="ctl10_phadlist_3_hiddenFieldAdGuid" value="BE7DA9601D4840B981A1E5305E01786F" />

                        Forbrugsforeningen 2

har det hele

                    <input type="hidden" name="ctl10$phadlist_4$hiddenFieldAdGuid" id="ctl10_phadlist_4_hiddenFieldAdGuid" value="75011C876D04465D865B34FA6DC2CBE3" />

                    <input type="hidden" name="ctl10$phadlist_5$hiddenFieldAdGuid" id="ctl10_phadlist_5_hiddenFieldAdGuid" value="BE7DA9601D4840B981A1E5305E01786F" />

I've tried this:
 $("#belt figure").each(function () {

    if ($(this).filter(':visible')) {
        alert("visible");
        //Do something, like calling a webservice
    } else {
        alert("not visible");
        //Dont call webservice
    }

});

I've tried looking at the jquery.appear plugin, but it doesnt seem to support the thing i want?
Comment: One thing I've noticed in your HTML is that all the `` elements are visible. In other words, none of them have `style=display:none`, or whatever, in order to hide them. Could be a red-herring, but I thought I'd point that out.
Comment: Yeah, i know, and that is the problem, that's why I cant do it with :visible - So I need somekind of method that can check if the figure elements are visible within a specific viewport of a div - Ex: #belt is 980px wide
Answer: You could probably just loop through only visible figures if that's the only ones you are interested in
$("#belt figure:visible").each({...});

Or if you're looking to do something with each figure based on their visibility, I think you're looking for the is() method:
if ($(this).is(":visible")) {
    //Do something
} else {
    //Do something else
}

edit: I now see that you're trying something else. If you want to see if it's visible within an area, you need to do something else. :visible will be true if the element isn't display:none or visibility:hidden.
So you need to check the height of the scrollable area and the scrollTop, then check the offset of each figure against those numbers to see if it's visible
edit2: Is it something like this you had in mind?
Comment: The problem is that all figures are visible, none of them have the display:none - So I cant use :visible  :(
Comment: @NickyChristensen Added a working example to my answer, that I think might be something along the lines of what you're looking for.
Comment: Yeah, it's exactly like that, however, I just need it in a horisontal state, instead of vertical...
Comment: @NickyChristensen Then just switch `offset().top` with `offset().left` and `scrollTop` with `scrollLeft` (:


Integral closure of $k[x^3,x^2y,y^3]$ in field of fractions

Question:
Let $A = k[x^3,x^2y,y^3] \subset k [x,y] $. I want to find the integral closure of $A$ in its field of fractions. To do so, I first want to find the field of fractions $\mathrm{Frac}(A)$.

I think that $\mathrm{Frac}(A) \neq k(x,y)$, since if we want to check if $x \in \mathrm{Frac}(A)$ we would have
$x = \frac {x^{\alpha}y^{\beta}} {x^{\alpha-1}y^{\beta}} $ with $x^{\alpha}y^{\beta} = (x^3)^{a_1}(x^2y)^{a_2}(y^3)^{a_3}$, therefore: $\alpha = 3a_1 + 2a_2$ and $\beta = a_2 + 3a_3$.
On the other hand, I have $x^{\alpha-1}y^{\beta} = (x^3)^{b_1}(x^2y)^{b_2}(y^3)^{b_3}$
therefore: $\alpha-1 = 3b_1 + 2b_2$ and $\beta = b_2 + 3b_3$.
This system has no integer solutions, therefore $x \notin \mathrm{Frac}(A) $.
Now continuing with this method doesn't seem to be very effective. How can I compute $\mathrm{Frac}(A)$ more efficiently?
Comment: I think the field of fractions should be $k(\frac{x}{y}, x^3)$.
Answer: I do not know any general algorithm to compute the fraction field of an integral domain effectively in the sense of providing a minimal set of generators over a given domain. So usually one proceeds by determining 'small' candidates and by carefully extending them if necessary.
Let $K$ the the field of fractions of the given ring. Then it is clear that $\frac{x^2y}{x^3}=\frac{y}{x}\in K$. Hence $k(\frac{y}{x})\subseteq K$. Now $y^3\not\in k(\frac{y}{x})$, therefore we are forced to consider $k(\frac{y}{x},y^3)\subseteq K$. Now $x^3=y^3(\frac{x}{y})^3\in k(\frac{y}{x},y^3)$ and $x^2y=(\frac{x}{y})^2y^3\in k(\frac{y}{x},y^3)$. Hence $K=k(x^3,x^2y,y^3)=k(\frac{y}{x},y^3)$.
Comment: So, even if this is not a general algorithm, all that's needed is to make this verification over the 'added' elements of the starter extension?


Number Theory:Quadratic Reciprocity Part II

Question: Claim: If $p \equiv 2 \mod 5$ then $5$ is a non-residue modulo $p$.
Attempt: I know that similarly to proving Quadratic Reciprocity Part II, we need to reduce the numbers $5,10,15,\cdots,\frac{5}{2}(p−1)$ so that they lie between $-\frac{1}{2}(p-1)$ and $\frac{1}{2}(p-1)$ and see how many of them are negative but I don't know how that proves the claim.
Comment: I like this direct approach, which doesn't rely on Quadratic Reciprocity. Note that you get positives for a while, then negatives, then positives, then negatives, then positives. Find the break points in terms of p and count the elements in each part. Fun counting exercise (and not too hard -- you just need to be careful).
Answer: You are looking for $\left( \dfrac{5}{p} \right)$, but we understand only $\left( \dfrac{p}{5}\right)$. In particular, the squares mod $5$ are $1$ and $4$, so $\left( \dfrac{p}{5} \right) = -1$ and $p$ is not a square mod $5$. How do we relate this to $\left( \dfrac{5}{p} \right)$?
We use what you mentioned: the law of quadratic reciprocity! Since $5 \equiv 1 \pmod 4$, we know that $\left( \dfrac{5}{p} \right)=\left( \dfrac{p}{5} \right)$, and so $5$ is not a square mod $p$. $\diamondsuit$


Checksum mismatch on update: SVN v1.8.10

Question: I am getting this error while running svn up command: svn: E200014: Checksum mismatch.
I tried the solution here: SVN - Checksum mismatch while updating
 (which involves running command svn update --set-depth empty and svn update --set-depth infinity in the directory with problematic file) but this doesn't work and I am still getting the same error.
Is there any other solution apart from checking out the whole repository again and copying back the changes?
Thanks in advance.
Answer: Checkout a new working copy -- that one seems to be broken.
Note that SVN 1.8.10 is outdated. The latest version is 1.9.6, the latest maintenance update in 1.8.x release is 1.8.16.


How to post correctly fields in views-view-fields.tpl.php?

Question: I'm using Drupal 7, and Views 3.
I would like to reproduce my comment template in views-view-fields.tpl.php.
Thus I need to print my fields to be able to arrange them as I wish it.
For each field, I proceed like that : <?php print $view->render_field('field_name', $id);?>, is it the correct/secure way ?
I don't think so, because all the row does not display.
Answer: The correct way is:
<?php print $fields["field_name"]->content; ?>

Note: Using views-view-fields.tpl.php will affect all of your views, which you may not want.
To target a specific view you need to use:
views-view-fields--[view-name]--[machine-name].tpl.php
Comment: It works, but I have now for every field an error of type: `Notice : Trying to get property of non-object dans include()` and `Notice : Undefined index: namefield dans include()` Do you know where from it can come?
Comment: Did you name your template like this `views-view-fields--[view-name]--[machine-name].tpl.php` ?
Comment: Yes. I think that this problem appears when I disconnect. Fields indeed appear only when the users are connected. I would have to include in the views template a condition of type "if" i think
Comment: But I do not know the syntax. I try this `content;): ?>` but it does not work
Comment: Are you trying to check if it exists? You don't need the `;` inside the bracket, if it still does not work after deleting the `;` try `content)): ?>` something goes here ``


Selecting a car, then selecting tires based on which tires the car can have

Question: Sorry, I can't express my problem without having to abstract it into something simple, I hope gets my point across. It has also been pretty much impossible to search Google etc., for this particular issue as I can't properly formulate it.
Imagine a content type called "Order".
You go to create a new Order. Where you can choose a car, and tires for THAT car.
The only tires you can choose, have been defined on the car itself, when it was created.
So if you choose a tiny car, the tractor wheels are not shown as a choice of tires. Because on that tiny car, the tractor wheels haven't been selected.
On the car node, there's a field_usable_tires, where you can select the different tires that car can use.
My problem is how to make the "tires" selection on the create Order form change, dependent on the tires the car can have, when a car is selected.
Really hope someone out there understands my issues and can help! :)
/Dan
Answer: Is tires a dropdown list on the order content type?
If so, I think you might just need to manipulate the states, https://api.drupal.org/api/examples/form_example%21form_example_states.inc/function/form_example_states_form/7.x-1.x
I haven't used this module in a long time, but it might work for you, https://www.drupal.org/project/conditional_fields
Answer: In similar situation, what I did, was to create an ajax callback on the field.
I'm working on D8.
<code>$form['field_name']['widget']['#ajax'] = array(
    'callback' => 'my_callback',
    'wrapper' => 'edit-field-organisation',
    'event' => 'change',
    'method' => 'replace',
    'effect' => 'fade',
  );
</code>
And in the callback I fetch the related content based on user selection.
In my case I had to do with taxonomy terms. And replace the values in my second selectbox.
<code>function my_callback($form, $form_state) {
  //Here get the selected value
  $organisation_id = $form_state->getValue('field_organisation')[0]['target_id'];

  $option = '<option value="_none">- Select a value -</option>';
  if(!is_null($organisation_id)){
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($organisation_id);
    $sector_list = $term->get('field_sector')->getValue('list');

    foreach ($sector_list as $key=>$item){
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($item['target_id']);
      $option .= "<option value='" . $item['target_id'] . "'>" . $term->getName() . "</option>";
    }
  }
  $response = new AjaxResponse();

  $output = '<select data-drupal-selector="edit-field-sector" id="edit-field-sector" name="field_sector" class="form-select required" required="required" aria-required="true">' . $option . '</select>';
  $response->addCommand(new ReplaceCommand('#edit-field-sector', $output));

  return $response;

}
</code>
Maybe there is a better way to fetch the terms but this works.
Answer: Create two vocabulary 1> Car 2> Tires . Now add term relation in tires vocabulary and select car vocabulary.
Now when you create a order . onchange of car select call a AJAX behalf selected car tid get you tries related to you car and replace tries field option by that option .
Thanks


Is there any way to get the image of the first page of pdf file in c#?

Question: Am looking for a way to get image of the first page in pdf file using c#
Any solution ??
Comment: I find an article in codeproject.com but seems complicated ..I need some library that do this easily
Answer: iTextSharp should handle that.  Exit on the first image
example here http://www.vbforums.com/showthread.php?t=530736
Edit:
Copied code from the thread by stanav
<code>Public Shared Function ExtractImages(ByVal sourcePdf As String) As List(Of Image)
    Dim imgList As New List(Of Image)

    Dim raf As iTextSharp.text.pdf.RandomAccessFileOrArray = Nothing
    Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
    Dim pdfObj As iTextSharp.text.pdf.PdfObject = Nothing
    Dim pdfStrem As iTextSharp.text.pdf.PdfStream = Nothing

    Try
        raf = New iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf)
        reader = New iTextSharp.text.pdf.PdfReader(raf, Nothing)

        For i As Integer = 0 To reader.XrefSize - 1
            pdfObj = reader.GetPdfObject(i)
            If Not IsNothing(pdfObj) AndAlso pdfObj.IsStream() Then
                pdfStrem = DirectCast(pdfObj, iTextSharp.text.pdf.PdfStream)
                Dim subtype As iTextSharp.text.pdf.PdfObject = pdfStrem.Get(iTextSharp.text.pdf.PdfName.SUBTYPE)
                If Not IsNothing(subtype) AndAlso subtype.ToString = iTextSharp.text.pdf.PdfName.IMAGE.ToString Then
                    Dim bytes() As Byte = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw(CType(pdfStrem, iTextSharp.text.pdf.PRStream))
                    If Not IsNothing(bytes) Then
                        Try
                            Using memStream As New System.IO.MemoryStream(bytes)
                                memStream.Position = 0
                                Dim img As Image = Image.FromStream(memStream)
                                imgList.Add(img)
                            End Using
                        Catch ex As Exception
                            'Most likely the image is in an unsupported format
                            'Do nothing
                            'You can add your own code to handle this exception if you want to
                        End Try
                    End If
                End If
            End If
        Next
        reader.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    Return imgList
End Function
</code>
Comment: Be careful when you redirecting to other web pages.(specially threads) since they might be get delete at sometime and your answer will be pointless. you can put some code in answer and put the link as a reference :)
Comment: what is i means "For i As Integer = 0 To reader.XrefSize - 1"
Answer: You are probably trying to rasterize the pages of the PDF. If look for get image etc you will turn up other operations that you could perform on a PDF. There are a list of ways already posted. I've used ABCpdf to do this very easily.
Answer: Are you in a web, or native environment? It makes a huge difference. What you want to is rasterize the PDF into an image. This is easy enough to do in a native environment via GhostDoc or a similar tool. They all use a virtual printer driver to rasterize the PDF. This approach won't work in a web-environment where you will probably need to use something commercial as writing your own rasterizing engine is a massive undertaking.
Comment: I Mean getting image dynamically in runtime of c# program or web in asp.net


NullPointerException when calling an operator

Question: I have a Fraction object that I defined in a java class. I need to be able to do math with fractions that I create. When I do math with an undefined fraction, I am required to return null. My problem is when the user doesn't know that null was returned and tries to do math with a Fraction object that is set to null.
For example.
Fraction f1=null;
Fraction f2=new Fraction(1, 2);
Fraction f3=f1.add(f2);

This will give me an error. But when I do it the other way around, there is no error.
Fraction f1=null;
Fraction f2=new Fraction(1, 2);
Fraction f3=f2.add(f1);

This wont error and will instead return null.
Why does the top example error and how do I force it to instead return null? Also, the checking if the fraction is null can not happen in my tester program, it has to happen in the Fraction class.
The add operator works just fine. I just want it to return null when the Fractions object equals null.
Comment: the top example fails because `f1` is null and you can't call a function on null. What you can do is replace your function by a static function that tests both operands
Comment: That's not gonna happen.
Comment: You can't. Calling a method on a null reference is a bug, and will always lead to a NPE.
Comment: You want the fraction f3 to return null in second example?
Comment: @Scitech The second example already returns null. Which is correct. I want the the first example to return null.
Comment: Ok, use a static method. This eliminates the object creation.
Answer: What you are trying to do is not possible because you cannot call a method on a null object. Trying it will always yield and exception. However, if this is really important for you, you could change the API to a static method with two parameters:
public static Fraction add(Fraction f1, Fraction f2)

Now you can return null in case one of the parameters is null.
Answer: Calling a method on a null object, will always end with a NullPointerException.


What contributes to an artist's melodic "signature?"

Question: Studying the vocal melodies in recorded pop music, from a theoretical perspective, I have the impression that there are certain musical characteristics that make up the melodic"fingerprint" of an artist, genre, or time period -- such that it's possible to tell, independent of the arrangement/performer, the artist/genre/period that gave rise to a particular melody.
Can anyone offer suggestions about how to conduct this kind of analysis? Which melodic features are worth focusing on? Is there any systematic research that's been done on this already, as it relates specifically to pop vocal melodies?
As an example of the kind of thing I mean: Ben Folds often ends phrases by falling from scale degree 5 to 3, then back up to 6. I'm looking for other examples of such signatures, and for general methods of discovering them.
Comment: Do pop vocal melodies have signature style, other than degree-of-melisma?
Comment: please note that my last comment was made with tongue-in-cheek ;) Yet degree-of-melisma may distinguish among your examples. Hmmm....
Comment: Have a look at [hook theory](http://www.hooktheory.com). More focused on chord progressions, but might be useful.
Comment: Sometimes, I'm not sure whether tendencies to use certain melodic fragments count as musical signatures. I've found the note-minor 2nd up-minor 3rd down motif in video game music from 4 video game series (and more composers) so far, and at this point, I'm prone to plain calling that motif overused.
Answer: I would say you're on the right track. You've already noticed a pattern of jumping from the 5th to the 3rd to the 6th. That's a pattern of two intervals - a minor third down and then a major 4th up. If I were looking for melodic signatures I would look at intervals and the rhythms they're played or sung in. What are the relative lengths of the 5th, 3rd and 6th? Does Ben Folds repeat the rhythmic relationship of those notes? Rhythm and pitch are the two main components of a melody.
A pattern might also have a typical location where it shows up. James Taylor has a pattern in the second bar of a four bar phrase, where the 2nd note of the tonic scale is sounding on the first beat and by the 4th beat he's moved by a major second interval to the 3rd. The rhythm in between varies somewhat.
Pick another composer, style or period and listen until you hear a repeated pattern and then study it in the same way.
Next, you might work outside the linear realm of melody and start including the harmonic dimension. I can often tell Beethoven or Brahms after just a few bars based on their characteristic harmonies (I realize that's not pop).
One way of thinking about harmony is by looking at the chord progressions. Patterns occur in chord progressions just like they do with intervals. Certain chord progressions might also be used repeatedly with the same rhythms or in the same parts of pieces.
Finally, what instruments are favored in different ways? You might find that some instruments are typically given one pattern to play and other instruments another pattern. Or maybe the pattern is repeated by different instruments. Either situation could be part of the musical signature. Instruments can take roles, too. Does one instrument play the melody more often than any other? Which instruments typically back or embellish the vocals? Music from the same periods and genres often share the same instrumentation.


Check if textarea is empty always return false

Question: I've created below form with 1 input and 1 textarea. however it seem like the textarea never is empty even though i haven wrote anything in it when i press submit button. What can trigger this??
form
<form method="post" action="index.php">

          <input type="text" name="username" id="title" value="" placeholder="title" required="required">
          <textarea name="textarea" id="description" placeholder="Beskrivelse" required title="3 characters minimum"></textarea>

         <input type="submit"name="commit" value="Tilføj" onclick="saveMarker(document.getElementById('title'), document.getElementById('description'));">
          <input TYPE="button" name="commit" value="Fortryd" onclick="div_hide();">

</form>

Function
function validate() {

  if ($('#description').val() == "" && $('#title').val() == "") {
    return false;
  } else {
    return true;
  }

}

Comment: How is `validate()` called?
Comment: I'm not sure what exactly the problem is. Your code works just fine. The `validate()` function return `FALSE` if both are empty and `TRUE` if any of them isn't.
Comment: its called `if (validate() == true) {`
Comment: I tested this as well and it works fine for me.  If both are empty false is returned.  If either one or both have content true is returned.
Comment: strange when i try it returns the length of the description is 0 but still return true. it only return false if title is empty
Answer: Give this a shot =)
if(document.getElementById("description").value == '') {

}

Comment: Why would this be any different?
Comment: it's vanilla bruh...  no need for a library for users that don't like using them... Like me.
Answer: you can try with this
$.trim( $('#description').val() ).length > 0

Answer: Try uing   $('#description').text();
if ($('#description').text() == "" && $('#title').val() == "") {

Comment: `$('#description').text()` and `$('#description').val()` should always be identical.


How may versions does HBase MapReduce reads when MapReduce is run on a table ?

Question: suppose you have an HBase table that support versioning when a map reduce is run over this table how many version are read in Map phase, by default and how to change this behavior ?
Answer:
Default versions gets created when you hit create 'test', 'cf' is 3
But when you scan in hbase shell
scan 'test' =>returns only latest versions.
scan 'test', {VERSIONS => 3} =>returns 3 versions if it's available.
In Java default scan always return latest but you can force to get
  previous
  versions by having this line

scan.setMaxVersions(int maxVersions);


How to unit test a filter using cache2k

Question: i am having a servlet filter which uses cache,the code basically goes like this
public class CustomFilter implements Filter {
    private  final Cache<String, ClientRequest> cache;
    @Autowired
    public CustomFilter(Service service){
    cache = Caching.getCachingProvider().getCacheManager()
            .createCache("requestsCache",
            ExtendedMutableConfiguration.of(
                    Cache2kBuilder.of(String.class,
            ClientRequest.class).entryCapacity(100)
            .expireAfterWrite(1000, TimeUnit.SECONDS)));
    }
}

Any thoughts about how can i unit test methods in this filter which use this class ? thanks in advance,
Answer: Extract Cache<String, ClientRequest> creation to external configuration and inject it through filter constructor:
public class CustomFilter implements Filter {
  private final Cache<String, ClientRequest> cache;

  public CustomFilter(Cache<String, ClientRequest> cache) {
    this.cache = Objects.requireNonNull(cache);
  }

That way you can mock the cache in your unit tests. This will allow to test CustomFilter business logic in isolation, without having to deal with complexity of the cache.
After that you might need a separate test for your cache configuration e.g. by using a property to define expiry timeout.
Comment: thanks, this should work, but while i integrate the controller using mockMvc, can we force the filter to use this ? why i am asking is, for uni testing i can add a mock cache, but integration test use mockMvc with just the path.. i can ask this as a seperate question too.
Comment: If you are using Spring Boot you can create `@WebMvcTes` with `@MockBean @Primary Cache mockCache;` and it should work. Standard auto-wireing rules apply.
Comment: but i am not using spring boot's cache, using cache2k, will that work ?
Comment: It's standard bean `@Autowire` order and overrides logic, which cache you are using it makes no difference as it's based on names and types.

How to unit test a filter using cache2k


Lilypond: How to create an ossia Staff above a PianoStaff?

Question: When trying to create an ossia Staff, that is used multiple times, above a PianoStaff, Lilypond does not reuse the context, but creates a new one. How can I tell Lilypond to find the existing context outside the PianoStaff?
\version "2.20.0"
<<
  \new Staff = "ossia" \with {
    \remove "Time_signature_engraver"
    \remove "Clef_engraver"
    fontSize = #-3
    \override StaffSymbol.staff-space = #(magstep -3)
    \override StaffSymbol.thickness = #(magstep -3)
    %alignAboveContext = "left"
  }
  { \stopStaff s1*5 }

  %\new PianoStaff = "piano" \with { instrumentName = "Piano" } % <<< if I add this, it does not find the context anymore
  <<
    \new Staff = "right" \relative {
      c'4 b c2
      <<
        { e4 f }
        \context Staff = "ossia" {
          \startStaff e4 e8 f \stopStaff
        }
      >> e2
      g4 a g2
      <<
        { g4 a }
        \context Staff = "ossia" {
          %\change Staff = "ossia"
          \startStaff g4 e8 f \stopStaff
          %\change Staff = "right"
        }
      >> g2
      e4 d c2
  }
  \new Staff = "left" \relative { \clef F c1 c c c c }
  >>
>>

Without PianoStaff:

With PianoStaff:

Note: I also tried to add the ossia Staff inside the PianoStaff: that works for the ossia staff, but it centers the name of the instument wrongly:
Comment: You should probably stick with the last one and mess with `\override Staff.InstrumentName.extra-offset = ...`, or whatever property will give you the spacing you want.
Answer: Does this work for you?
\version "2.20.0"

\new PianoStaff = "piano" \with {
  \override InstrumentName.extra-offset = #'(0 . -4)
  instrumentName = "Piano"
} <<
  \new Staff = "ossia" \with {
    \remove "Time_signature_engraver"
    \remove "Clef_engraver"
    fontSize = #-3
    \override StaffSymbol.staff-space = #(magstep -3)
    \override StaffSymbol.thickness = #(magstep -3)
    %alignAboveContext = "left"
  }
  { \stopStaff s1*5 }

  <<
    \new Staff = "right" \relative {
      c'4 b c2
      <<
    { e4 f }
    \context Staff = "ossia" {
      \startStaff e4 e8 f \stopStaff
    }
      >> e2
      g4 a g2
      <<
    { g4 a }
    \context Staff = "ossia" {
      %\change Staff = "ossia"
      \startStaff g4 e8 f \stopStaff
      %\change Staff = "right"
    }
      >> g2
      e4 d c2
    }
    \new Staff = "left" \relative { \clef F c1 c c c c }
  >>
>>

Answer: since I use ossia in piano scores for left and right hand, the only solution I found works with markup only
\version "2.20.0"

\include "english.ly"

#(set-default-paper-size "a4")
#(set-global-staff-size 14)

staffUpper = {\change Staff = RightHand}
staffLower = {\change Staff = LeftHand}

global = { %\easyHeadsOn
  \key c \major
  \numericTimeSignature
  \time 4/4
}

RHI = \relative c' {
  \voiceOne
  \global

  c4 d e f
  c4 d^\markup{\hspace #-12
             \score {
    \new Staff \with {
      \remove "Time_signature_engraver"
      \magnifyStaff #2/3
      firstClef = ##f
    }
    {\clef bass \relative c {\partial 1 c4 d f e f }}
  }}
   e f
  c4 d e f

}

RHII = \relative c' {
  \voiceTwo
  \global
}

LHI = \relative c, {
  \voiceThree
  \global

c4 d e f
  b,4 d4 e_\markup{\hspace #-12
             \score {
    \new Staff \with {
      \remove "Time_signature_engraver"
      \magnifyStaff #2/3
      firstClef = ##f
    }
    {\clef bass \relative c {\partial 2 c4 d f e f }}
  }}

     f
  c4 d e f

}

LHII = \relative c' {
  \voiceFour
  \global
}

Dynamics = {
}

\score
{
  \new PianoStaff \with {
  }
  <<
    \new Staff="RightHand"{ \clef treble
    <<
      \new Voice = "RFirst"
      \relative c'
      \RHI
      \new Voice= "RSecond"
      \RHII
    >>}

    \new Staff="LeftHand" { \clef bass
    <<
      \new Voice = "LFirst"
      \relative c'
      \LHI
      \new Voice= "LSecond"
      \LHII
    >>}
  >>
  \layout { }
  \midi { }
}

Output:
Answer: Whenever there are many such staves (for example to show the notes below a ChordNames staff), I placed a mix of the code from other answers in a Scheme function, and used it in a lyrics staff:
#(define-markup-command (chordstaff layout props notes) (ly:music?)
  (let ((markup #{ \markup {
                     \score {
                       \new Staff \with {
                         \remove "Time_signature_engraver"
                         \remove "Key_engraver"
                         \remove "Clef_engraver"
                         \magnifyStaff #3/4
                       }
                       { #notes }
                     }
                   }
                #}))
        (interpret-markup layout props markup)))

\score
{
  <<
    \new Staff { c'4 e'4 g'4 e'4 | c'1 }

    \new ChordNames {
       \chordmode { c2 | g2 | c1 }
    }

    \new Lyrics {
      \override LyricText.self-alignment-X = #LEFT
      \lyricmode {
         \markup{\chordstaff{<c' e' g'>2}}2
         \markup{\chordstaff{\partial 2 2}}2
         \markup{\chordstaff{<c' e' g'>1}}1
      }
    }
  >>
  \layout {}
}

Output:


How can I center an image and a button inside a div?

Question:

        T-Shirts                                View details

I'm trying to center my image and button within my div, and possibly shorten the width of the button as well.
Comment: There's a lot of errors in the HTML. There are some attributes missing.
Answer: Add the following to the style attribute of your image:
display:block; margin:auto
display:block is required, because img is an inline element by default.
By setting margin:auto, the margins of your image will adjust to center it automatically.