Prove that for matrices $A, B\in M_n: r(A)=r(B)=n \Rightarrow r(AB)=n$

Question: Prove that for matrices $A, B\in M_n$
$$r(A)=r(B)=n \Rightarrow r(AB)=n$$
My attempt:
$$\dim[\{A_1,...,A_n\}]=n$$ where $A_i$ are columns of $A$.
$$\dim[\{B_1,...,B_n\}]=n$$ where $B_i$ are columns of $B$.
$$AB=C=\begin{pmatrix}
\sum_{k=1}^{n} a_{1k}b_{k1} & \sum_{k=1}^{n}a_{1k}b_{k2} &\ldots &\sum_{k=1}^{n}a_{1k}b_{kn}\\
\vdots &\vdots &\ddots &\vdots\\
\sum_{k=1}^{n}a_{nk}b_{k1} &\sum_{k=1}^{n}a_{nk}b_{k2} &\ldots &\sum_{k=1}^n a_{nk}b_{kn}\\
\end{pmatrix}$$
$\dim[\{C_1,..,C_n\}]=?$
How do I continue from here?
Comment: Hint: $r(A)=n\iff\forall x\ne0\colon Ax\ne0$.
Answer: $$r(A)=n\;\wedge\;r(B)=n\Rightarrow \det A\ne 0 \;\wedge\;\det B\ne 0$$ $$\Rightarrow \det (AB)=\det (A)\det (B)\ne 0 \Rightarrow r(AB)=n.$$
Comment: How does $\det (A)\det (B)\neq 0$ imply $r(AB)=n$?
Comment: It is a well kown result: A square matrix $M$ of order $n$ is non-singular iff its rank is equal to $n$.


Retornar chave primaria após inserção no MySQL

Question: Eu preciso inserir no meu banco de dados duas tabelas, uma das tabelas tem uma chave primária e a outra vai usar esse valor como chave estrangeira.
Minha dúvida é: Como consigo retornar o valor dessa chave primária logo na hora da inserção? Ou como eu posso fazer a busca da PK, sem tem o risco de eu pegar o valor de uma outra tupla que foi inserida ao mesmo tempo ou logo depois?
Obrigado
Comment: em trigger ou programação?
Answer: Se tratando de MySQLi você pode utilizar a função insert_id().
Exemplo da documentação:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Answer: Outra forma se tratando de mysqli, se não tiver usando uma classe (orientado a objeto), a função insert_id(); pode ser usada da seguinte forma:
mysqli_insert_id($conexao_com_mysql)

ao invés de:
$mysqli->insert_id

Esta função retorna a última chave primária inserida naquela sessão, sem  a chance de você pegar outra chave primária que não seja a que acabou de inserir.


Drupal daylight savings issue

Question: My drupal installation is still displaying summer time after the daylight savings switch yesterday. Wrong dates include the following pages:

Views displaying nodes with created/updated fields
Drupal reports
page

My timezone is set in drupal config to Europe/Bratislava. I have tested the raw date() function in the web server, and it returns the correct time.
It seems that dates are saved correctly by timestamp using a time() function; the problem is displaying. Can anybody tell what is wrong? Is it a bug, or something else?

I have already found a problem. Drupal variable date_default_timezone was set to 7200 for Europe/Bratislava timezone. In fact, the correct value for winter time is 3600 for this timezone.
Solution was to resave the timezone settings under the Drupal "Date and time" configuration within the administration menu. It will then adjust the date_default_timezone variable.
I am just curious, why is this switch not happening automatically?
Comment: Drupal 6 or Drupal 7?
Comment: In the U.S., daylight savings time does not change until 4 November. http://www.time.gov/timezone.cgi?Pacific/d/-8/java  Perhaps there is some bug related to time/date handling, although it is surprising that Drupal is not simply using the system time. It would probably be best to address this in the issue queue on Drupal.org.
Answer: Try out Daylight saving time module.

This module intended to work with Daylight saving time. It replaces
  system time offset and has preferences for each user and full site.
Used to display correct time of creation of documents etc.

Drupal daylight savings issue


Is $G$ a subgroup of $GL(2,\mathbb R)$?

Question: Let $G=\begin{bmatrix}a&b\\0&d\end{bmatrix}$ exist in $GL(2,\mathbb R)$.
So in order to prove this is a subgroup we need to show $G$ is closed with respect to $*$ and we also need to show $G$ is closed with respect to taking inverses.
I know $$\begin{bmatrix}a&b\\0&d\end{bmatrix}^{-1}=\begin{bmatrix}1/a&1/b\\0&1/d\end{bmatrix}$$ which exists in $GL(2,\mathbb R)$ since these are all real numbers.
Now to show it is closed under $*$ we will do $$\begin{bmatrix}a&b\\0&d\end{bmatrix}*\begin{bmatrix}a&b\\0&d\end{bmatrix}=\begin{bmatrix}a^2&ab+bd\\0&d^2\end{bmatrix}.$$  Since this exists in $GL(2,\mathbb R)$ then it is closed under $*$.  [Thus $G$ is a subgroup].
I'm not sure if this is right but I just used the defintion of a subgroup.
Comment: Your formula for $A^{-1}$ is wrong. Also, for some real numbers $x$ there is no such thing as $\frac1x$
Comment: Also. it is unclear to me why you are looking at $AB\in G$ only for the special case $A=B$.
Comment: You've only shown that if $A\in G$ then $A*A\in G.$ (And the previous commenter is correct, your definition of $A^{-1}$ is wrong.)
Comment: My apolgizes the matrix is, /begin{bmatrix}1/a&-b/ad\\0&1/d\end{bmatrix}.  What would be another matrix I could use besides A?
Answer: You are wrong about the inverse. It turns out that$$\begin{bmatrix}a&b\\0&d\end{bmatrix}^{-1}=\begin{bmatrix}\frac1a&-\frac b{ad}\\0&\frac1d\end{bmatrix}.$$But it is still an element of $G$ and therefore there is no problem here.
And in order to prove that $G$ is closed with respect to the product of matrices, you should take two elements of $G$:$$\begin{bmatrix}a&b\\0&d\end{bmatrix}.\begin{bmatrix}a'&b'\\0&d'\end{bmatrix}=\begin{bmatrix}aa'&ab'+bd'\\0&dd'\end{bmatrix}\in G.$$

Is $G$ a subgroup of $GL(2,\mathbb R)$?


Colocando um vetor em ordem decresente

Question: Preciso criar um vetor de tamanho N mas ele tem que esta ordenado decrescente só que quando eu faço o codigo sempre da 0.
public int[] vetor_dec (int n) {
    int[]vetor = new int[n];
    for(int i=n;i>vetor.length;i--) {
        int aux=0;
        vetor[aux]=i;
        aux++;
    }
    return vetor;
}

Teria como me dizer o que esta errado?
Answer: Olhei rápidamente aqui seu int aux=0; esta dentro do For, esta alimentando seu vetor sempre na posição 0 !
Answer: Os problemas no seu código são os seguintes:

Você nunca vai entrar nesse loop:
for(int i=n;i>vetor.length;i--) {

Ao iniciar, i vale n, que é igual a vetor.length; quando a condição for testada, dará false de cara, de modo que ele vai retornar o vetor inalterado.
E como em Java um vetor é sempre iniciado com tudo zero (ou null, se for um vetor de referências) então é isso que você vai obter.
Uma solução é percorrer de n até 1:
for(int i=n;i>0;i--) {

O aux está sendo definido dentro do corpo do loop
for(int i=n;i>vetor.length;i--) {
    int aux=0;

Isso significa que, mesmo que seu primeiro problema seja resolvido, ele sempre será zero. Isso faria com que você atribuísse a posição zero do seu vetor, várias vezes (uma sobrescrevendo a outra). O resultado seria algo do tipo:
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

Para resolver isso, é só mover o aux para fora do loop, de modo que ele preserve seu valor (incrementado por você) entre uma iteração e outra:
int aux=0;
for(int i=n;i>vetor.length;i--) {

Código completo:
int[]vetor = new int[n];
int aux=0;
for(int i=n;i>0;i--) {
    vetor[aux]=i;
    aux++;
}
return vetor;

Nota: estou assumindo que você quer valores de 1 a n. Se quer outro intervalo - por exemplo de 0 a n-1 - ajuste a condição do seu for de acordo.
Answer: Muda o seu for e tira a variável aux do loop.
Deixa o código assim:
public int[] vetor_dec (int n) {
    int[]vetor = new int[n];
    for(int i=n-1;i>=0;i--) {
        vetor[i]=i+1;
    }
    return vetor;
}

Colocando um vetor em ordem decresente


Will arranging a song in piano increase my overall arrangement ability?

Question: Will arranging a song in piano increase my overall arrangement ability ?
Is arranging in piano some what of basic ? or essential or fundamental for arranging in orchestra or any other genre with multi instruments ?
Like what could you learn from just arranging your music in piano ?
How would arranging in piano increase my overall arrangement ability ?
Comment: I would argue that arranging anything for anything will generally increase your skills.
Answer:
Is arranging in piano some what of basic ? or essential or fundamental for arranging in orchestra or any other genre with multi instruments?

Do you mean on piano, or for piano? Basic keyboard skills are required of all music majors at university (or at least it was a degree requirement in my day) so yes I would argue that being able to arrange a song for piano reduction is somewhat of a "basic or essential or fundamental" skill that all musicians should possess. Piano is very linear and visual, which is why it's a great first instrument for young beginners. Arranging on a keyboard (on piano) can help you to see melodic and harmonic intervals in a way otherwise not possible on (for example) a trumpet or clarinet.

Like what could you learn from just arranging your music in piano?

Again, do you mean on or for piano?  My first paragraph may answer this. I'll add that once you reach the intermediate level of piano lessons, you learn different bass techniques, and chord inversions. These are necessary knowledge for any good composer/arranger.

How would arranging in piano increase my overall arrangement ability?

I believe it depends on you and on your understanding of how piano music works, and how piano players think. If you approach piano with a guitar mentality, it will sound like a guitarist's attempt to play keys. Much like when a pianist who doesn't understand guitar tries to play guitar on their keyboard with a VST/plugin.
The point I'm trying to make is that if you are using the keyboard to visualize your music in a new way, then yes it will definitely help you to see those intervals mapped out in front of you. However if you are writing for a piano player to perform your work, then you must first study other piano arrangements to try and grasp the perspective of the performer.
Comment: The only instrument I know how to play and have is piano.
But my dream isn't being a pianist or composing solo piano pieces.
I don't know anything about arranging a orchestra or other genre right now, so
I thought maybe arranging for piano first, might help me arranging other type of music.
Answer: Yes, any arranging will develop your arranging skills.  An arranger needs to be able to write idiomatically for all instruments, including piano.
But your question is unclear.  Are you asking about making a piano arrangement as a first step towards an orchestral version?   Maybe a piano version will be useful to the future performers.  But forcing the resources of an orchestra into what can be played by two hands can be a backwards step.  If you're writing for orchestra, think orchestrally from the outset.
Comment: I would argue that making a piano reduction of an orchestral piece requires a considerable amount of musical wisdom as well. How do you rearrange a piece played by hundreds or even thousands of musicians, played on a huge variety of instruments, to a version that can be played with two hands only without losing any crucial musical character?
Answer: It will help you to increase your knowledge of handling the harmony, melody, train your ear, thinking and reading key-assignments, reading  different clefs, finding a good bass line and also writing the notes.
But the you will know only about 20 percent of the work you have to do arranging for orchestra and instrumentation. My experience (writing for brass band) is: When I have an arrangement for piano it takes me at least twice as time for arranging the piece for a whole orchestra or band.
Answer: Arranging for orchestra is far different than arranging for piano.  Piano is pure harmony with no consideration as to how that part will be articulated on the actual instrument.  Each instrument has its own technical difficulty and limitations.  First do the arrangement for piano and then migrate that to the specific instrument parts.  Take these individual parts and show them to highly skilled musicians on each instrument.  They will give you valuable feedback as to the "playability" of the arrangement.


How to store data locally on a computer?

Question: I want to develop a Java based desktop application, in which I want to use MySQL or any other database for storing data. Then I want to make my application bundle in a one file package for distribution.
Distributed execution file can be installed in any operating system (Mac, Linux, Windows). But the problem is, general people don't want to install MySQL or any other database. So what is the good way to pack everything inside my bundle package so that only one click installation is sufficient to run my application smoothly?
If I don't use SQLite, is there any way to pack other database in my application? Or suggest me a better way for this plan.
Comment: Possible duplicate of [Executable Java application (JAR) with database packaged inside](https://stackoverflow.com/questions/30323276/executable-java-application-jar-with-database-packaged-inside)
Comment: You can always use SQLite.
Comment: Possible duplicate of [How to include SQLite database in executable Jar?](https://stackoverflow.com/questions/12019974/how-to-include-sqlite-database-in-executable-jar)
Comment: No it's  not. I don't want to use SQLite.
Answer: You can use any Database, but you have package that DBMS software in your installer.
You have to create different installers based in the Operating Systems that you want to support.
For every OS based installer you have to write different scripts which you have embed in your installer. Like for Windows you can write Powershell script which will extract the installer and install different softwares required. As for your DBMS you need to provide username and password. So you need to write a script which will ask this input from user (It can be a small window).
Another solution that you may like to look into, you can write a Docker image and can run a docker container.


How to install OGRE SDK in Ubuntu 13.04?

Question: I installed Ubuntu 13.04 in VMware. Now I want to install OGRE and Eclipse but I don't know which version of OGRE SDK I should install. The OGRE SDK download page has many links, but none that says it is for Ubuntu. Which one should I get?
Answer: Have a look at the Quick Start Guide. The source code download page is currently pointing at OGRE 1.8.1 Source for Linux / OSX. Don't forget to read through the Prerequisites!


model implicit and explicit behavioral data for recommendation engine

Question: I've following user behavior data,
1. like
2. dislike
3. rating
4. product viewed
5. product purchased
The spark MLlib which support implicit behavioral data with the confident score 0 or 1, Ref (http://spark.apache.org/docs/latest/mllib-collaborative-filtering.html).
For example user 1 viewed product A then the model will be like
1,A,1 (userId, productId, binary confident score)
But by looking at the nature of behavior, product liked has strong confident than product viewed. Product bought has strong confident than product viewed.
How can one model the data based on the type of behavior?
Answer: Actually implicit data does not have to be 0 or 1. It means that the values are treated like a confidence or strength of association, rather than a rating. You can simply model actions that show a higher association between user and item as having a higher confidence. A like is stronger than a view, and a purchase is stronger than a like.
In fact, negative confidence can be fit into this framework (and I know MLlib implements that). A dislike can mean a negative score.
What the values are are up to you to tune, really. I think it's reasonable to pick values that correspond to relative frequency, if you have no better idea. For example, if there are generally 50x more page views than likes, maybe a like's value is 50x that of a page view.


What can cause a HV000028 validation exception?

Question: The application can persist users which can be modified later. Lately a user could not be modified and the HV000028 exception was thrown. The user entity was persisted without errors or validation.
Does someone have an idea what could have caused such a behaviour or how I could find out more details?
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48) Caused by: javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:451)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:127)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:592)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:555)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:490)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:454)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:406)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:204)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:253)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at sun.reflect.GeneratedMethodAccessor427.invoke(Unknown Source)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2018-06-29 13:40:29,612 INFO  [stdout] (default task-48)        at java.lang.reflect.Method.invoke(Method.java:498)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.proxy.LazyInitProxyFactory$JdkHandler.invoke(LazyInitProxyFactory.java:507)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at com.sun.proxy.$Proxy287.validate(Unknown Source)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at ch.lmv.ulm.web.page.template.BasePanel.doCompleteJSR303Validation(BasePanel.java:65)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at ch.lmv.ulm.web.page.template.BasePanel.doCompleteJSR303Validation(BasePanel.java:49)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at ch.lmv.ulm.web.page.person.EditPersonPanel$7.onSubmit(EditPersonPanel.java:420)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink$1.onSubmit(AjaxSubmitLink.java:110)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.ajax.form.AjaxFormSubmitBehavior$AjaxFormSubmitter.onSubmit(AjaxFormSubmitBehavior.java:215)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1307)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.markup.html.form.Form.process(Form.java:974)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:795)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.ajax.form.AjaxFormSubmitBehavior.onEvent(AjaxFormSubmitBehavior.java:171)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.ajax.AjaxEventBehavior.respond(AjaxEventBehavior.java:155)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        at org.apache.wicket.ajax.AbstractDefaultAjaxBehavior.onRequest(AbstractDefaultAjaxBehavior.java:588)
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48)        ... 82 more
2018-06-29 13:40:29,613 INFO  [stdout] (default task-48) Caused by: java.lang.NullPointerException

Comment: Have you written custom validation?
Answer: From your stack trace the validation failed on some NullPointerException, but it's on the last line. You should have posted a full stack trace.
Also please note, it's not a Hibernate (an ORM) that has caused the exception, but Hibernate Validator, which is a completely different thing.
This validator has a series of validations executed on input object that is called from wicket, see: ch.lmv.ulm.web.page.template.BasePanel.doCompleteJSR303Validation.
Now the bad part is that your logging system probably is not correctly configured. It's hard to say what exactly happens with your logging system, because you do not supply any details about it.
In a correct configuration, the exception with the stack-trace should be printed as a multiline string (one single INFO message) and not as a series of Messages (you have INFO on every single line, and it's wrong).
The correct way of calling the log (for example in slf4j framework) should be:
try {
   ... execute validation code
}catch (<SomeKindOfValidationExceptionYouExpectToGet> ex) {
   logger.error("Failed to validate <or better message>", ex);
}

Note, that you pass an exception as an additional parameter here.
Comment: This should be a comment not answer.
Comment: yes exactly, but unfortunately I only have this part of the stacktrace, since the log level was 'info'.
Comment: Thank you for the tip concerning the logging configuration. Do you have a tip on a good tutorial for log config?
Comment: Usually it depends on logging framework, and usually by default, it works like this. Do you catch the exception? if so, how do you print it? The good way is something like... (I'll update an answer with an example of a correct call), but if you need more details, I think its better to ask a separate question
Answer: Easy, it is because the user has submitted some value in the webpage form that has @NotNull annotation, and in the validator for the incoming request, when you detect the invalid null, some NPE is thrown in midst of validation, before Spring could throw its own InvalidArgumentException.
Most importantly, tell user to change its input, and change code to throw InvalidArgumentException so that the exception handler could do its job.
Answer: For me it was This
I solved by adding this to application.propperties
spring.jpa.properties.javax.persistence.validation.mode=none


What does this syntax in c++ means?

Question: I found a code from someone to solve a code question, but I really don't understand this line
if(!(dp[i] = dp[i + 1] || str[i] != str[j]) && (e - s) <= (j - i)), and what the array "dp" really do?  What does dp[i] = dp[i+1] mean? Isn't it assigning dp[i+1] to dp[i]??? Here is the code.
class Solution {
public:
    string longestPalindrome(string str) {
        const int n = str.size();
        if(n < 2) return str;
        int s = 0, e = 0;
        int dp[n] = {0, };
        for(int j = 0; j < n; ++j){
            for(int i = 0; i < j; ++i){
                if(!(dp[i] = dp[i + 1] || str[i] != str[j]) && (e - s) <= (j - i))
                    s = i, e = j;
            }
        }
        return str.substr(s, e - s + 1);
    }
};

Comment: Note `int dp[n] = {0, };` is not standard C++ since `n` is not a constant expression (its value is not known at compile time). The code is relying on a language extension provided by some compilers.
Comment: @HongOoi How can you know whether or not that is the intention of the original creator of the code?
Comment: I think it will be helpful to you in the long run to understand the basics of the language from a [good textbook](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Getting answers to the specific questions you ask will only benefit you in the short term.
Comment: I assume that `=` is meant to be a `==`
Comment: anthony, the `dp` array is not syntax but instead the calculation storage for a dynamic programming solution to this presumably competitive programming problem. This is not a programming problem, so it doesn't really belong on stackoverflow. Read more about dp here: https://blog.usejournal.com/top-50-dynamic-programming-practice-problems-4208fed71aa3
Answer:
What does dp[i] = dp[i+1] mean? Isn't it assigning dp[i+1] to dp[i]

Not exactly! As the || operator has higher precedence than the = operator, the assignment is actually equivalent to this:
dp[i] = ( dp[i+1] || (str[i] != str[j]) );

But all expressions in C++ have a value as well as an effect. In the case of an assignment, like the one here, the value of the expression is the same as the value that is ultimately assigned (to the LHS). So, here, the value of the expression will be equal to the value of dp[i + 1] logically ORed with the result of the str[i] != str[j] comparison. If the i and j elements are not equal, then dp[i] will be given the value of 1; if they are the same, it will be given the value of dp[i+1].
The use of this expression inside a logical test condition achieves two things:

First, it accomplishes the assignment (as expected)
Second, it checks whether or not the assigned value is non-zero ("true").

The second point is used to further evaluate the entire if statement.
As this is the first expression to be evaluated, the code could be written more clearly (though less succinctly) as follows:
    for(int i = 0; i < j; ++i){
        dp[i] = dp[i + 1] || (str[i] != str[j]); // Do the assignment...
        if((dp[i] == 0) && (e - s) <= (j - i))  // ... then test dp[i]
            s = i, e = j;
    }

Feel free to ask for further clarification and/or explanation.
Comment: `=` has lower precedence than `||`.
Comment: yeah, thank you two! I know what's wrong now! The question of dp array is also solved since I get it after I read through all code. Thanks @Adrian Mole.

What does this syntax in c++ means?


Auto List Member não funciona com javascript

Question: Eu uso Visual Studio 2015, estou tendo problema de não exibir auto list member no javascript.

*Já fui na configuração > Editor de texto > JavaScript > Geral.
*Já reparei Visual Studio 2015 no painel de controle e nada resolveu.
*Já fui TOOLS > Import and Export Settings > Reset all Settings

OBS: Reinstalei Visual Studio, Auto List Member voltou a funcionar, no dia seguinte ela sumiu.
Já tenho as opções marcadas Auto list members e Parameter information, porem ela não funciona.

Um tempo atrás funcionava, mais agora não aparace mais.

Eu digito qualquer letrar, ela não acontece nada. O que pode ser esse problema ?
Answer: Resolvi o problema. O problema estava relacionado com NuGet.
Vai no menu PROJECT > Manage NuGet Packages, Vai desinstalando cada uma para ver se realmente resolve o problema. Então descobri o problema quem estava impedindo a mostrar auto list member. O problema era "JQuery.UI.Combined".


Drush post-installation - where can I find drushrc.php?

Question: Just getting my first hands-on with Drush 5.1. The stuff works and is very promising as per how modules can be installed and enabled. One question though. Where should I look for the drushrc.php file that everyone is referring to and how should I code it to set up aliases for my sites?
I did a search over my disk and found nothing except examples.aliases.drushrc.php. Also I found a couple of mysterious locations:
C:\Program Files\Drush
C:\Program Files\Propeople\Drush
C:\ProgramData\Drush
C:\ProgramData\Propeople\Drush

They surely contain vital stuff and I'm not going to touch anything, but I'm wondering if this is the correct post-installation shape.
Answer: First off, note that alias records go in *.aliases.drushrc.php, whereas general (global) Drush settings go in drushrc.php.  You can find example.aliases.drushrc.php and example.drushrc.php in the Drush "examples" folder.  Drush will look for aliases.drushrc.php and drushrc.php in the ".drush" folder in your home directory.  On most of my systems (Linux), my home directory is /home/ga; on Linux, $HOME and ~ will expand to your home directory.  On my Windows system, my home directory is at 'c:/Users/Greg Anderson'.  To find out exactly where Drush thinks your home directory is, run:
drush ev 'print(drush_server_home());'

Create a .drush folder inside of your home directory, copy example.drushrc.php to .drush/drushrc.php, and example.aliases.drushrc.php to .drush/aliases.drushrc.php, and customize to suit.
Comment: Haha :) yet another pair of location :) OK, thanks Greg, the evaluation probably fails, as I'm getting empty line and a blinking prompt, but placing a simple php file named `aliases.drushrc.php` in `C:\Users\[username]` worked. Issuing `drush @aliasname status` returned a meaningful info. Brilliant. More questions still to come :)


Two Hubs must not share the same name

Question: I created asp.net mvc 5 application (call it "WebServices"), then i add my Hubs in a folder called "Hubs".
Now what happened is that SignalR (2.0.2) generate JavaScript proxies for hubs in environment:
1-in local machine.
2-when i publish to azure web role.
Now when i publish to azure website (.NET is 4.5 and websocket is opened),it didn't generate proxies.
Now i tried to add hubs to App_Code folder ,and it generate proxies ,but the build action of the hub classes are "Content",when i change it to Compile it raised this exception :

Two Hubs must not share the same name. 'Webservices.App_Code.MyHub1,
  App_Code.c9aucf2j, Version=0.0.0.0, Culture=neutral,
  PublicKeyToken=null' and 'Webservices.App_Code.MyHub1, Webservices,
  Version=126.96.36.199, Culture=neutral, PublicKeyToken=null' both share the
  name 'MyHub1'.

Thanx
Answer: Probably you accidentally loaded an old dll (or better the framework discovered one for you) which also contains a hub with the same name. In my case the framework loaded
MyHubsTest.dll (with myHub in it)
MyHubsTest.exe (with myHub in it)

You can check it in Debug -> Windows -> Modules
Answer: I had this problem as well. I'm using ASP.NET 5, MVC6, and SignalR 2.2. To do this, I'm using the BuilderExtensions class detailed here:
https://code.msdn.microsoft.com/The-ASPNET-vNext-Real-Time-b1d27fe4
After a LONG debugging session, what ended up doing it was this part in my Startup.cs:
services.AddIdentity<ChirpUser, IdentityRole>(config =>
{
    config.User.AllowedUserNameCharacters = Properties.Resource.AllowedUsernameCharacters;
})
.AddEntityFrameworkStores<ChirpContext>();

ChirpUser is the name of my User class, and ChirpContext is my DbContext class, but honestly I don't think that's the important bit.
The problem line is the call to Properties.Resources. I had defined a string of my allow username characters there, but when this line is included, I have the error you described. When I take the line out, the problem goes away.
I don't have a good explanation for this, but maybe it will fit your situation.
Answer: For me, I had converted my code into a web application and needed to move the hub class out of the app_code folder.
SignalR creates it's own virtual SignalR/Hubs folder.  Maybe try renaming your Hubs folder to _Code

Two Hubs must not share the same name


If-Else Condition to Create New Column

Question: I have a dataset on gym activity.  I have data that looks like the following:
VisitNum   Date       Trainer   CaloriesBurned
1          01/04/20   Mike      500
2          01/06/20   Cindy     600
3          01/07/20   Lucy      550
4          01/10/20   Mike      650
5          01/15/20   Lucy      625
6          01/16/20   Lucy      575
7          01/19/20   Mike      525
8          01/21/20   Rebecca   592
9          01/26/20   Lucy      603
10         01/29/20   Mike      559

My goal is to have boxplots comparing the calories burned by trainer.  This is just a snapshot of the data and there are >30 different trainers.  I don't want to include all trainers in the plot, so I want to create a new variable, "Trainer2" that looks at the number of visits per trainer and if that number is less than 3, then the new value of Trainer would be "Other".
This is my attempt so far:
if data["Trainer"].value_counts() >= 3:
    data["Trainer2"]==data.Trainer
else:
    data["Trainer2"]=="Other"

I'm getting an error when I run this code and I'm not sure what I'm doing wrong:
ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().

Comment: @chung Using `==` instead of `=`  will calculate that expression as a boolean, and then discard the value.  Granted, this likely isn't what he _wanted_, but it won't throw an exception.
Comment: In your else: statement you have `==` instead of `=`. Edit: You should change the first if statement to use the single `=` which is the assignment operator, rather than the double `==`, which is a comparison operator. Right now all you're doing is checking `data["Trainer2"]` is equaling something and not changing its value at all
Comment: What is `"Trainer"` in this aspect? Is it a placeholder for one specific trainer, so, would your code state `"Lucy"` instead?
Comment: _I'm getting an error when I run this code_ Show us the error.
Comment: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Answer: I figured it out:
data["TrainerCounts"]=data["Trainer"].map(data['Trainer'].value_counts())

def f(row):
    if row['TrainerCounts'] >= 3:
        Trainer2 = row['Trainer']
    elif row['TrainerCounts'] < 3:
        Trainer2 = "Other"
    return Trainer2

data['Trainer2'] = data.apply(f, axis=1)

If-Else Condition to Create New Column


Comparator sort matching String at first, and rest using default sorting order

Question: String currency = EUR;

List<Payment> payments = #has payments, with one field being Currency;

//This is not it:
payments.sort(Comparator.comparing(o -> o.getCurrency().equals(currency));

I want all the payments which currency equals to variable currency in my case EUR to be at the top of the list, others order stays the same.
And if there is nothing that equals with the variable currency then sort by default value which for example is USD.
I know this can be done other ways, but this is kind of a challenge, can someone help, what I am missing from the first part, to order by equals.
Comment: Are you just trying to get the sort function to work correctly for your or are you also looking to see how you can use the keyExtractor Comparator.comparing()?
Answer: You need to have custom comparator logic to sort the object with currency = EUR at first and rest of them using natural sorting order
List<Payment> list = new ArrayList<>(List.of(new Payment("EUR"),new Payment("EUR"),new Payment("AUS"),new Payment("INR"),new Payment("INR")));

    list.sort((c1,c2)->{

        if (c1.getCurrency().equals("EUR")) {
            return c2.getCurrency().equals("EUR") ? 0 : -1;
        }
        if (c2.getCurrency().equals("EUR")) {
            return 1;
        }
        return c1.getCurrency().compareTo(c2.getCurrency());

    });

    System.out.println(list);  //[Payment [currency=EUR], Payment [currency=EUR], Payment [currency=AUS], Payment [currency=INR], Payment [currency=INR]]

Comment: Or `list.sort(Comparator.comparing(Payment::getCurrency, Comparator.naturalOrder().thenComparing(s -> !s.equals("EUR"))));`
Comment: You could just use `Arrays.asList()` instead of new `ArrayList(List.of`
Answer: If you are just looking to get the sort function to work for you, then your Comparator can return a negative value for your EUR currency giving it the lowest position in your sort order and treat all others as equal. If you want to maintain order within your EUR currency objects, you will have to expand on this further.
list.sort((o1, o2) -> o1.currency.equals("EUR") ? -1 : 0);

Comment: This is broken. A comparator must return zero for equal values, your comparator returns `-1` when both values are `"EUR"`. Further, a comparator must be symmetric, so when `("EUR", "xyz")` evaluates to a negative value, ("xyz", "EUR")` must evaluate to a non-zero positive value, but your comparator return zero in that case.


Java can't parse JSON generated by JSON.stringfy

Question: After upgrading from rc-1 to rc-3 the JSON.stringfy() method is returning values with \ at start and end of each value:
{
    \"perfil\":\"CLIENTE\", ...
}

How should I fix that?
code snippet:
post(url, data) {
    console.log(JSON.stringify(data));
    return Observable.create(observer =>
        this.http.post(this.restConfig.baseUrl + url, JSON.stringify(data), {
            headers: this.getDefaultHeaders()
        }).subscribe(
            data => this.next(observer, data)
            , err => {
                console.log(err);
                if (err.status === 401) {
                    this.redirectAuth();
                }
                observer.error(err);
            }
        )
    );
}

My Java RESTful services can't parse the output:
Unexpected token (VALUE_STRING), expected FIELD_NAME: missing property 'perfil' that is to contain type id  (for class br.com.inbit.medipop.model.entities.impl.Cliente) at [Source: java.io.ByteArrayInputStream@79f844cf; line: 1, column: 1]

class Cliente:
@Table
@Entity
@DiscriminatorValue("CLIENTE")
public class Cliente extends Usuario {

}

class Usuario:
@Table
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "perfil", discriminatorType = DiscriminatorType.STRING)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "perfil")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Administrador.class, name = "ADMIN"),
    @JsonSubTypes.Type(value = Colaborador.class, name = "COLABORADOR"),
    @JsonSubTypes.Type(value = Parceiro.class, name = "PARCEIRO"),
    @JsonSubTypes.Type(value = Cliente.class, name = "CLIENTE"),
    @JsonSubTypes.Type(value = Dependente.class, name = "DEPENDENTE")
})
public abstract class Usuario {

    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(insertable = false, updatable = false)
    protected PerfilUsuario perfil;

    ...
}

data before stringfy:
{"perfil":"CLIENTE","pessoa":{"tipo":"FISICA","sexo":"MASCULINO","nome":"Marcos Kichel","cpf":"911.111.064-36","rg":"1234"},"dependentes":[],"email":"email@example.com"}

Comment: please post a snippet of your code
Comment: done @Apostolos :)
Comment: It's just escaping the quotes. Is it actually causing problems?
Comment: Yes, my Java RESTful services can't parse the JSON output.
Comment: cannot reproduce it actually
Comment: what does data look like before you try to stringify it?
Comment: added to the question @JarodMoser
Comment: interesting, that's what it should look like **after** it has been stringified. So it seems your code is stringifying something that's already been stringified. What happens if you completely omit JSON.stringify?
Comment: @JarodMoser You got it! It was being stringfied one layer above in between some complex code of the framework. Thanks a lot! Now would you post an answer suggesting what I just mentioned so I can accept it? :D
Answer: It seems that you are stringifying something that was already stringified. Take out the JSON.stringify() and you should be good to go.
Answer: The issue here actually not caused by escaped quotes, but the wrong data type of perfil field. In your java code it's expected to be an object, while in json you pass the String value "CLIENTE".
So either make sure you send an object within "perfil" field or change the type of perfil field from PerfilUsuario to String
Comment: Actually, it is an `enum`, as you can notice on the `@Enumerated` annotation above the field. Enums are parsed as `String` by the `Jackson Body Writer`, it is not the problem, but thanks for your help anyway


Routing outgoing HTTP/HTTPS traffic over a different subnet

Question: I am trying to set up a Linux Server which was initially only supposed to be in one "server-subnet".
However I am forced to use a proxy to access HTTP/HTTPS services in this subnet, which causes a lot of problems with my web applications, that need to access an API over HTTPS.
Fortunately the Server is connected to a second "client subnet", which offers unrestricted access to HTTP/HTTPS services.
I configured both NICs and now I got the server subnet on eth0 and the client subnet on eth1.
I was reading up on similar issues and the closest I found was this: https://askubuntu.com/questions/104400/how-to-put-all-traffic-and-on-one-interface-and-some-traffic-on-another-interfac
I followed the instructions and changed the ports and interfaces accordingly (eth0's gateway being the default gateway) :
iptables -t mangle -A OUTPUT -p tcp --dport 443 -o eth0 -j MARK --set-mark 1
ip rule add fwmark 1 table 1
ip route add 0.0.0.0/0 table 1 dev eth1

However this doesn't seem to work.
I was wondering whether it is actually possible, from a technical point of view, to even create certain routing rules, that allow to route local outgoing HTTP/HTTPS traffic over another subnet.
Comment: Yes, and you've described exactly how it's done. So what is happening? And what else is unusual about your server?
Comment: Well, I can't establish any http or https connection. They are all terminated with connection timeout. Interrstingly enough traceroute --fwmark=1 myhost.com uses eth1's gateway as its first hop. So I suppose there must be sth. wrong with my iptables entry. Besides that there isn't anything weird about the server, besides the fact it's running in MS HyperV.
Comment: It might be possible that the responses are filtered as the IP address your query is originating from still would be the one from the "server subnet". Try adding `src ` to the `ip route add` statement if this is the case.
Comment: I got a little further. I was able to connect to a https server after trying `iptables -t mangle -A OUTPUT -p tcp --dport 443 -o eth0 -j MARK --set-mark 1` `ip rule add fwmark 1 table 1` `ip route add default table 1 via [gateway-client] src [client-ip]`. However I was only able to connect by using wget's `--bind-address` option. Is there a way to avoid this?
Answer: I know this post is really old, but just recently I solved this problem using another approach which involves source policy routing: Can't ping multihomed Linux machine on non-default interface.
The host is connected to the two networks. The "client subnet" allows for access to external resources, however its clients cannot be accessed from outside the network. Clients on the "server subnet" can be accessed from outside the network, however they cannot access any resources outside their own network.
                  ---
                   |"Client Subnet"
 ------     eth0   | 22.214.171.124
| Host |-----------
|      |-----------
 ------     eth1   |"Server Subnet"
                   | 18.104.22.168
                  ---

I set the gateway of the client subnet as the default gateway and configured the source policy routing as seen in the answer from the post above. The server then behaved as desired.
echo 13 eth1 >> /etc/iproute2/rt_tables
ip route add default via 126.96.36.199 table eth1
ip rule add from 184.108.40.206 lookup eth1

Comment: Can you please post actual commands you had used for created routing tables and specifying them in iptables rules. Your answer would be much more useful that way!


Theme generic file link in node template

Question: I want to change the text on a link to download a file in my node template. In Manage Display I have selected  Generic File as the formatter which outputs this

but I want to change it to this

How can I do this?
Comment: @Watergate Indeed can be marked as duplicate as the solutions are same, even though this question's about Manage Display page, and the dupe is about Views, both use "Generic File" formatter, and the solution is to override it or introduce a custom formatter.
Comment: @Beebee I undertand your point, therefore I think the title 'possible duplicate' is in it's place here. The solutions given in the linked answer are more extensive than the one currently given here.
Answer: You can function theme_file_link() , you can change the file link title before html rendered for file link in your custom themes templete.php file.


Apache Configuration - Domain with Hyphen

Question: Having a strange issue configuring apache.
I've got 4 domains

www.mydomain.tld
www.my-domain.tld
www.anotherdomain.tld
www.another-domain.tld

I've configured named virtualhost for each of the domains.
mydomain.tld, my-domain.tld and anotherdomain.tld works correctly but another-domain.tld isn't working correctly.
Apache seems to be picking up the virtualhost for anotherdomain.tld and serving it rather than the another-domain.tld
both have the server name set correctly

ServerName anotherdomain.tld

and

ServerName another-domain.tld

which seems to be the only place this could be an issue. Does anyone have any suggestion on finding the cause of this error.
A couple of other notes: each virtualhost is in a different file. mydomain.tld and my-domain.tld on a different ip address to anotherdomain.tld and another-domain.tld.
Comment: I have a couple ideas - but could you post the relevant vhosts configs? Obviously, feel free to edit the domain names out :)
Comment: Please paste the relevant bits of configuration -- it's much easier to see.
Comment: What happens if you put the name in quotes?
Comment: Are permissions set the same on your 4 config files?
Comment: Is it getting caught by your rewrite rules?
Answer: How can you tell that the web server is serving anotherdomain.tld instead of another-domain.tld? Do you see that URL in the browser's address bar has anotherdomain.tld in it?
If you created these configuration with copy-paste technique, then you could have left the DocumentRoot the same for both domains.
Another guess is if anotherdomain.tld and another-domain.tld are configured on the same IP address for apache, but another-domain.tlp DNS "A" record is set up to a different IP, Apache HTTPD just pulls out the default VirtualHost for the IP specified in its configuration, which may be anotherdomain.tld.
Example: If you have in DNS:
 anotherdomain.tld ->  184.108.40.206
 another-domain.tld -> 18.104.22.168

Then in httpd.conf:
<VirtualHost 18.104.22.168:80>
 ServerName anotherdomain.tld
  ...
</VirtualHost

<VirtualHost 220.127.116.11:80>
 ServerName another-domain.tld
  ...
</VirtualHost

When you type http://another-domain.tld/  in the browser's address bar, it makes a request to 126.96.36.199, which pulls out the default virtual host for 184.108.40.206, which is anotherdomain.tld.
These are just two wild guesses though...


How can I disable a single checkbox in a 'checkboxes' FAPI element?

Question: Title basically says it all, I want to disable a single checkbox of a checkboxes type FAPI element.
I don't want to do if with JavaScript, nor is changing it from checkboxes to multiple checkbox elements an option as the element is provided by another module.
Thoughts?
Comment: There is a typo in your question: "disable"
Answer: A clean way does exist in Drupal 7! Apparently, per this post, it's not yet documented.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#disabled'] = TRUE; //disables all options
  $form['checkboxes_element'][abc]['#disabled'] = TRUE; //disables option, called abc
}

Another example.
You can also set #access function to FALSE, to completely hide the checkbox.
Comment: With the typo corrected, this code absolutely works for me in D7. Thank you!
Comment: If you use #access, then if the checkbox is set in the #default_values, it will not be set in the form state values on submit.
Comment: Great catch! Glad it worked for you.
Comment: This works nicely.
Comment: Will not work with checkboxes (can select more than one element) using Better Exposed Filters (BEF) in views,  AFAICT.
Comment: This also works in Drupal 8. disabled inputs get attribute `disabled=disabled`, and the wrapper div gets the class `form-disabled`. It also works for form radios.
Comment: If you disable a checkbox and it was checked, than the value won't be sent. This is a bug currently (there's an issue about it on drupal.org).
Comment: I don't understand this. When I use the form_alter hook, there is no checkbox element under `$form`. They are under `$form['submitted']`, and you cannot disable the options there. I am using the webform module.
Answer: Unfortunately there's no really clean way to do that in FAPI. Your best bet -- if you're determined -- is to alter an additional #process function onto the checkboxes element.
The default function added to elements of type 'checkboxes' is actually a function (expand_checkboxes()) splits the single element out into multiple elements of type 'checkbox' that are later merged back into one. If you were to piggyback your second process function, it could reach into the expanded group of 'checkbox' elements and disable the one in question.
The following code is utterly untested, so caveat emptor:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#process'][] = 'mymodule_disable_element';
}

function mymodule_disable_element($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#disabled'] = TRUE;
      return;
    }
  }
}

Comment: The accepted answer seems a bit overkill when compared to @timofey's response.
Comment: Sounds better than the approach I took, which was to attach a theme function to the element and run a `preg_replace()` over the output.
Comment: You could add a "break;" inside the if statement above for a bit more efficiency, unless you expect to see the same element key twice.
Comment: Good catch, Chris, I changed the code snippet. Thanks!
Answer: Here is my code for Drupal 7, to change the Roles element in the Edit User page.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#pre_render'][] = 'form_process_checkboxes'; // I had to add this one, or it will return the first role only with my callback bellow
  $form['checkboxes_element']['#pre_render'][] = 'mymodule_disable_element';
}

function mymodule_disable_element(($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#attributes']['disabled'] = 'disabled';
    }
  }
  return $element;
}

Answer: I am using checkboxes as "assign" and "unassign". The client has asked that I disable "unassign", but it is still important to represent "assignment."  Keeping in mind that DISABLED checkboxes submit as "false" and if not handled properly will unassign, I split my checkboxes into "process these" and "ignore these disabled ones."  Here's how:
// Provide LIVE checkboxes only for un-assigned Partners
$form['partner']['partners'] = array(
  '#type' => 'checkboxes',
  '#options' => array_diff($partners, $assignments),
  '#title' => t($partnername),
);
// Provide DISABLED checkboxes for assigned Partners (but with a different variable, so it doesn't get processed as un-assignment)
$form['partner']['partner_assignments'] = array(
  '#type' => 'checkboxes',
  '#options' => $assignments,
  '#default_value' => array_keys($assignments),
  '#disabled' => TRUE,
  '#title' => t($partnername),
);

Notice that 'partner_assignments' is its own array/variable and will not be processed as "unassign," in my use case. Thanks for posting-- it led me to this solution.
Answer: D7. Here we had to make sure that when adding a node one certain taxonomy term reference option is always uncheckable and will always be saved to the node. So we went into #after_build and disabled that certain option, but had to make sure that in the end that certain option will be passed on. Cause only disabling it would have stopped that option's travel to future hooks.
// a constant
define('MYTERM', 113);

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'MYCONTENTTYPE_node_form') {
    $form['#after_build'][] = 'MYMODULE_MYCONTENTTYPE_node_form_after_build';
    }
}

/**
 * Implements custom after_build_function()
 */
function MYMODULE_MYCONTENTTYPE_node_form_after_build($form, &$form_state) {
  foreach (element_children($form['field_MYFIELD'][LANGUAGE_NONE]) as $tid) {
    if ($tid == MYTERM) {
      $element = &$form['field_MYFIELD'][LANGUAGE_NONE][$tid];
      $element['#checked'] = TRUE;
      $element['#attributes']['disabled'] = 'disabled';
    }
  }
  // here's ensured the term's travel goes on
  $form['field_MYFIELD'][LANGUAGE_NONE]['#value'] += drupal_map_assoc(array(MYTERM));
  return $form;
}

That's how the disabled option looks like:
Answer: I couldn't get Eaton's answer to work as written (the #process callback doesn't return anything, and it's called before the checkboxes are expanded) and I also wanted to have the value returned from the disabled checkbox (I wanted it permanently checked). This worked for me for Drupal 6.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#process'][] = 'mymodule_disable_element';
}

function mymodule_disable_element($element) {
  $expanded = expand_checkboxes($element);
  $checkbox =& $expanded[YOUR_CHECK_VALUE];
  $checkbox['#disabled'] = TRUE;
  $checkbox['#value_callback'] = 'mymodule_element_value_callback';
  return $expanded;
}

function mymodule_element_value_callback($element, $edit = FALSE) {
  // Return whatever value you'd like here, otherwise the element will return
  // FALSE because it's disabled.
  return 'VALUE';
}

Answer: Here is my code for Drupal 7, to change the Roles element in the Edit User page.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#pre_render'][] = 'form_process_checkboxes'; // I had to add this one, or it will return the first role only with my callback bellow
  $form['checkboxes_element']['#pre_render'][] = 'mymodule_disable_element';
}

function mymodule_disable_element(($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#attributes']['disabled'] = 'disabled';
      return $element;
    }
  }
  return $element;
}

Answer: Here is my example (using #after_build):
$form['legal']['legal_accept']['#type'] = 'checkboxes';
$form['legal']['legal_accept']['#options'] = $options;
$form['legal']['legal_accept']['#after_build'][] = '_process_checkboxes';

Plus the following function callback:
function _process_checkboxes($element) {
  foreach (element_children($element) as $key) {
    if ($key == 0) { // value of your checkbox, 0, 1, etc.
      $element[$key]['#attributes'] = array('disabled' => 'disabled');
      // $element[$key]['#theme'] = 'hidden'; // hide completely
    }
  }
  return $element;
}

Tested on Drupal 6, but it should work for Drupal 7 as well.

Drupal 6
You can use the following function (source):
/*
 * Change options for individual checkbox or radio field in the form
 * You can use this function using form_alter hook.
 * i.e. _set_checkbox_option('field_tier_level', 'associate', array('#disabled' => 'disabled'), $form);
 *
 * @param $field_name (string)
 *    Name of the field in the form
 * @param $checkbox_name (string)
 *    Name of checkbox to change options (if it's null, set to all)
 * @param $options (array)
 *    Custom options to set
 * @param $form (array)
 *    Form to change
 *
 * @author kenorb at gmail.com
 */
function _set_checkbox_option($field_name, $checkbox_name = NULL, $options, &$form) {
    if (isset($form[$field_name]) && is_array($form[$field_name])) {
        foreach ($form[$field_name] as $key => $value) {
            if (isset($form[$field_name][$key]['#type'])) {
                $curr_arr = &$form[$field_name][$key]; // set array as current
                $type = $form[$field_name][$key]['#type'];
                break;
            }
        }
        if (isset($curr_arr) && is_array($curr_arr['#default_value'])) {
            switch ($type) { // changed type from plural to singular
                case 'radios':
                    $type = 'radio';
                    break;
                case 'checkboxes':
                    $type = 'checkbox';
                    break;
            }

            foreach ($curr_arr['#default_value'] as $key => $value) {
                foreach($curr_arr as $old_key => $old_value) { // copy existing options for to current option
                    $new_options[$old_key] = $old_value;
                }
                $new_options['#type'] = $type;  // set type
                $new_options['#title'] = $value;  // set correct title of option
                $curr_arr[$key] = $new_options; // set new options

                if (empty($checkbox_name) || strcasecmp($checkbox_name, $value) == 0) { // check name or set for
                    foreach($options as $new_key => $new_value) {
                        $curr_arr[$key][$new_key] = $value;
                    }
                }
            }
            unset($curr_arr['#options']); // delete old options settings
        } else {
            return NULL;
        }
    } else {
        return NULL;
    }
}

/*
 * Disable selected field in the form(whatever if it's textfield, checkbox or radio)
 * You can use this function using form_alter hook.
 * i.e. _disable_field('title', $form);
 *
 * @param $field_name (string)
 *    Name of the field in the form
 * @param $form (array)
 *    Form to change
 *
 * @author kenorb at gmail.com
 */
function _disable_field($field_name, &$form) {
    $keyname = '#disabled';

    if (!isset($form[$field_name])) { // case: if field doesn't exists, put keyname in the main array
        $form[$keyname] = TRUE;
    } else if (!isset($form[$field_name]['#type']) && is_array($form[$field_name])) { // case: if type not exist, find type from inside of array
        foreach ($form[$field_name] as $key => $value) {
            if (isset($form[$field_name][$key]['#type'])) {
                $curr_arr = &$form[$field_name][$key]; // set array as current
                break;
            }
        }
    } else {
        $curr_arr = &$form[$field_name]; // set field array as current
    }

    // set the value
    if (isset($curr_arr['#type'])) {
        switch ($curr_arr['#type']) {
            case 'textfield':
            default:
                $curr_arr[$keyname] = TRUE;
        }
    }
}

Comment: D7: Same here, using #after_build is working as desired. Also confirming setting disabled using #attribute.
Answer: In Drupal 7, in order to disable options in a select in a fieldable entity, I found that I had to install a #process function. Unfortunately, this disabled the built-in process function, form_process_checkboxes, so that needs to be added back (or called from your process function). Additionally, when disabling checkboxes that are already checked, I discovered that the built-in value callback (form_type_checkboxes_value) ignores defaults when retrieving results from the input.
$field_lang_form = &$your_form[$field][LANGUAGE_NONE];
$field_lang_form['#process'][] = 'form_process_checkboxes';
$field_lang_form['#process'][] = 'YOURMODULE_YOURFUNCTION_process';
$field_lang_form['#value_callback'] = 'YOURMODULE_form_type_checkboxes_value';

Then something like this:
function YOURMODULE_YOURFUNCTION_process($element) {
  // Disallow access YOUR REASON, but show as disabled if option is set.
  foreach (element_children($element) as $field) {
    if (REASON TO DISABLE HERE) {
      if (!empty($element[$field]['#default_value'])) {
        $element[$field]['#disabled'] = TRUE;
      } else {
        $element[$club]['#access'] = FALSE;
      }
    }
  }
  return $element;
}

And finally:
function YOURMODULE_form_type_checkboxes_value($element, $input = FALSE) {
  if ($input !== FALSE) {
    foreach ($element['#default_value'] as $value) {
      if (THIS OPTION WAS SET AND DISABLED - YOUR BUSINESS LOGIC) {
        // This option was disabled and was not returned by the browser. Set it manually.
        $input[$value] = $value;
      }
    }
  }
  return form_type_checkboxes_value($element, $input);
}

I did not find that any of the other answers on this page worked in this case.
Answer: I am using this following code at drupal 6:-
$form['statuses'] = array(
    '#type' => 'checkboxes',
    '#options' => $statuses,
    '#default_value' => $status_val,
    '#after_build' => array('legal_process_checkboxes')
    );

and the call back function is here:-
/**
 * Process each checkbox based on 'feture' is already used by a Sub-domain or not.
 * @param Array $element array of form checkboxes
 */
function legal_process_checkboxes($element) {

  foreach (element_children($element) as $key) {

    $feature_id = $key;
    $res_total = '';

    $total = feature_used($feature_id) ;

    if ($total) {
      $element[$key]['#attributes'] = array('disabled' => 'disabled');
    }
  }
  return $element;
}

Comment: Welcome to drupal.stackexchange.com! Please fix your code formatting. Comments before legal_process_checkboxes() function have been left outside the "code" format. Thank you.
Answer: One important thing to factor in is that disabled checkboxes do not get submitted, so you might find that you need to force the #value of the checkbox too.. For example:
$element['child1']['#disabled'] = TRUE;
$element['child1']['#value'] = 'child1';

In my case, without this, the $form_state['values'] did not contain my checkbox value (which was checked by default, but disabled).
Comment: It is happening indeed, however this trick doesn't make any change(at least in my case)
Answer: Hook textfield and make a dynamic textbox with info from database
1° get the assoc. array from database eg
$blah = array('test1' => 'Choose for test1', 'test2' => 'Choose for test2', ...)

2° Implements hook_form_alter()
/**
 * Implements hook_form_alter().
 * form id = views-exposed-form
 */
function test_form_alter(&$form, &$form_state, $form_id)
{
  //only for this particular form
  if ($form['#id'] == "views-exposed-form-advanced-search-page-2")
    {
       $form['phases'] = array(
           '#type' => 'checkboxes',
           '#options' => $blah,
      );
    }
}

3° multiple fields will be checkable !
Answer: If you're building your own form, instead of running through separate form_alter/#process/#pre_render functions you can just switch from 'checkboxes' to generating individual 'checkbox' elements.
$options = array(
   1 => t('Option one'),
   2 => t('Option two'),
);

// Standard 'checkboxes' method:
$form['my_element'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Some checkboxes'),
  '#options' => $options,
);

// Individual 'checkbox' method:
$form['my_element'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('form-checkboxes')),
  '#tree' => TRUE,
  'label' => array('#markup' => '' . t('Some checkboxes') . '',
);
foreach ($options as $key => $label) {
  $form['my_element'][$key] = array(
    '#type' => 'checkbox',
    '#title' => $label,
    '#return_value' => $key,
  );
}
// Set whatever #disabled (etc) properties you need.
$form['my_element'][1]['#disabled'] = TRUE;

'#tree' => TRUE gives you the same tree structure as the checkboxes version when the $form_state['values'] array arrives at validation/submit/rebuild. If you can't or don't want to use #tree for some reason, give each checkbox a '#parents' => array('my_element', $key) property to explicitly set its position in the values structure.


How to test input and output overloaded operator in C++ Gtest

Question: I am using following example from here
Consider I have following class
#include <iostream>

class Distance {
private:
  int feet;
  int inches;

public:
  Distance()             : feet(), inches() {}
  Distance(int f, int i) : feet(f), inches(i) {}

  friend std::ostream &operator<<( std::ostream &output, const Distance &D )
  {
     output << "F : " << D.feet << " I : " << D.inches;
     return output;
  }

  friend std::istream &operator>>( std::istream  &input, Distance &D )
  {
     input >> D.feet >> D.inches;
     return input;
  }
};

I am using Gtest to test this class.
But I could not find better way to test it.
I can use the macro provided in gtest ASSERT_NO_THROW, but it will not validate the values.
Is there any way I can use EXPECT_EQ instead?
Thanks
Comment: Just looking at this one example I can already tell you that this tutorial is bad and teaches C++ that professionals will frown upon. Get [a good book](http://stackoverflow.com/a/388282/140719) instead!
Comment: @sbi, I know, I just wanted to give simple example to explain my problem.
Comment: Could you please post your testing code also? I'd go for testing using a `std::istringstream`, `std::ostringstream`.
Comment: @Rohit: I have edited your question so that the class now uses [initialization lists](http://stackoverflow.com/q/1711990/140719). Feel free to disagree with my formatting, but without the initialization lists the code was just awful. And see [here](http://stackoverflow.com/a/1453605/140719) for why `using namespace std` is bad.
Comment: @sbi I agree code was awful. My apologies.
Answer:
Is there any way I can use EXPECT_EQ instead?

You can use a stringstream to print the results of operator<< to a string, then compare the string.
https://en.cppreference.com/w/cpp/io/basic_stringstream
TEST( Distance, Output )
{
    std::ostringstream out;
    Distance d;
    out << d;
    EXPECT_EQ( "F:0 I:0", out.str() );
}

Input test would be similar, just use std::istringtream instead.
Answer: What do you want to test about the operators?

That the stream is in a good state after writing to or reading from it.
You can check for that.
That the output operator writes a particular string for a particular distance.
You can do this by writing into a std::ostringstream and comparing the result of calling its str() member with your expectations.
That the input iterator reads a particular distance from a particular string.
You can do this employing a std::istringstream initialized with the string, comparing the distance read from it with what you expect.
That the class eats its own dog food.
Use a std::stringstream to write into, then read from it, and compare what you read with what you wrote.
Note: This will currently fail.


password less sudo access for deploy user

Question:
Possible Duplicate:
ubuntu - how can I avoid typing a password on every admin action?

Googled and tried various approaches to solve the password-less sudo access commands, but none seem worked for me. The server is Ubuntu 10.04
I've a deploy user under deploy group.
I added the deploy user
Through google search and even all SF search combination, nothing worked. Following is my /etc/sudoers file
deploy@myserver:~$ id
uid=1000(deploy) gid=1001(deploy) groups=0(root),107(admin),1001(deploy),1002(rvm)
deploy@myserver:~$ groups
deploy root admin rvm
deploy@myserver:~$ sudo cat /etc/sudoers
# /etc/sudoers
Defaults    env_reset
root    ALL=(ALL) ALL
deploy  ALL=(ALL) ALL
#deploy ALL=NOPASSWD: ALL

%sudo ALL=(ALL) ALL
#includedir /etc/sudoers.d

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
%wheel ALL=(ALL) ALL
deploy@myserver:~$

When I try to open up /etc/sudoers with visudo command, Permission denied
deploy@myserver:~$ visudo
visudo: /etc/sudoers: Permission denied
visudo: /etc/sudoers: Permission denied
deploy@myserver:~$

Comment: can you try "sudo visudo"?
Comment: Is there a question here?
Comment: Oh! holy cow! What was I smoking??? Sorry guys.
Answer: How would you expect sudo to do its magic if you don't actually use sudo? What you need to do here is run sudo visudo.
Comment: Yup, holy cow! What was I smoking??? Sorry buddy.


How to solve Sturm-Liouville problem $y'' + (1 + \lambda)y = 0$?

Question: Find all the eigenvalues and eigenfunctions of Sturm-Lioville problem:
$$y'' + (1 + \lambda)y = 0$$
$$y(0) = y \left(\frac{\pi}{2}\right) = 0$$
Can someone please tell me how to solve this? Because most of the time, I mostly solve this type of Sturm-Liouville problem $y'' + \lambda y = 0$. And, my book is base on theory more than example. Thank you in advance.
Comment: The only difference between the problem you usually solve and this one is the $1+\lambda$?  OK, so let $1+\lambda = \mu$, solve the problem with $\mu$, and then take $\lambda = \mu - 1$.
Answer: The general solution to $y''+(1+\lambda)y=0$ is $y=A\sin(kx)+B\cos(kx)$
where $k^2 = 1 + \lambda$
the condition $y(0) = 0 $ gives $B=0$
then $ y(\frac{\pi}{2})=0$ requires that k be an even integer $k=2n$
So for every positive integer $n$
$y_n = A \sin (2nx)$
$\lambda_n = 4n^2 -1$
Comment: can you please be more specific. Because, I prefer how to solve rather than an answer
Answer: It's exactly the same as
$$y'' + \lambda y = 0 $$
except that $\lambda$ is replaced by $\lambda + 1$
So the solution is essentially the same, just treat $\lambda +1$ as $\lambda$
For $\lambda + 1 < 0$, $y = e^{\sqrt{\lambda+1}\,x} + e^{-\sqrt{\lambda+1}\,x}$
For $\lambda+1 = 0$, $x^2 + x$
For $\lambda_1 > 0$, $y = \cos\sqrt{\lambda+1}\,x + \sin\sqrt{\lambda+1}\,x$
And so on


Can CART models be made robust?

Question: A colleague in my office said to me today "Tree models aren't good because they get caught by extreme observations".
A search here resulted in this thread that basically supports the claim.
Which leads me to the question - under what situation can a CART model be robust, and how is that shown?
Answer: No, not in their present forms.
The problem is that convex loss functions cannot be made to be robust to contamination by outliers (this is a well known fact since the 70's but keeps being rediscovered periodically, see for instance this paper for one recent such re-discovery):
http://www.cs.columbia.edu/~rocco/Public/mlj9.pdf
Now, in the case of regression trees, the fact that CART uses marginals (or alternatively univariate projections) can be used:
one can think of a version of CART where the s.d. criterion is replaced by a more
robust counterpart (MAD or better yet, Qn estimator).
Edit:
I recently came across an older paper implementing the approach suggested above (using robust M estimator of scale instead of the MAD). This will impart robustness to "y" outliers to CART/RF's (but not to outliers located on the design space, which will affect the estimates of the model's hyper-parameters)  See:
Galimberti, G., Pillati, M., & Soffritti, G. (2007). Robust regression trees based on M-estimators.
Statistica, LXVII, 173–190.
Comment: @Tal CART is an equivalent to boosting, of a "pivot classifier" (the criterion that sits in each tree node, like some attribute grater than something or some attribute value in set something).
Comment: no *convex* loss function. See this article "A fast algorithm for the minimum covariance determinant estimator" for an example of what can be done with non-convex loss functions (although not related to classification, the article is worth a read).
Comment: Thank you kwak.  This article seems to be talking about boosting methods.  Do the results they present hold for the simple classifier case of a CART model? (on the surface it sounds like it, but I didn't go through the article enough to really know)
Comment: The result they present holds for any convex loss function, and was initially discussed by Tukey. To sum things up, the measure of spread (Gini or entropy) used to quantify the quality of a node is sensitive to contamination by outliers (i.e. observations that are miss-labeled in the dataset).  This problem affects both the building and the prunning stage. Contamination of a dataset by observation with wrongly imputed label will typically cause the resulting tree to be much too complex (you can check this rather easely by yourself).
Comment: Thank you Kwak!  And is there no loss function that is robust?
Comment: It is very enjoyable to ask questions when getting answers like the ones you give - thank you!  Last questions: Do you know of an easy way to implement such a loss function in R's CART? (rpart)
Comment: The problem you point out seems easier to solve for regression than classification trees. I do not know how to change the spread criterion (from s.d. to Qn) in R but since Qn (and MAD) are implemented it should not be difficult. Best (let us know whether you had any success with a 'robustified' version).
Comment: True.  Since I was intending to try this on regression trees, I'll have a go at it in the next few weeks and will come back to report if something nice will be formalized.  Best.
Answer: You might consider using Breiman's bagging or random forests.  One good reference is Breiman "Bagging Predictors" (1996).  Also summarized in Clifton Sutton's "Classification and Regression Trees, Bagging, and Boosting" in the Handbook of Statistics.
You can also see Andy Liaw and Matthew Wiener R News discussion of the randomForest package.
Comment: The problem is that outliers will make some 'bad' (i.e. contaminated) tree look better than good (uncontaminated) ones. This is called, masking effect and is easy to replicate with simulated data. The problem comes about because the criterion you use to evaluate trees is not in itself robust to outliers. I know i'm starting to sound like a fundamentalist mullah, but unless each and every tool you use is made robust, your procedure can be shown to be sensitive (at one level or another) to outliers (and hence not robust).
Comment: @kwak Still, this is a good answer; trees in RF don't see the entire set, so many of them will not be contaminated. Even better -- tracking in which leafs do OOB cases land can be used to find mislabeled objects and eliminate them. (As I recall now, this is mentioned in Breiman's paper about RF).
Comment: Not to spoil the party, but how are random forest supposed to provided robustness to contamination by outliers is a mystery.
Answer: If you check out the 'gbm' package in R (generalized gradient boosting), the 'boosting' uses loss functions that are not necessarily mean squared error.  This shows up in the 'distribution' argument to function 'gbm()'.  Thus the elaboration of the tree via boosting will be resistant to outliers, similar to how M-estimators work.
You might start here.
Another approach would be to build the tree the usual way (partitions based on SSE), but prune the tree using cross validation with a robust measure of fit.  I think xpred in rpart will give cross validated predictors (for a variety of different tree complexities), which you can then apply your own measure of error, such as mean absolute value.

Can CART models be made robust?


Visual Studio 2010 files modified warning dialog before recompile

Question: by default VS 2010 when I run a c++ application, eventually shows a dialog that notify if a source file changed, before automatically recompile the solution.
Unfortunately I made that dialog not to show anymore, accidentally selecting the checkbox "do not show again" or something like that.
Does anyone know how could I restore that dialog?
Comment: There isnt such a checkbox present. Are you sure its not working?
The options i had were: Yes  Yes to all  No  No to all.
Answer: In the Tools/Options/Projects and Solutions/Build and Run dialog are a couple of options that control this kind of behavior.  I think you're looking for the "On Run, when projects are out of date" option; select "Prompt to build".


Is it worthwhile to buy good accessories for a cheap violin

Question: I'm a self-teaching violinist. I bought my violin 3 years ago and have been practicing since than. I'm a highschool student, so I don't have much time to practice, so I'm slow at learning it. (I'm practicing classical music, BTW.) Because of quarantine, I'm staying at home, so now I have much more time practice my violin, and I think I'm a bit better than before. Recently, I've had a feeling that I should change some accessories for my violin like the bow, string, and bridge. I wonder if it is worth buying something good for my violin, like a Pirastro Tonica (~$30), a bow around $40, and/or a violin bridge like "Aubert à Mirecourt No.7". My violin is a Chinese violin "Christina V02" that I bought for $98. I've been using the cheap accessories that came with it. I think the strings are around $5, the bow is <$10 and the bridge is <$1. What do you think? As a high school student, I'm low on budget, so I don't think I'd buy a new violin soon enough.
Answer:
I'm a self-teaching violinist.

That's really the crux of the problem. If you had a teacher they would be able to give you far and away the best advice. I'm guessing you don't play in the school orchestra else the leader's advice would also be very useful.
Generally speaking the two things most worth upgrading in your situation are the bow and the strings. They are what, in the first instance, actually make the sound.
Tonicas would be a great choice for strings, particularly if you are currently using $5 strings.
For the bow I would try and get a halfway decent carbon fibre bow, but be prepared to go up to $100. At this low price point you will get a much better carbon fibre bow for your money than wooden bow.
It's almost impossible to give advice about a bridge over the internet, but the likelihood is that if what you have is a VSO (violin shaped object) then the cost of fixing the things that are wrong with it probably exceeds what it would cost to buy a decent student violin. Such changes would in any case have to be performed by an experienced luthier and that would cost. You can't just go out and buy a bridge over the internet and then make the adjustments (possibly involving cutting and trimming the bridge), adjusting the soundpost, etc., to improve the sound.
Comment: The problem is that the soundpost is not glued in place. It has to be so else it would not be possible to adjust the soundpost position. The soundpost is held in place by the pressure the strings place on the bridge and on the top of the violin. To replace the bridge you have to first slacken all the strings which removes this pressure so the soundpost can fall. Once the bridge is replaced and the strings tightened again then the soundpost will need to be repositioned. For a similar reason when you replace the strings it should be done one at a time to maintain the pressure on the soundpost.
Comment: As an instrumentmaker, I support what Brian says here. Better strings, followed by a better bow, will make the most difference in sound and playability.  I'd just add that while it's good practice to replace the strings one at a time, the soundpost will only very rarely fall down if all strings are removed at once.  If your soundpost is still in place, you don't need to bother with it.
Comment: @user635988 That's a tough question.  Normally, I would discourage anyone from changing the bridge themselves, because it's not easy.  You have to fit the feet to the belly of the violin and get all the dimensions correct.  However, if the original bridge is really shot, you really don't have access to a pro, are good with your hands, and aren't too worried about messing up the violin, you could try.  Alternatively, you could take the strings off one by one and superglue some bits of wood or paper in the slots to bring the strings up to their original level in the bridge.
Comment: In my country, there is no music subject and in my area there is no music teacher or luthier too. So I have to do everything online. For the bridge I thought when u buy it you could just put it on the violin between the sound hole, don't know that u have to adjust it
Comment: ohh no, last time I changed my string by remove all the string
Comment: I search some video on YouTube about fitting the bridge, it seem like it takes a lot of work. I have to change my bridge btw, because the string is eating the bridge and I usually hit 2 string instead of 1
Comment: What country has "no music subject" at school?  I know music is taught in Vietnam, and Thailand.  Though finding a luthier outside of the cities might be hard.
Comment: @JamesK I live in Cambodia, the neighbor of Thailand and Vietnam
Comment: @ScottWallace do you recommend i should change the bridge myself? The strings is cutting the bridge, I think it's getting deeper day by day
Comment: @ScottWallace I search around about the bridge and I just I realized that my bridge is on the wrong side! ( The front is at back and the back is put at the front... ) OMG it's been 3 years.
Comment: @user635988 There you go.  That's a problem easily solved.  Good luck to you.
Answer: "I wonder if it is worth buying something good for my violin"
You are not buying it for your violin, you are buying it for you.
The real question I think is whether the money will be wasted.  In my opinion NO.  If you are serious about playing and stick with it then some day you will buy a better violin and those accessories that are no perishable (like strings and rosin) will be put to good use.
As for the bow, $40 does not sound high end to me.  Bows can cost 100's or 1000's of dollars for a good one and having played violin and classical bass my teachers always stressed the importance of a good bow.  Some pros pay more for their bow than for the instrument.  In many cases a low quality instrument will sound better with good accessories so it is worth it to try.  Again, even if it does not improve you have better stuff when you get a better violin.
Comment: I was about to write an answer with _exactly_ the same first sentence and mostly identical first paragraph.
Comment: @user635988, violin is a tough instrument to master.  I've played violin and classical bass.  The bowing technique takes a lot of time and patience to master and before that it can sound like a cat getting hit by a car.  Only time will help with that, and occasional help from a good teacher.
Comment: Yeah, I've been thinking if I should just save the money until I could afford new violin or just buy new accessories. Thanks for your advice
Comment: @fdreger, make a new second paragraph and go for it.
Comment: @user635988, that is a tough call.  If the violin is really poor quality maybe wait but if it is a decent student model then in my experience a high quality bow and strings will make it play and sound better.
Comment: @ggcg i don't know about the quality of my violin at all, but for first time I played it, the sound is just bad that it gives me the thought of quiting playing it. To worth the money I spend on it, it gives me another idea, is to just ignore the sound and focus on developing my skill. Overtime, I think the sound is getting better ( I dunno if it is  because my violin skill or my violin just sounds better tho )


$\mathfrak{Top}$ and injective objects

Question: My question is very simple. Let $\mathfrak{Top}$ be the category of all topological spaces and continuous functions between them. Does such category have enough injectives? Is there a simple way to define injective objects of $\mathfrak{Top}$ with additional hypothesis on the topology?
Answer: I suppose you mean injective objects with respect to the class of all monomorphisms. Recall that a monomorphism in $\mathbf{Top}$ is precisely an injective continuous map. Thus:

Lemma. Every non-empty indiscrete space is injective.
Proof. Let $Z$ be non-empty and indiscrete. Then every map $X \to Z$ is automatically continuous. Thus, given any injective continuous map $f : X \to Y$ and any map $g : X \to Z$, there is at least one map $h : Y \to Z$ such that $h \circ f = g$, so $Z$ is indeed an injective object.

It follows that $\mathbf{Top}$ has enough injective objects, because every topological space admits an injective continuous map into a non-empty indiscrete space.
In particular, the injective objects in $\mathbf{Top}$ are precisely the non-empty indiscrete spaces: indeed, for any $X$, there is a non-empty indiscrete space $Z$ and an injective continuous map $f : X \to Z$, so if $X$ is injective, there is also a continuous map $r : Z \to X$ such that $r \circ f = \mathrm{id}_X$, and it is not hard to see that this implies $X$ is non-empty and indiscrete.

$\mathfrak{Top}$ and injective objects


Fixing off-tempo MIDI performance

Question: I'm a producer/composer and I've been tasked with fixing a MIDI file. I'm using Reason 7. There are a number of things not done right, but this one has me stumped.
I've been told the BPM is 130.100 but it doesn't line up, as you get further into the song in particular. This is what it looks like early on:

It's slightly off but still fixable. But as you get further into the song, it just wanders about its merry way, getting way off the tempo. For example, the notes at 45.3.25 should be on 46.0.00:

I'm wondering... Is there some fix or magic bullet to detect the actual tempo and apply it to the MIDI file, that you guys know of? I've tried several alternate tempos, like 130.050, 130.000, etc but they all wander off pretty quickly... Or do I need to just scrub the whole file by hand and spend precious hours getting this to line up right?
PS: I guess "Lost in time" is an appropriate song title, all things considered!
Comment: In Ableton you can use the "quantize" function to do this. Should be able to do the same in Reason. It won't be perfect but it might help you get the bulk of it in time then fix the smaller bits by hand: http://youtu.be/7yOv0Hx8eds?t=2m55s
Answer: I've never seen any software that can do this without a lot of human help. Quantizing, even with a performance that is very near the beat, will ruin the musician's expression. And if someone has recorded a MIDI performance without adhering to a tempo reference like a click track, simply quantizing will destroy the data.
If you really want a mechanical performance, enter the score into something like Sibelius or Finale, export to MIDI and you'll have it perfect.
If you want to preserve the human interpretation but want everything to land on its feet, you have a lot of work ahead of you. It will require detailed, subjective decision-making and tedious data entry. In the screenshots you've shown, it looks like simple triads. This will make your job easier.
I find it's best to work one phrase at a time. Timing differences compound over time, but you'll find that each phrase will tend to have integrity relative to itself. By working one phrase at a time, you'll drill into the first phrase, fix it, move to the next phrase and line it up with the first and so on.
Begin by lining up the first note or chord with the absolute beat but keep the rest of the phrase relative to the first note. Fix any glaring timing problems manually. By "timing problems", I mean single note mistakes that are obviously wrong. If the phrase is slower or faster than the target tempo, use an "adjust selection time" feature to lengthen or shorten the phrase so it matches the target tempo. Use trial and error to find the right amount. This will keep the expression that quantizing would ruin. Only when the phrase fits into its measures can you quantize safely. Only do it if it's necessary and start with just a little bit of quantization, like 40%. Then line the next phrase up with the next measure and repeat the process.
Comment: Sounds like I got my work cut out for! Next time this happens I will make sure to get the file first and listen to it before I commit to charging my standard rates lol. Thanks for your great answer.
Answer: If the piece is supposed to already have a uniform tempo, (i.e., it's not a recording of a human performance, as trw mentions) and the question is a merely a matter of discovering which tempo it is, you might be able to use some type of "tap tempo" tool. I'm sure there are lots of these, but the one I'm familiar with is in Reaper. You can probably find one on a website online.
Essentially, while the music is playing, you click a button (either on the mouse or keyboard) every beat, on the beat. Try to be as accurate as possible. Over a short period of time, the software will be able to determine the current tempo from your average rate of clicking. This will also allow you to check if the tempo varies, or remains constant, over the course of the song (If it varies, your work will be much more difficult).
Answer: If Reason has the capability: you can use the beats in the existing MIDI file to set the actual tempo to that of the unaltered MIDI performance. This means that the tempo itself will vary slightly to suit the music, not the other way around. If the project calls for a hard 130.1bpm tempo, this is not your solution.
What you're trying to do is to actually adjust the tempo as the song plays to match the human tempo of the midi file. If you can tell Reason where the downbeats in the MIDI file are, it might be able to generate a new tempo track that will adjust the tempo in little bits while the song is playing. This will completely eliminate any 'machine' effect from quantizing, but still let you use the tempo-based functions of your DAW.
Comment: Welcome to Music Stack Exchange.  Your answer is clear and to the point.  One concern might be that your details sound like they are based on a generic MIDI knowledge, rather than a specific knowledge of Reason, which perhaps makes the overall answer less helpful than it might be if you knew a specific fix, but I would think it would still be helpful to the OP.  Again, welcome.
Answer: A glance at the file suggests that it IS quantised, and therefore probably was created at a fixed tempo.  I'm not sure how it slipped out of synch, but you might be able to stretch it back.  I can only describe how I'd do it in Cubase though.
There's a function where you can select an object - in this case it would be the whole song - and drag the endpoint to re-size it.  The content is proportionately stretched.  Do this so that a note at the end DOES align with a barline.  All may be solved, or at least close enough so that a very small quantisation value makes it perfect.
But didn't the MIDI file import along with its tempo information?  You shouldn't have had to be TOLD the tempo was 130.1.  This setting should have been imported automatically.   Though note that tempos often are interpreted slightly differently by different programs.   A song made in Cubase at q=120 may well import to Logic as e.g. q=119.0177.   Be careful you don't mess things up by 'correcting' this.
It's also possible that it isn't quantised.  Does it need to be?  What sort of 'fixing' have you been tasked with?

Fixing off-tempo MIDI performance


How to add a row of data with EPPlus when delimiter can occur inside the cells?

Question: I'm having problems when my data contains my delmiter value, that the cells will be populated in the wrong place.
I'm exporting and importing excel data from my application. Below is a working snippet of my export. I've set my delimiter to be ';' but it causes issues if any of my properties value contains this character. Therefore I am wondering if there is a better way to load data which would allow me to use my delimiter value inside the cells.
 public void Export()
        {
            using (ExcelPackage excel = new ExcelPackage())
            {
                excel.Workbook.Worksheets.Add("Worksheet1");
                var headerRow = new List<string[]>()
                {
                    new string[] { "Id", "FirstName", "LastName",  }
                };
                // Determine the header range (e.g. A1:D1)
                string headerRange = "A1:" + Char.ConvertFromUtf32(headerRow[0].Length + 64) + "1";
                var worksheet = excel.Workbook.Worksheets["Worksheet1"];
                worksheet.Cells[headerRange].LoadFromArrays(headerRow);
                worksheet.DefaultColWidth = 20.0;

                //TODO examine delimiter
                var counter = 2;
                var format = new OfficeOpenXml.ExcelTextFormat();
                format.Delimiter = ';';
                //format.TextQualifier = '"';
                format.DataTypes = new[] { eDataTypes.String };

                foreach (Attendee item in context.Attendees.Include(attendee => attendee.Tags))
                {
                    worksheet.Cells[counter++, 1].LoadFromText($"{item.Id};{item.FirstName};{item.LastName}", format);
                }

                //Create the response
                Response.Clear();
                Response.ContentEncoding = Encoding.UTF8;
                Response.HeaderEncoding = Encoding.UTF8;
                Response.Charset = Encoding.UTF8.WebName;
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("Content-Disposition", "attachment; filename=people.xlsx");
                Response.BinaryWrite(excel.GetAsByteArray());
                Response.Flush();
                Response.End();
               }
        }

This works but if any of my fields contain ';' I will have problems. Is there some archaic delimiter value I can use or perhaps a more secure way to load my data? I could probably write two nested for loops and call load cell on every cell but that would be rather ugly as I have about 15 columns/fields in my real code. I cannot load from collection either as there are some fields that I don't want to show and they end up in the wrong order.
Answer: Why not use cell by cell?
foreach (Attendee item in context.Attendees.Include(attendee => attendee.Tags))
{
    int column = 1;
    worksheet.Cells[counter, column++].Value = item.Id;
    worksheet.Cells[counter, column++].Value = item.FirstName;
    worksheet.Cells[counter++, column++].Value = item.LastName;
}

edit - full code
public void Export()
    {
        using (ExcelPackage excel = new ExcelPackage())
        {
            excel.Workbook.Worksheets.Add("Worksheet1");
            var headerRow = new List<string[]>()
            {
                new string[] { "Id", "FirstName", "LastName",  }
            };
            // Determine the header range (e.g. A1:D1)
            string headerRange = "A1:" + Char.ConvertFromUtf32(headerRow[0].Length + 64) + "1";
            var worksheet = excel.Workbook.Worksheets["Worksheet1"];
            worksheet.Cells[headerRange].LoadFromArrays(headerRow);
            worksheet.DefaultColWidth = 20.0;

            var counter = 2;

            foreach (Attendee item in context.Attendees.Include(attendee => attendee.Tags))
            {
                int column = 1;
                worksheet.Cells[counter, column++].Value = item.Id;
                worksheet.Cells[counter, column++].Value = item.FirstName;
                worksheet.Cells[counter++, column++].Value = item.LastName;
            }

            //Create the response
            Response.Clear();
            Response.ContentEncoding = Encoding.UTF8;
            Response.HeaderEncoding = Encoding.UTF8;
            Response.Charset = Encoding.UTF8.WebName;
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("Content-Disposition", "attachment; filename=people.xlsx");
            Response.BinaryWrite(excel.GetAsByteArray());
            Response.Flush();
            Response.End();
    }
}

Comment: I actually tried exactly this, but it would not work, it still couldn't handle my delimiter value.  I ended up specifying the delimiter as ¤ so I will have to pray that nobody uses this character.
Comment: Let's say Firstname contained kalle;fdsf, fdsf would be put in the next column anyway. Maybe its a bug in the lib?
Comment: I post the full code I have in mind.  I can't figure out why this is an issue with delimiter.
Comment: I just tested it right now.  It works without any issue;
Answer: There is the ascii "VTAB" character (chr(11), 0x0B), that is probably safe to use as your delimiter, as you'll probably otherwise never encounter it outside of this :)
How many people really know how to hold down the ALT key (in Windows) and type "0011" on the keypad to enter that control character?