getView on extended ArrayAdapter always has position 0

Question: I have created a class PickedDropsAdapter that extends ArrayAdapter for a listView that lists Objects from a List
Adding and removing basically works fine except that position in getView is always 0 and I just can't figure out, why.
I found a few similar question but none of the answers was really helping
Maybe important to mention is that listView is in a Fragment which again is in a ViewPager with two pages.
PickedDropsAdapter.java
public class PickedDropsAdapter extends ArrayAdapter {

private LayoutInflater myInflater;
private List<PickedDrop> pickedList;

public PickedDropsAdapter(Context context, int resource, List objects){
    super(context, resource, objects);
    myInflater = LayoutInflater.from(context);
    setData(objects);
}

public void setData(List list){
    this.pickedList = list;
}

@Override
public int getPosition(Object item) {
    return super.getPosition(item);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView profileName;
    if (convertView == null) {
        convertView = myInflater.inflate(R.layout.picked_drop, null);
        profileName = (TextView)convertView.findViewById(R.id.profileName);
        Log.i("TAG", "Name in adapter: " + pickedList.get(position).name);
        Log.i("TAG", "Postion in adapter: " + position);
        profileName.setText(pickedList.get(position).name);
        pickedList.get(position).makeActive(convertView);

    }
    return convertView;
}
}

PickedDrop
public class PickedDrop extends Fragment {

int id, listLoc;
String name;
RelativeLayout pickedLayout;
PickedDropsFrag parentFrag = null;

public static PickedDrop newInstance(String nameParam, int idParam) {
    final PickedDrop fragment = new PickedDrop();
    fragment.name = nameParam;
    Log.i("TAG", "Drop name: " + fragment.name);
    fragment.id = idParam;
    return fragment;
}

public PickedDrop() {
    // Required empty public constructor
}

public void openDrop(){
    MainActivity mainActivity = (MainActivity)parentFrag.getActivity();
    mainActivity.openDrop(this);
}

public void openDrop(int i){
    listLoc = i;
    MainActivity mainActivity = (MainActivity)parentFrag.getActivity();
    mainActivity.openDrop(this);
}

public void makeActive(View convertView){
    pickedLayout = (RelativeLayout)convertView.findViewById(R.id.pickedLayout);

}
}

Part of PickedDropsFrag (The fragment that contains the listView)
public class PickedDropsFrag extends Fragment {
private OnFragmentInteractionListener mListener;
PickedDropsAdapter pickedAdapter;
ListView pickedListView;
List<PickedDrop> pickedList;

public PickedDropsFrag() {
    // Required empty public constructor
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    pickedListView = (ListView)getView().findViewById(R.id.pickedListView);
    pickedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            PickedDrop drop = (PickedDrop) adapterView.getItemAtPosition(i);
            drop.openDrop(i);
        }
    });

    pickedList = new ArrayList<>();

    pickedAdapter = new PickedDropsAdapter(
            getActivity(),
            R.layout.picked_drop,
            pickedList
    );

    pickedListView.setAdapter(pickedAdapter);
}

public void addToPicked(PickedDrop drop){
    drop.parentFrag = this;
    //pickedList.add(drop);
    pickedAdapter.add(drop);
    drop.listLoc = pickedList.size() - 1;

    //pickedAdapter.notifyDataSetChanged();

    drop.openDrop();
}

That should be everything important, I hope I didn't forget anything.
Answer: Update following methods in your Adapter:
public class PickedDropsAdapter extends ArrayAdapter {
    @Override
    public int getCount() {
        return pickedList.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView profileName;
        if (convertView == null) {
            convertView = myInflater.inflate(R.layout.picked_drop, null);
        }
        profileName = (TextView)convertView.findViewById(R.id.profileName);
        Log.i("TAG", "Name in adapter: " + pickedList.get(position).name);
        Log.i("TAG", "Postion in adapter: " + position);
        profileName.setText(pickedList.get(position).name);
        pickedList.get(position).makeActive(convertView);

        return convertView;
    }
}


Falha de segmentação ao printar espaço em branco C

Question: Preciso fazer uma função que retorna um porteiro para o primeiro espaço em branco encontrado na string. Quando eu tento printar o espaço em branco o programa acusa falha de segmentação, o que não acontece quando eu troco *str == ' ' por um caractere qualquer, por exemplo (*str == 'b').
#include <stdio.h>
#include <stdlib.h>

int main()
{

    char word[80];

    printf("Digite a string: \n");
    scanf("%s", &word);

    char *firstblankchar(char *str)
    {
        while (*str)
        {
            if (*str == ' ')
            {
                return str;
            }

            *str++;
        }
    }

    printf("%c", *firstblankchar(word));
}

Answer: Tem vários problemas nesse código.
O scanf() tem problemas para ler textos com espaços então troquei por algo que faz a leitura corretamente.
Não faz muito sentido retornar o primeiro espaço, mas deixei assim.
Você está somando o caractere que está manipulando em firstblankchar() mas o que deseja incrementar é o ponteiro, então não use o operador para dereferenciar, só incremente o próprio ponteiro.
O que acontece se não achar um espaço no texto? Está retornando nada, e isso não pode acontecer, tem que retornar alguma coisa. Eu mandei retornar 0 que é um ponteiro nulo. Fazendo isso o correto é testar o retorno para ver se veio 0 e não deixar usar o dado, só se vier outro endereço é que deveria acessar o caractere desejado, então coloquei o retorno, mas deixei você fazer o teste.
Veja como fica:
#include <stdio.h>

char *firstblankchar(char *str) {
    while (*str) {
        if (*str == ' ') return str;
        str++;
    }
    return 0;
}

int main() {
    char word[80];
    printf("Digite a string:\n");
    fgets(word, 79, stdin);
    printf("%c", *firstblankchar(word));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Perfeito, muito obrigada pela ajuda
Comment: Por que o 79 no fgets? Já vi varios exercicios com esse 79 mas não entendi. Porque 79 e não 80 ou 78?
Comment: Podia ser outro número e pra falar a verdade eu preferia por 80, mas pra isso eu teria que ter um buffer de 81, quando só tem 80 tem que ser 79, por causa do terminador: https://pt.stackoverflow.com/q/327101/101 e https://pt.stackoverflow.com/q/136628/101
Answer:
Preciso fazer uma função que retorna um porteiro para o primeiro
espaço em branco encontrado na string. Quando eu tento printar o
espaço em branco o programa acusa falha de segmentação, o que não
acontece quando eu troco *str == ' ' por um caractere qualquer, por
exemplo (*str == 'b')

Sua pergunta foi editada então não sei o que escreveu e o que foi alterado.
Note que se escreveu como está no texto, str='' sem espaço entre as aspas no programa isso é diferente de str=' ' que é o que você pretendia testar.
Entenda que em C *str++ soma um no valor que está em *str. Se quer incrementar o ponteiro str para que ele aponte para a próximo letra deve escrever str++. No geral esses operadores ++ e -- são mais problema do que solução, mesmo que meigos. str++ e ++str tem diferença sutil, com a qualquer ninguém deveria se preocupar se não usasse... Mas assim é.
De volta ao seu programa, e um exemplo um pouco alterado
Veja esse exemplo aqui e talvez te ajude a entender a mecânica disso em C
O programa mostra
Frase original: 'uma frase para testar o programa    '
Depois do proximo branco: ' frase para testar o programa    '
Depois do proximo branco: ' para testar o programa    '
Depois do proximo branco: ' testar o programa    '
Depois do proximo branco: ' o programa    '
Depois do proximo branco: ' programa    '
Depois do proximo branco: '    '
Depois do proximo branco: '   '
Depois do proximo branco: '  '
Depois do proximo branco: ' '
Depois do proximo branco: '(null)'
Depois do proximo branco: '(null)' :)

Eis o exemplo
#include <stdio.h>
#include <stdlib.h>

char* firstBlankChar(char*);

int main()
{
    char word[80] = "uma frase para testar o programa    ";
    char* proximo = word;
    printf("Frase original: '%s'\n", word);
    while (proximo != NULL)
    {
        proximo = firstBlankChar(1+proximo);
        printf("Depois do proximo branco: '%s'\n", proximo);
    };
    printf("Depois do proximo branco: '(null)' :)\n");
};

char* firstBlankChar(char* str)
{
    while (*str != 0)
    {
        if (*str == ' ') return str;
        str += 1;
    };
    return NULL;
};

Nesse exemplo o programa continua procurando pelos espaços e mostra na tela a string restante, até acabar a string.
Note esse folclórico comportamento do printf(): Quando o valor da string é 0, o tal NULL e que vai sair do loop e terminar o programa ele imprime
Depois do proximo branco: '(null)'

e nunca vai saber a diferença entre isso e o resultado desse comando aqui aqui
printf("Depois do proximo branco: '(null)'\n");

Claro que nem todo compilador vai fazer isso em toda situação.
Note que em geral se vai imprimir uma string que pode ter espaços ou apenas espaços é conveniente colocar algo em volta, como as aspas que usei aqui, por razões óbvias.
Evite ficar lendo coisas do teclado antes de seu programa estar pronto. Não vai aprender nada com essas linhas de printf() e fgets() e scanf() e coisas assim. Mas vai levar muito mais tempo para testar seu programa...


Possible migration to Server 2008 but with conditions

Question: I've searched the forums but nothing quite matches what we're looking for. I've read through enough forums, documentation, and other web resources, but I'm still a novice Windows Server 2008 potential user.
Setup right now with:

About 20 workstations with 5 laptops, one Terastation RAID 5 (switchable from workgroups to AD), with one Windows Server 2003 (not a DC) running Visual SVN standard.
The enterprise edition (which we are not running) is where users are able to access VisualSVN Server using their Active Directory domain credentials, but they don't want to upgrade to that version.

VisualSVN maintains its own internal user database.   If we go to a Server 2008 R2 configuration, I understand all computers and storage devices will need to be added to AD as well as the users.
My questions:

Would we be able to maintain workgroup access to those devices not added to AD?   I read in another forum that you still have access to workgroup devices, but how is that done?
Could we just use Windows Server 2008 to maintain a user database (create/delete users, change passwords) without going full AD?
Reason being is that my manager is constantly changing users passwords on their workstations because they either forget them and they don't expire out.
They also want to move the authentication from the VPN device to server 2008 to simplify management. I mentioned upgrading to AD would be the best solution, but they are adverse to the idea since they won't have a full time domain administrator.
They're also not interested in the security aspects of AD aside from the passwords for user accounts.
Would it still be wise to turn on scavenging for DNS (if we do upgrade to Server 2008 AD) if there are no more than 5 laptops that are connected and disconnected from the network?

I'm sure I'll come up with more questions later, but until then, any answers would be appreciated.
Answer: This is a really open ended question. It feels like you're basically asking "how do I architect my IT infrastructure?"
That being said I'd still like to try to help.
I would recommend Active Directory. Now your quote "Secondly, could we just use Server 2008 to maintain a user database (create/delete users, change passwords) without going full AD" is pretty much the definition of AD LDS (formerly ADAM, uses LDAP, etc...) but just use AD. When you are logging on to a Windows workstation there are two possibilities - you either authenticate to the local SAM on that machine, or you authenticate to an Active Directory.  Plus you'll actually find it easier to get help with vanilla AD problems because it's so much more common.
It's ridiculous for you or your boss to have to walk around the office changing people's passwords on their workstations.
Yes, you can still communicate with devices outside of your domain, but it will not be single-sign-on.  You simply have to authenticate separately to a device that is outside of your domain.
You'll also have to design a DNS structure that includes DNS records for devices that are in workgroups or other domains. (Research GNZ or GlobalNames for that.)
edit:  Didn't see your last question about scavenging. I would say it's fine to turn it on. I don't know your DHCP situation or subnet(s), but if you have clients connecting and disconnecting from the network all the time, such as a laptop, you'll end up with lots of stale DNS records in your zone if you don't enable scavenging, because they'll keep getting new DHCP addresses and registering new DNS records.
Comment: Thanks Ryan, a few more questions.  If I do set Server 2008 as AD, would I have to add the workstations to the domain for them to be able to login with their credentials from that workstation? As for the storage devices outside the domain, if they are set as public, would they access them without credentials? Sorry if they seem basic, but I'm still at the research stage at the moment.
Comment: Yes. There would be no point in standing up a domain with a domain controller, if you didn't then join your workstations to that domain.  As for your storage devices, I don't know what they are but if you can access them now with no authentication, you will not have to do so once you're inside a domain either. If you have to supply credentials to them now, you will still have to do so once you are inside a domain. That is of course unless you can get the storage devices to join the domain with you.
Comment: Final question hopefully. You mentioned GNZ but isn't that mainly concerned with transitioning away from WINS?  Can't the workgroup resolve to the server 2008's DNS?
Comment: Yes, the workgroup computers may use the domain controller as their DNS server.  However, they will not have the ability to register their own names in the domain DNS zone because they're not part of that domain. You could create "fake" A records in your domain DNS zone that resolve to the IP addresses of the workgroup computers, but that is bad behavior and I don't recommend it. The GNZ is to help get away from WINS when for legacy reasons you still need to resolve some old hosts by single label name.
Comment: That said, if everything is on the same subnet, you will probably still be able to resolve the names of the workgroup computers from inside the domain because it will fail back to NetBIOS. Hopefully.
Comment: But they will still be able to accesst those devices via their IP addresses correct? edit: To fall back to NETBIOS would WINS need to be added to 2008?
Comment: If not having name resolution is good enough for you, then yeah IP addresses will still work.  ;)


Line integral of$ \int_c \frac{dz}{(1 - z )^3}$ , where $ C$ is circle $|z| = \frac{1}{2}$

Question: (a) Iintegral of$ \int_c \frac{dz}{(1 - z )^3}$ , where $ C$  is circle $|z| = \frac{1}{2}$
I try with
put $u =1-z $ then $du =-dz$
$\int (-du/u^3)= 1/2u^2$
is that correct ??
(b) Integral of$\int_c\frac{e^z}{(1 - z )^3 } dz $, $C$ is circle $|z - 1| = 1/2$
this not understand it
Answer: (a) $f$ is analytic in $|z|=\frac{1}{2}$. So the integral is $0$ ( by Cauchy's theorem) .
(b) $f$ has a pole of order $3$ at $z=1$. So by Cauchy's theorem , given integral $=\frac{2\pi i}{2!}g''(1)$ , where , $g(z)=e^z$.


Laravel 5 wildcard subdomain + route model binding

Question: So when you define a resource controller in a wildcard subdomain group route similar to this:
Route::group(array('domain' => '{subdomain}.example.com'), function() {
  Route::resource('users', 'UserController');
});

on RouteServiceProvider
$router->model('user', 'App\User');

and on the UserController show method:
public function show($user)
{
    return $user;
}

what i get is the subdomain name instead of the user resource. This is because the subdomain parameter is passed to controller methods and i would have to change them like this:
public function show($subdomain, $user)
{
    return $user;
}

I simply don't want to add the subdomain parameter to each and every controller method in my app because i am not going to do anything with it. I use the subdomain parameter in a middleware to do some configuration changes.
How can i do it so the subdomain doesn't get passed to controllers as parameter?
Comment: I gave up and ended up including the subdomain parameter on every controller method. Came up to be handy for some cases though. Especially when i needed to pass the parameter to the views.
Comment: Were you able to find any solution for this?
Answer: I'm aware that this question is somewhat old (and potentially stale) although I stumbled across this post when searching for an answer to another route model binding question.
To avoid requiring the subdomain, you can specify that Laravel forgets that route parameter.
You could either do this in a middleware (which checks for the subdomain too), like so:
$request->route()->forgetParameter('subdomain');

Alternatively, using your code snippet, it would look something along the lines of this:
Route::group(array('domain' => '{subdomain}.example.com'), function() {
  Route::forgetParameter('subdomain');
  Route::resource('users', 'UserController');
});

However, I'd strongly recommend that the process is moved into a middleware, as it doesn't feel right putting that in the routes file.
Answer: In your controller function you can ignore the $dubdomain if you do not use it and make sure you typehint the User like this
public function show(User $user)
{
    return $user;
}

Comment: Thank you Margus. That makes sense but it doesn't feel like a good way of doing it. It may cause confusion for nested resources. I prefer to simply make router ignore the subdomain parameter.
Comment: I just tested and you can ignore the $subdomain if you do not use it. As you have User then you need to typehint it to be resolved.
Comment: I get `Argument 1 passed to App\Http\Controllers\UserController::show() must be an instance of App\User, string given` when i typehint User. Assuming that string is the subdomain passed.
Comment: It must be something related to model binding then and needs deeper investigation. I am able to typehint and get resolved Eloquent Model values and skip other url params.
Comment: @MargusPala how to solve it if there is a model binding on route service provider? Perhaps you have this `$router->bind('users', function($id) { return \App\User::findOrFail($id); });` and on methods there is already the type hint doSomething(User $user) { ... again laravel asks for object and the subdomain is taking place of it.


Definite integral of terms

Question: $\int _{\frac{-\pi}2}^{\frac{\pi}2} [2\sin |x| + \cos |x|] dx $
As this integral contains greatest integer function and magnitude function. So I have no clue to how to solve.
Any hint is appreciated. Thank you.
Comment: Maybe the plot of the integrand will help. [WA](http://bit.ly/2lcemQ4)
Comment: I know that but I want to know steps. As WA not shows any steps.
Comment: Do you where value changes from 1 to 2 for inner expression
Comment: @Archis Welankar please help me to solve this.
Comment: The first step is to break the interval of integration into the two parts, $[-\pi/2,0] \cup [0,\pi/2]$.  You will then find the integrand simplifies in each part (and indeed, the two parts are symmetric).
Answer: Since $|x|$ changes sign at $x = 0$, split the integral into two parts. $|x| = -x$ for $x <0$ and $|x| + x$ for $x \geq 0$.
For $a < 0, b > 0$
$$\int_a^b f(|x|) = \int_a^0 f(-x) + \int_0^b f(x)$$
Then use properties of sine and cosine to simplify further.
Comment: What about greatest integer function?
Answer: Let $\varphi(x)=[2\sin |x| + \cos |x|]$.
As  $\varphi(-x)= \varphi(x)$, $\varphi$ is an even function. Thus the integral to be computed is
$$\tag{0}2\int_{0}^{\frac{\pi}{2}} [2\sin |x| + \cos |x|] =2\int_{0}^{\frac{\pi}{2}}  [f(x)] dx$$
with $f(x):=2\sin(x) + \cos(x).$
It is very important to situate the abscissa of the jump. To have a clear idea of it, one needs to plot the curves of $y=f(x)$.  See figure below (where the other part of the curve of $y=\varphi(x)$ is represented as well).
let:
$$x_0=2 \tan^{-1}(1/3)\approx 0.6435. \ \ \text{(Explanation at the bottom)}$$
For $0<x<x_0$, $[f(x)]=2.$
For $x>x_0$, $[f(x)]=3.$
Thus, using (0), the result is obtained by computing the area of 2 rectangles:
$$2(2 x_0+3(\dfrac{\pi}{2}-x_0))=3 \pi-2x_0=3\pi-4 \tan^{-1}(1/3)$$

Explanation of the result in (1): We have to find the solutions of
$$\tag{2}2\sin(x)+cos(x)=2.$$
Using Weierstrass substitution formulas (https://en.wikipedia.org/wiki/Tangent_half-angle_substitution), (2) is equivalent to:
$$\tag{3}2\dfrac{2t}{1+t^2}+\dfrac{1-t^2}{1+t^2}=2.$$
whence quadratic equation $3t^2-4t+1=0$ with solutions $t=1$ corresponding to $\pi/2$ and $t=1/3$. Thus, as $t=tan(x/2)$, $x_0=2 \tan^{-1}(1/3)$.
Comment: @Amar I see you have asked 9 questions today and yesterday, and today especialy you have asked 4 questions in a few hours. Consider it is too much. It is not the way you will progress in mathematics. Moreover, you have been helped a lot. Answer to our questions by "please help me" is definitely not an adult attitude. You should react to the answers that are provided to you and say, "I don't understand" this, or, at the opposite, "This answer is convenient" (in this case, it has to be validated). You must have a dialog with us. Math S.E. is not a "quick serve" "(not)pay and carry"...
Comment: Why not to use the fact that the function is even .
Comment: In fact, I was just modifiying my answer in order to take this fact into account from the beginning:)
Comment: Can you please provide solution without graphically.

Definite integral of terms


How does matrix multiplication work when you have two parenthesis of two calculations?

Question: How do I calculate the following example:
$$(\lambda A-I)(\lambda A-I)$$
where A is any $n\,x\,n$ matrix of the same size as $I$? Do I multiply as regular algebra or what?
Is is:
$$(\lambda A)^2-2\lambda A + I$$
Why, why not?
Edit:
Or for the example
$$(A-2BC)(A-2BC)$$
where $A, B, C$ are three $3\,x\,3$ matrices.
Comment: It does work that way for this example. However usually one needs to note not all matrices obey $AB=BA$. So for instance, if I have $A, B$ matrices, $(A+B)^2$ is not usually $A^2+2AB+B^2$, rather, we would have $A^2+AB+BA+B^2$
Comment: The reason I am asking is because in my textbook one of the equations is solved by simply multiplying the left side parts with the right parenthesis: (A-B)(A-B) = A(A-B) -B(A-B)
Comment: For the edited example it would be $A^2-2BCA-2ABC+4B^2C^2$
Answer: Matrix multiplication is distributive but since order matters you have to be careful not to commute any of the elements. Lets look at the example $(A-B)(C-D)$ since it's more general and assume all the matrices are square. We can do this two ways. First we can calculate $$(A-B)(C-D)=(A-B)C -(A-B)D=\\AC-BC-(AD-BD)=AC-BC-AD+BD$$
Or we could have distributed the other way with $$(A-B)(C-D)=A(C-D)-B(C-D)=\\AC-AD-(BC-BD)=AC-AD-BC+BD$$
And we can see by inspection that they are the same regardless of our choice in left or right distributivity.
Comment: Ahhh yes, now I can see how he got $A(C-D)-B(C-D)$, I went one step too far. Thanks a lot!
Comment: Small note: it doesn't change anything if these matrices are not square, as long as they are of the right sizes for the operations to be defined. (And if they are in any of these expressions, they also are in all the others.)
Comment: I am also confused about: $(AA^t)(AA^t)=A(A^tA)A^t=A(I)A^t=AA^t$, is this actually correct?
Comment: @linker $A^tA=I$ is only true if $A$ is an orthogonal matrix.
Answer: Remember how matrix multiplication is defined:
Given a matrices $\mathbf A$ and $\mathbf B$ of size $m\times n$ and $n \times p$, we define the product $\mathbf C = \mathbf {AB}$ as the matrix of size $m \times p$, whose entries, $c_{ij}$ are given by the dot product between the $i$th row of $\mathbf A$ and the $j$th column of $\mathbf B$.
That is
$$
c_{ij} = \sum_{k=1}^{n} a_{ik}b_{kj}.
$$
Using this definition, we can satisfy ourselves that matrix multiplication does distribute over addition. Given matrices $\mathbf{L}$, $\mathbf{M}$ and $\mathbf{N}$, of suitable sizes, the product $\mathbf{L}(\mathbf M + \mathbf{N})$ will have coefficients given by
$$ \sum_k l_{ik}(m_{kj} + n_{kj}) = \sum_k l_{ik}m_{kj} + \sum_k l_{ik}n_{kj}$$
The two terms on the right are the coefficients of $\mathbf {LM}$ and $\mathbf{LN}$ respectively, and we conclude that $\mathbf{L}(\mathbf M + \mathbf{N}) = \mathbf{L}\mathbf M + \mathbf{L}\mathbf{N}$


Should loop based songs conform to whole measures?

Question: I've been doing some loop based compositions lately. And I was wondering if I should conform to measures or is it ok not to.
Sometimes when I'm loop recording I don't really bother to look at how many beats or measures were recorded as I am looping on a hardware based looper (boss rc-202) so I could stop the loop recording whenever I want and it immediately loops on it (although there is a setting that forces a loop to whole measures, that's if I set the bpm and turn on the metronome). Subsequent loops are then just a multiple of the time of the base loop and I stitch all these loops together eventually (.wav files) to create a song.
I don't really mind if they're not whole measures, I prefer it because then the loop stops immediately and doesn't have to wait until it gets to a whole measure to stop. But I was wondering if it's ok to do that.
Comment: If you intend on making compositions that sound like EDM, then I must tell you that EDM strongly does not tend to change time signatures, so you're stuck with whole measures.
Comment: I agree with a lot of the below. Make it however you like. However keep in mind it may not be listenable. But it depends on your goals. Want to make people dance? Go with a steady 4/4. Want to make art? Do whatever you like.
Answer: It's certainly simpler to "conform to whole measures," but this can also result in songs that sound repetitive, predictable, or "blocky." I'd also point out that the concept of a "measure" can vary dramatically in orchestral scores. A lot of classical music switches time signatures frequently. A song might start in 5/4 and switch to 3/2 or 2/2 or 4/4.
I would say that you shouldn't let one time signature constrain your creativity. It might make it more complicated to rearrange parts or you may find it tricky to teach other folks how to play a tune when rehearsing, but mixing up your time signatures can give your music a more sophisticated structure. It might be a bit weird on the first few listens, but the song might seem interesting for longer because if its unusual rhythmic structure.
Comment: I agree with this answer. Mind that there are often notated ritardandos, fermatas and even accelerandos or general breaks.
Comment: @AlbrechtHügli yes! translated to more contemporary terms, a beat drop or birds eye might be of indeterminate length. I'd further add that tempo often wanders in live performances. Even the most highly trained performers play faster or slower than a perfect metronome. https://www.youtube.com/watch?v=L8wHteSOwW4
Answer: Use whatever technique produces the sound you want.  Regularity is good.  Irregularity is also good.
Comment: Yes, fully and concisely, in the first sentence.  It doesn't waffle on pointlessly though.
Comment: This covers most bases. But does it really answer the question?
Answer: You can obviously do exactly as you wish. However, when trying to put it all together, it won't just be a matter of going from, maybe, 4/4 to 3/4 or whatever. You'll have fractions of bars to join, which will make the whole sound pretty amateur. Imagine a track where you start tapping a foot, and suddenly it's out of time. That will be going on all through.
I know some music varies time signatures bar to bar, but even so, before the next bar comes in, at least the previous bar is completed!!
If you want to make stuff that sounds avant-garde then carry on. But I'd have thought you might have realised how bitty the final mix sounds already.
I use a looper on occasions, and yes, it takes some doing to stop/start exactly in time, but that's really what it's about. More work needed!
Comment: There is a [counterpoint](https://www.youtube.com/watch?v=AFaRIW-wZlw) to "highly quantized" music.
Comment: I don't think it would be possible for the song to suddenly be out of time as you said with tapping the foot. because the whole thing relies on the base loop. as long as the base loop sounds good then all the other loops are just multiples of it in length. I just meant the base loop could be variable in length (not necessarily a whole measure in 4/4 time)
Comment: That is the whole point. Unless i'm missing some information.


Body field doesn't display in any view mode

Question: I inserted some articles in my Drupal 7 site, the body field  doesn't display, the manage display setting is ok, I tried to change the theme.
Even though I still to display it in edit mode.
One thing is that I imported this content type with bundle copy , it's the same Article default content type with some custom fields.
Comment: Are you using the Panels module?
Comment: no, I'm not using it
Comment: what is text format of the body ? full_html ,formatted_html or  plain text ...?
Comment: @zhilevan filtred_html
Comment: @learner123  try to `var_dump($node->body);` (or if you install devel module  `dpm($node->body);`  and write result in question for additional details.
Comment: @zhilevan plz see the screeshot above
Comment: @learner123 it seem's ok , are you  sure you didn't select summary in display manager? plese sure that you not select summary (becasue summary is empty).  also try  `dpm($content);` . I think prlbelm is only in displaying
Comment: @zhilevan no, I didn't http://s32.postimg.org/6lpifxk5h/Selection_003.png
Answer: I deleted the body field and I recreate it again. that's slove my problem, while I have not yet had any contents
I didn't find a second solution


Why is $form_state always empty, even when my form-building-function is called after validation?

Question: I'm having a little trouble with the terminology here, so I'll explain my problem directly with code samples (trucated for clarity).
myModule.module
Here I create a menu with a link to a form built using a function declared in form_identification.php
[...]
require_once(dirname(__FILE__) . '/form_identification.php');
[...]
function myModule_menu() {
    $weight = 1;
    $items = array(
        'identification' => array(
            'title' => t('Identification'),
            'page callback' => 'identification_callback',
            'access arguments' => array('Acces myModule'),
            'type' => MENU_NORMAL_ITEM,
            'weight' => $weight++
        ),
        [...]
    );
    return $items;
}
[...]
function identification_callback() {
  return drupal_get_form("form_identification");
}
[...]

form_identification.php
This file holds the function which builds the form, called form_identification

function form_identification($form_state) {

    error_log("form_state: " . print_r($form_state, true));
    // always outputs `form_state: Array\n(\n)\n`

    $form = array(
        '#attributes' => array(
            'enctype' => 'multipart/form-data'
        ),
        'sex' => array(
            '#type' => 'textfield',
            '#title' => t('Sex'),
            '#disabled' => true
        ),
        /*[...]*/
        'enregistrer' => array(
            '#type' => 'submit',
            '#value' => t('Enregistrer'),
            '#submit' => array('form_identification_enregistrer')
        )
    );
    return $form;
}

function form_identification_validate($form, &$form_state) {
    /*[...]*/
}

function form_identification_enregistrer($form, &$form_state) {
    /*[...]*/
}

As you can see, I'm printing the contents of $form_state to the log every time form_identification is called, so I can confirm that the function is called on page load and also after validation. The problem is that in both cases, I just get an empty Array (Array\n(\n)\n). I would have expected to get an array full of form info when the function is called after validation. That way, I could have a look at the values entered and decide how to build the form based on them. Is there any way to achieve this? In what situation would $form_state NOT be an empty array?
Answer: You've just got the signature for the form function slightly wrong, it should be:
 function form_identification($form, &$form_state) {

The first arg that's passed to your form function by the form builder is the $form, which for a new form is pretty much always an empty array.
Comment: I would also point out that in the validate and submit callbacks, $form is passed by reference and should be set as an argument like `&$form`.


Erro ao executar o comando yarn start/ npm start

Question: Assim que executo o comando create-react-app e faz criação do projeto. no final quando eu vou executar o comando "yarn start". segue o seguinte erro:
yarn run v1.22.4
warning package.json: No license field
error Command "start" not found.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Ja tentei várias coisas como, deletar a pasta node_modules, deletar o yarn.lock, deletar o package.json, desinstalei e instalei o node de novo. Não sei o que aconteceu, pois um dia atrás eu estava rodando o comando normalmente.
Comment: Tenta  rodar o comando ```yarn``` na pasta do projeto (apenar o yarn, depois o comando completo)
Comment: Como é um comentário à minha resposta, não crie uma nova resposta para a pergunta, comente na minha resposta que já fez isso e ainda assim não funcionou. Aproveita e edita a sua pergunta com mais essas informações e inclusive adicione o package.json, uma vez que a mensagem de erro aponta para ele.
Comment: Eu estava com o mesmo erro, tentei de algumas formas , mas resolveu quando reiniciei o VsCode.
Comment: Eu exclui da maquina as pastas npm/yarn e quando executei o comando create-react-app, funcionou! Acho que havia alguma problema com aquelas pastas. Assim que eu criei uma nova aplicação react, foi instalado na maquina uma nova pasta npm e desde então, não tive mais problemas. Agradeço todas as sugestões! Muito obrigado!
Comment: Ola!
Pode parecer bobo, mas eu estava tendo esse mesmo problema e tudo o que eu fiz foi fechar o programa (vscode), e reabri. Me certifiquei de que estava dentro da pasta correta do projeto (web) e fiz o processo de novo. Deu certo. No meu caso foi apenas falta de atencao. Espero que seu problema seja tao simples quanto foi o meu. Abraco!
Answer: Nesses casos, procure incluir o passo a passo executado na sua pergunta. Pela descrição do problema, o mais provável é que vc tenha criado o projeto e não tenha entrado na pasta do dele.
Seguindo a documentação do react:
yarn create react-app my-app
cd my-app
yarn start


On which structures does the free group 'naturally' act?

Question: One of the best ways to get a handle on a group is to recognize it as isomorphic to a set of symmetries of some structure. The dihedral group of order $2n$ is easily recognized as the set of symmetries of a regular $n$-gon, the symmetric group as the permutations of a set, the Klein-four group as the symmetries of the 'cross'---one pair of opposing prongs are longer than the other pair.
The previous descriptions are also in a sense 'exhaustive': every 'sensible' symmetry you could conceive of those structures is represented by some element of the group. An example where the group is not exhaustive over its structure is $C_n$ over the regular $n$-gon (reflection is missing), or $A_n$ over the set of $n$ elements.
I wish to know of a structure that a free group---specifically $F_2$---naturally acts on which it is also in a sense 'exhaustive'. I'm aware of $F_2$'s Cayley graph, but I want other examples.
EDIT
The question may have been a bit unfair and imprecise, but I can't help that it is really.
One of the reasons it may be unfair is that 'exhaustive' is a bit subjective. For example, I myself cannot point out a structure that $C_n$ naturally acts on that $D_{2n}$ could not be conceived of as acting on also; however, both of these groups also sit in $S_n$ in a more-or-less canonical fashion. But there are structures, such as polygons, that we think of as $D_{2n}$ acting on naturally rather than $S_n$.
I'm trying to find structures such that when we think of their 'natural' set of symmetries, the group of these symmetries would be isomorphic to a free group. I want a
couple of examples, as I'm slightly disappointed in having only the Cayley graph or finite tuples of words as a reference. Other groups have many examples of acting on a structure. For example the Klein four group could also be realized as the symmetries of a proper rectangle, $A_4$ can be realized as the rigid motions of the tetrahedron rather than the even permutations of a 4-element set.
I also don't want these examples to be 'cheap'. What I mean by this is that the action is not arrived at by quotienting by a normal subgroup to get an action that is more properly realized by another group.
Comment: @commentors: Have you read the question carefully?
Comment: The free group on $n$ generators acts on _anything_ that has $n$ specified automorphisms.
Comment: Just an idea: Take the set $X = \operatorname{conv}(\{e^{k\frac{2\pi i}{\sqrt{2}}}|k\in\mathbb{Z}\})$, and let $a^n\in F_1$ act on $X$ by multiplication with $e^{n\frac{2\pi i}{\sqrt{2}}}$. I doubt $X$ has any symmetries other than by rotation, though I'm not sure how to prove it (which is why I made this a comment). You can generalize this to $F_k$ by taking the $k$th cartesian product, and let the generators of $F_k$ act componentwise.
Comment: Are fundamental groups too far from "symmetries"?  Because one can obtain free groups as fundamental groups of wedge sums of circles: http://en.wikipedia.org/wiki/Fundamental_group#Free_Groups_of_Higher_Rank
Comment: Free groups can be viewed as subgroups of $GL_2(\mathbb{Z})$. This means that they act on the abelian group $\mathbb{Z}\times \mathbb{Z}$, as well as on the plane $\mathbb{R}\times\mathbb{R}$. However, in neither case is the free group the whole automorphism group. But what we can learn from this action is that free groups are residually finite: automorphism groups of finitely generated, residually finite groups are residually finite (this is a $10$-line proof), and then $\mathbb{Z}\times\mathbb{Z}$ is f.g. and r.f. so it automorphism group, $GL_2(\mathbb{Z})$, is r.f. Thus, $F_2$ is r.f. QED.
Comment: Of course a free group *naturally act* on the set of strings on the generators: which is the Cayley actions, nonetheless I suppose you weren't interested in such trivial action.
Comment: They certainly act on trees - there is a big theory of groups acting on trees developed by Serre and others - but I think that is the same as the action on the Cayley graph, which is itself a tree of course. My guess is that all faithful actions are on structures that are similar (quasi-isomorphic perhaps?) to trees for the general informal reason that any features of the structure being acted on are likely to imply conditions on the acting group, and free groups are essentially groups with no conditions.
Comment: @ZhenLin true, but the question only makes sense if you restrict attention to faithful actions, and the wording of the question suggests that is what he is looking for.
Comment: @MannyReyes it's not quite what I'm looking for, but I do like that. If we considered symmetries of the figure-eight to accommodate for bending, turning, stretching, and self-overlapping I can see how that works. I'm looking for something more 'rigid'. I thought about the Koch snowflake 'grown from a line' where one generator would shrink and overlap on the right, and the other generator would shrink and overlap on the left. But these operations are not quite symmetries and only form a monoid.
Comment: @roman the set you provide is a good example. if you take the elements around $S_1$ that you mention and adjoin a reflection you get the infinite dihedral group (under complex multiplication) which is isomorphic to $\mathbb{Z}\times\mathbb{Z}/2$. That's quite a polygon.
Comment: Since the OP is "looking for something more rigid", I think @DerekHolt is right. If a group $G$ acts isometrically, cocompactly and properly discontinuosly on a proper geodesic metric space $X$, then $G$ and $X$ are quasi-isometric (Milnor-Svarc Lemma). Since $G$ acts like that on its Cayley graph (which is a tree), any such space with such an action will be quasi-isometric to that tree.
Answer: $F_2$ acts on a certain tiling of the hyperbolic plane. It looks sort of like this:

The above tiling is acted on by the modular group $\Gamma \cong \text{PSL}_2(\mathbb{Z})$, which naturally sits as a subgroup inside of the full group $\text{PSL}_2(\mathbb{R})$ of isometries of the hyperbolic plane. Abstractly, this group is the free product $C_2 \ast C_3$. It has congruence subgroups $\Gamma(N)$ given by the image of the kernel of the quotient maps $\text{SL}_2(\mathbb{Z}) \to \text{SL}_2(\mathbb{Z}/N\mathbb{Z})$ in $\Gamma$. For $N \ge 2$ these groups act freely on the hyperbolic plane, and the topological structure of their quotients are known (they are uncompactified modular curves, all of which will be compact Riemann surfaces minus finitely many points, and both the genus and the number of points removed are known). In particular, $\mathbb{H}/\Gamma(2)$ is known to be $\mathbb{R}^2$ minus two points, which has fundamental group $F_2$. Hence
$$\Gamma(2) \cong F_2$$
acts on the hyperbolic plane $\mathbb{H}$. You can find a fundamental domain for this action by taking a union of finitely many fundamental domains for the action of $\Gamma$ (pictured above), and this gives a tiling of the hyperbolic plane whose automorphism group should be exactly $\Gamma(2)$ (I think).
Groups that arise in this way can be thought of as hyperbolic analogues of wallpaper groups.
In general, an interesting way to find an interesting space on which a group $G$ acts is to find a space $X$ with $\pi_1(X) \cong G$ and look at the action of $G$ on the universal cover $\tilde{X}$, especially if $X$ has extra structure for its universal cover to inherit. In the case of $F_2$ we can pick $X$ to be the wedge of two circles and this reproduces the action of $F_2$ on its Cayley graph, but for other kinds of spaces $X$ we get more interesting spaces. Above we instead pick $X$ to be $\mathbb{R}^2$ minus two points and get an action on the hyperbolic plane; this is a special case of uniformization.

Edit: Perhaps an easier description of what I'm talking about is in terms of the von Dyck groups. In the Poincaré disk model the relevant tiling looks like this:

$F_2$ is (Edit:) the group of orientation-preserving symmetries of this tiling that can be obtained by rotating around the vertices of any of the triangles in it. (The original statement that was here was wrong; the tiling above clearly admits a rotational symmetry of order $3$, but $F_2$ has no torsion. The resolution is that this rotational symmetry fixes the origin, which is not a vertex.)
Comment: Regarding a side comment in the OP, $C_n$ acts on an oriented $n$-gon. There are various equivalent ways to describe what an orientation is here; one way is to think of it as a consistent orientation of the edges so that they all point clockwise or all point counterclockwise.
Comment: It should be pointed out that these groups are called Fuchsian groups. They play an important role in, for example, studying the structure of hyperbolic groups (which are groups whose coarse structure "looks" hyperbolic), as hyperbolic groups can be split as a graph of groups in a canonical way over virtually-cyclic subgroups, and then vertex groups are either (bounded) Fuchsian or have finite outer automorphism group. This yields information about the outer automorphism groups and the model theory of hyperbolic groups, and has led to the resolution of the isomorphism problem for them.
Comment: @QiaochuYuan: To picture $F_2$ acting here you need to take the union of two adjacent (white and back) triangles;  let's call it a "quadrilateral" $Q$. Call the sides  of $Q$: $A, B, C, D$ (in cyclic order); where $A, B$ are on "white" side and $C, D$ are on the "black" side. One generator $g$ of $F_2$ will "rotate" $D$ to $A$, while the other $h$ will "rotate" $C$ to $B$. When you glue the corresponding sides of $Q$ via these "rotations", you will get a triply punctured sphere (with the fundamental group $F_2$, of course). Hence, $g, h$ indeed generate a free subgroup of rank 2.
Comment: @Alex: it's from Wikipedia. I added links to make this clearer.
Comment: It wouldn't have mattered if it were from a calculus textbook--it's still a nice picture of a disk :)
Comment: I'm having a hard time picturing the generators for $F_2$ from this picture. I can see how you can rotate the center hyperbolic triangle around one of its vertices to match up with one of the 'smaller' hyperbolic triangles on the same vertex, and this drags one of the other black triangles 'up' to become the new 'center'. But I do not see the other independent symmetry that generates the rest.
Comment: @Bryan: I think the group is generated by the rotations around the vertices of any fixed triangle. These rotations, suitably oriented, should have product $1$, so the group is really $\langle x, y, z | xyz = 1 \rangle$ but this is just $F_2$. I'm also having kind of a hard time picturing this though.


MathJax not displayed properly

Question: Lately I've been seeing expressions rendered by MathJax not displayed properly: they all have a vertical bar at the end. See image below. This occurs for both inline and display math expressions, in the post as well as in comments.

This seems to be unique to Econ.SE site. Math.SE doesn't seem to suffer from this issue:

Is this just me? I'm using Version 48.0.2564.82 of Chrome.
Comment: I did not experience the problem with Chrome 47.something and neither after updating to 48.0.2564.97.
Answer: This is an issue specific to Chrome 48 (possibly, not on every OS). It has been reported and fixed in MathJax 2.6.0 which was released recently.
It's possible you may have an older version of MathJax cached in your browser. Check the version that is displayed by right-clicking an equation and selecting "about MathJax".
You wouldn't see this on Math.SE because Math is on the beta channel of MathJax, unlike other SE sites. (It loads the script from beta.mathjax.org)
Comment: Thanks! My MathJax is v2.5.3. That's why.

MathJax not displayed properly


Custom Post Type Not Accepting Page Variable

Question: I have created a custom post type using PODS
The URL ends up being:
http://example.com/dj/dj-name
The dj has an author field that I am using to query the DJ's posts.
The url for next_posts_link(); ends up becoming /dj/dj-name/page/2 as one would expect.
After clicking the link wordpress seems to be ignoring the /page/2 and just redirecting back to /dj/dj-name
My permalink structure is: http://example.com/sample-post/
When I use default permalink structure /?dj=dj-name&paged=2 it works correctly.
Any ideas?
Comment: what is the value of `$paged`?
Comment: @celeriko it never gets to that point because wordpress redirects back to /dj/dj-name
Comment: it does get to that point, or else the query would not be executed and there would be nothing displayed on the page.
Comment: @celeriko It get's to that point if I am on /dj/dj-name...  However when I go to /dj/dj-name/page/2 it is NOT that it is displaying data from /dj/dj-name it is PHYSICALLY redirecting me to the url /dj/dj-name... Does that make more sense?
Answer: In your PHP file, do you assign $paged to anything? View Pagination Codex
Above your query, probably right below your get_header() you need to add something like this:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
If that doesn't work you can try saving your Permalinks again (Settings -> Permalinks -> Save Permalinks). This will refresh your current permalink structure.
Finally, if you have a page called "dj-name" already created, you can run into problems because WordPress can't differentiate between a subpage called page/2/ and a pagination link page/2/
Comment: Yes I do have that up at the top. Again the issue is wordpress is sending me back to /dj/dj-name as if /dj/dj-name/page/2 is an invalid URL
Comment: Maybe if you move the `` before the `endif;`
Comment:  is generating the proper link. Upon clicking it when I view source. Upon clicking it, wordpress **redirects** me back to /dj/dj-name.
Comment: Did you try moving it before the endif? It may be generating the correct link, but not the corresponding query since it is a custom one.
Comment: Yes, still the same result. Even if I type the proper in the URL bar. It redirects back.
Comment: On a side note, you really should use WP_Query instead of [`get_posts()`](http://codex.wordpress.org/Function_Reference/query_posts) since WP_Query is faster and you have more control. Are you 100% sure there's more than 1 page? Maybe if you pass max num pages into your next_posts_link() -> `max_num_pages ); ?>`
Comment: Turns out you can't use WP_Query at all with what I was trying to do. Fix is below.
Answer: Pagination only works on archive pages such as index.php, category.php, archive-posttype.php etc.
You can make it work on single.php or similar pages but you need to hijack the built in redirect function, see below...
function dj_redirect_hack($url) {
    if ( is_single() and get_post_type() == 'dj' ) $url = false;
    return $url;
}
add_filter('redirect_canonical','dj_redirect_hack');


How to populate a ManyToMany relationship using YAML on Play Framework 2.1.x

Question: I have the following ManyToMany (bidirectional) relationship:
@Entity
public class Proposal extends Model {
    ...
    @ManyToMany
    public List<Tag> tags;
}

@Entity
public class Tag extends Model {
    ...
    @ManyToMany(mappedBy="tags")
    public List<Proposal> taggedProposals;
}

And I want to populate my DB with some test data using a yaml file (to display later using a simple view). This is part of my yaml file:
...
- &prop2 !!models.Proposal
    id:         2
    title:      Prop2 title
    proposer:   *user2

- &prop3 !!models.Proposal
    id:         3
    title:      Prop3 title
    proposer:   *user3

# Tags

- &tag1 !!models.Tag
    name: Tag1 name
    desc: Tag1 description
    taggedProposals:
        - *prop1

- &tag2 !!models.Tag
    name: Tag2 name
    desc: Tag2 description
    taggedProposals:
        - *prop2
        - *prop3

The problem is that when I try to display a Proposal's tags or a Tag's taggedProposals, the ArrayLists are empty! I tried using square brackets and commas without success. All the other data is being loaded and displayed correctly.
Answer: The problem you have encountered happens because play uses ebean and ebean doesn't automagically saves many-to-many associations.
I had to solve it this way:
private static void initialData() {
    @SuppressWarnings("unchecked")
    Map<String,List<Object>> all = (Map<String,List<Object>>) Yaml.load("initial-data.yml");

    // Save all roles
    Ebean.save(all.get("roles"));

    // Insert users and for every user save its many-to-many association
    Ebean.save(all.get("users"));
    for(Object user: all.get("users")) {
        Ebean.saveManyToManyAssociations(user, "roles");
    }
}

And the yaml file:
# Roles
roles:
  - &adminRole !!models.Role
    name: admin

  - &projectleadRole !!models.Role
    name: projectlead

# Users
users:
  - &leonUser !!models.User
    email: email@example.com
    roles:
     - *adminRole
     - *projectleadRole
    firstName: Leon
    lastName: Radley

Comment: Unfortunately that didn't work. I adapted your code and I get a NullPointerException when trying to save the relationships. My yaml (http://chopapp.com/#bt5pwjvk) and the loader method (http://chopapp.com/#qy5dfec1)
Comment: It could be that you need to add CascadeType.PERSIST to your collection.

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
 public List roles = new ArrayList();
Comment: I added `@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)` to my `Proposal` (equivalent to your Roles) but the problem remained...
Answer: If the answer posted by Leon Radley was accurate, it is no longer the case !
Play evolved and, since the 2.1 version, manyToMany reference initialization by list now work (see this link) ! See User.zones for an example of how it works.
zones:
    - &zone1 !!models.Zone
        id:                 1
        gtbName:            "ZZ01"
    - &zone2 !!models.Zone
        ...

users:
    - &user4 !!models.User
        id:                 4
        profile:            *profile4
        defaultZone:        *zone3
        zones:
            - *zone1
            - *zone2
            - *zone3


Why are these notes separated on the stave?

Question: So I'm just learning this Coldplay piece and it has notes which are not joined but on the same stave. I'm wondering what the purpose of this is or rather what information it's trying to convey? Perhaps the lower notes should be played when the lower lyrics are to be sung, i.e. on the second repeat?
Later on in the sheets it's made slightly more obvious as some of the notes that are separated are slightly smaller.
I'd like to know for sure as I'm turning my sheet music into MIDI files so that I can use Synthesia to practice them.
Comment: Note that since several of the pairs of notes have different durations, it would make no sense to use the same stem. (I assume by "separated" and "not joined" you mean that instead of sharing one stem, each notehead has its own stem.)
Comment: Thanks @KyleStrand, yes that is what I meant. You're right, it makes no sense, but I didn't see that until my question had an answer. ;-)
Answer: Smaller notes are a different issue, and could be relevant to a second line of lyrics, but you will typically see them only sporadically appear within the top voice.
Anyway, what you're asking about is referred to as multiple voices on a staff. Notes in harmony will generally only be grouped together with a stem if the rhythm is the same, and all of the notes are "on the same part".
There are three parts/voices in this excerpt. The bass is on the bass cleff staff, the melody is the top part of the treble clef staff, and the part in the middle is a harmony part. All parts should be played with each line of lyrics, and the top line should be sung.
Generally a staff will contain up to two voices, since they can easily be distinguished from one another with the use of up stems or down stems. But this is certainly not a hard limit; it is quite common to see more than 2 voices in a staff when reading orchestral scores. In ambiguous cases, the music will contain short instructions like "1.", "a 2" to designate which parts should be playing where.
Comment: Right, so if I understand correctly, I should be playing both voices of the cleff staff with my right hand?
Comment: @deed02392 Yes.
Answer: When notes do share the same stem like this, it is because the editor is showing the two notes to be different "voices".  In this particular case, they want to distinguish the melody, which is the top part, from the bottom notes that are filling out the harmony.
Separating the voices is extremely common whenever there is a sung melody that is also being played by the piano.  Choral music where all four parts are written on the same staff will often be separated the same way so that the singers can tell which part is theirs.
Comment: ecline6 - did you mean 'share the same stave/staff' rather than 'share the same stem' ?
Comment: Sorry, I'm confused ! In the sample, no notes are sharing the same stem. Same stave, yes.You're spot on with SATB, S- treble clef, stems up, A- treble clef, stems down,etc. I'm hoping a stem is the same as a tail on a crotchet,etc.If they're sharing the same tail, it's difficult to tell whether they're alto or soprano for example.
Comment: @Tim Nope.  Stem is what I meant.  The question is about notes that have different stems in the same staff.


Mostrar dados do PostgreSQL em pagina web

Question: Sou novo no assunto e acabei empacando na parte web.
Gostaria de uma ajuda para exibir/pesquisar informações do banco de dados PostgreSQL e mostrar em uma pagina web.
Como estou aprendendo Python, gostaria de ajuda nessa linguagem, mas JS também seria interessante para mim.

Tenho um arquivo em Python que faz a conexão e um SELECT.O arquivo Python funciona certinho, via terminal. Este é um código base que, a partir deste código, eu fiz o meu
     cur.execute("SELECT id, name, address, salary  from COMPANY")
    rows = cur.fetchall()
    for row in rows:
       print "ID = ", row[0]
       print "NAME = ", row[1]
       print "ADDRESS = ", row[2]
       print "SALARY = ", row[3], "\n"

    print "Operation done successfully";
cur = conn.cursor()

cur.execute("SELECT id, name, address, salary  from COMPANY")
rows = cur.fetchall()
for row in rows:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "\n"

print "Operation done successfully";
conn.close()

Answer: Bom, usando PHP consegui mostrar os dados usando js(jquery).
<?php
include_once("./php/conect_postgre.php");

  $consulta_bd = "SELECT * FROM uniao  WHERE regua LIKE 'Co%'";

  $result=pg_query($conexao, $consulta_bd);
  if  (($result)){
      while($linha_usuario = pg_fetch_assoc($result)){
          echo $linha_usuario['regua'] . "
";
      }
  }else{
      echo "Nenhum resultado encontrado";
  }

Armazenei meu select numa variavel($linha_usuario) ou pode chamar ela de row, passei o id "regua" do input para isso. Logo depois criei uma função em jquery para puxar essa variavel, assim:
JQUERY

Onde tem a "paginaquetemoselect", você coloca onde está seu banco de dados puxando registro, a function(retorna) é a função que vai receber esse registro e mostrar na div chamada "conteudo", esse nome ai é o ID da minha div onde quero mostrar os registros. O php é so para você ver como fiz o select dos registros. Foca ali no jquery.


UmbracoTemplatePage and strongly typed view not working together

Question: I don't quite understand why I can't use both strongly typed view and umbraco template in one view.
I have a script importing excel data. My website is in umbraco 7.
I use Import.cshtml view which calls upload.cshtml partial
@inherits UmbracoTemplatePage
@{
    Layout = "~/Views/Master.cshtml";

    var locations = new List<SelectListItem>
        {
        new SelectListItem {Selected = false, Text = "location 1", Value = ""},
        };

    var fileTypes = new List<SelectListItem>
        {
        new SelectListItem {Selected = false, Text = "type 1", Value = ""},
        };
}

@Umbraco.Field("title")

            @Html.Partial("Upload", new MvcImport.Models.ImportModel { FileTypes = fileTypes, Locations = locations })

Upload.cshtml partial does the job in ImportController. The data are there inserted into nicely into
List<CourseImport> courses = List<CourseImport>

All I want to do with it now is to display them in a view or partial view.
I tried several things:

CASE 1
1.
in ImportController I do:
return View("CoursesList", courses);

2.
The view includes a table which displays the rows and starts with
@inherits UmbracoTemplatePage
@model IEnumerable<MvcImport.Models.CourseImport>
@{
    Layout = "~/Views/Master.cshtml";
}

3.
In this case I get:
Parser Error Message: The 'inherits' keyword is not allowed when a 'model' keyword is used.

CASE 2
1.
As 1. in Case 1.
2.
The view starts with (so without @inherits UmbracoTemplatePage)
@model IEnumerable<MvcImport.Models.CourseImport>
@{
    Layout = "~/Views/Master.cshtml";
}

3.
I get:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[MvcImport.Models.CourseImport]', but this dictionary requires a model item of type 'Umbraco.Web.Models.RenderModel'.

CASE 3
1.
In ImportController I do
return PartialView("CoursesList", courses);

2.
I'm now using partial view which it similar to the view in the above points and also is strongly typed eg.
@model IEnumerable<MvcImport.Models.CourseImport>

3.
In this case the data is displayed but without my umbraco template shape, no styling etc.
If in the partial view I include
@{
    Layout = "~/Views/Master.cshtml";
}

I get the same error as in Case 2

Changing the starting directive to
@model UmbracoViewPage<MvcImport.Models.CourseImport>

does not work either as the model must be enumerable

Can someone advise me how to do it? I guess there must be a solution but I am very new to MVC so I don't get how things work yet too much.
Thanks.
Answer: The solution is provided on umbraco forum website http://our.umbraco.org/forum/developers/razor/55389-UmbracoTemplatePage-and-strongly-typed-view-not-working-together?p=0


Intervals: Diminished unison?

Question: I am learning level 8 theory. There was an exercise where I had to write each interval below the given note. The interval given was a diminished 1. In general, how would I solve this? Here is a similar picture of the exercises I had:
Comment: Level 8 theory? What level is that equivalent to in, say, U.K? Which country?
Comment: ...or rather, when one wouldn't instead call it _augmented unison downwards_.
Comment: @Tim That's a good question. It's level 8 Theory in Canada. I'm not too sure how to convert it.
Comment: A better, deeper question might be - describe a circumstance when one needs a dim. unison...
Answer: You would actually solve it exactly as you would any other diminished interval. Let's say you want to write a diminished first (also known as a diminished unison) below C.

First, you want to determine what the note name will be without any accidentals. Since you're looking for a unison, it will be the same pitch as C: C!
Next, let's determine what quality unison this is from C. Obviously C to C is a perfect unison. (Recall that there are no major or minor unisons, fourths, fifths, or octaves!)
This is a perfect unison, but you want a diminished unison. Just as we lower the resulting pitch a half step to move from, say, a perfect fifth to a diminished fifth, we'll lower the resulting tone in our example down to a C♭.

As such, your diminished unison below C is a C♭. Even though this is enharmonic to B, B–C would be a minor second, not a diminished unison.

Now let's see these steps for your first example looking for the major 10:

Write the note name that is a 10th below F: D.
Now, measure this interval: D up to F is a minor tenth.
We have a minor tenth, but we want a major tenth. To make a minor interval major, we have to make it larger. So, we lower the D to D♭ to make the major tenth.

Make sure you do not alter the given pitch. We could have raised the written F to F♯, but this is typically against the rules.

A quick note on whether this diminished unison is above or below the C in question.
When teaching intervals, we assume octave equivalence. We know this for at least two reasons: first, because we equate simple intervals (intervals of an octave or less) with their compound (intervals larger than an octave) siblings; and second, because the patterns that arise when we invert intervals are not possible without octave equivalence.
As such, in my opinion it's necessary that a diminished unison is spelled the same way as the compound version of that interval (i.e., that interval plus an octave). The diminished octave above C is unequivocally C♭, and thus the same is true for the diminished unison.
Comment: @iiRosie1 Correct. Maybe more correct would be that you make the interval smaller to make it diminished, and you make the interval larger to make it augmented. This is because you'll move the pitch in various directions depending on if it's above or below the other pitch.
Comment: In a way this sort of mocks the idea that intervals are worked out from the *lower* note! And, diminished means smaller. By going C>Cb, it's actually bigger! Also can't think of a reason for a dim 1, except for exam purposes. +1.
Comment: @Aethenosity Yes, which is why I tried to stay away from terms like "larger" and "smaller" when discussing that particular interval.
Comment: Ok, so a unison interval is basically perfect (no major or minor), and if you want to diminish it you just lower it by a semitone, and if you want to make it augmented, you basically raise it by a semitone?
Comment: @Richard diminishing a unison would make the interval larger in the case of a unison though, right? The unison would have an interval of nothing, and a diminished unison would have an interval of a semi tone.
Comment: Why would C-Cb be *diminished unison* and not a *descending augmented unison*? Is *"diminished unison"* just a play on following some written rules or is it a real thing? After all, the rules were created to describe what's happening, not the other way round.
Comment: @JiK In my opinion, they're the same thing, but "diminished unison" is admittedly more theoretical and not all that practical.
Comment: I do not understand your octave equivalence statement since in every other situation, an inverted interval changes both name and size. A P5 above a given note become a P4 below, a M6 above becomes a m3 below, etc. The inverted interval of a d8 would be an +unison, which is what we have here in C to Cb.
Comment: @HeatherS. I only meant switching between the compound and simple version of an interval (not inverting it), hence the quality stays the same. But you're correct, inverting intervals *does* change the size and quality, and this example shows that the diminished unison would be C to C♭, since the augmented octave would be C♭ to C!
Comment: @Richard, that changes the base note and direction, so I don't see how that helps answer the question.
Comment: @HeatherS. I'm not sure I understand what you mean. In my post I wasn't discussing inverting the interval. I only mentioned it in my last comment to show that that logic also supports my argument of this interval being C to C♭.
Comment: @Richard, I also believe in this situation, it would be an inversion since in addressing the "compound" interval, you are bringing the upper note below the original. In compound situations, the relation of notes as far as top/bottom does not change.  As, in your answer, the D a tenth below the F, no longer compound, is still a 3rd *below* the F.
Comment: @Richard, when C is still the starting note, an augmented octave would be C#. It is only Cb to C if you change the starting note to Cb, which is not the starting note in question.
Answer: The main trouble that some people find with Diminished unisons is that the starting note is above the other note. This has been the source of much debate among theorists, with some arguing that diminished unisons are therefore the same as augmented unisons when written harmonically.
Suppose that you want a diminished fifth written above the root G. 5th is D, diminish it BY DECREASING THE DISTANCE BY 1 SEMITONE, changing the ending note. This is going to become a problem later. Suppose I want, now, a diminished 1st above the note G. G-G is a unison, diminish it to G♭. Note that this end note is below its root G. Diminished 5th below G? G-C is fifth, diminish it to C♯. G to C♯. But what about the diminished unison BELOW G? G-G is the unison, and to diminish the note, we've got to raise the G to G♯. Except, now our diminished unison BELOW the note is actually HIGHER than its starting note, making NO SENSE AT ALL.
So do diminished unisons exist? In theory, it's possible to construct one, but it makes little sense, and theorists argue over whether the phrase "descending diminished unison" is even correct.
Comment: @Tim  but in theory,  Theory misses its own foot ; in practice, not so much :-) (cheap paraphrase from famous statement about engineering)
Comment: Question probably made up by a theorist! This is where theory stops being helpful, and shoots itself in the foot.
Comment: I hope I never need to know the answer to this question, it sounds to me like a variation on the old idea of "Stump the Band".
Comment: @dfhwze Technically, d8 and d1, respectively, though some contest that d1 truly exists, preferring a1.
Answer: Your picture shows a diminished 12th; that should be easy. Unisons can be augmented but I've never seen a diminished unison. Kosta and Payne say such an interval does not exist. (Apparently, from a perusal of the NET, some people call C to Cb a diminished unison but that makes little musical sense.)
Answer: I believe the question in the example is unfair, and if you brought that up to the teacher you would look like you knew even more theory than what you have studied in class. As explained here on this thread, the idea of a diminished unison is quite debatable and as such is not a suitable question for a student to answer. If I faced your situation, I would leave the answer blank and go talk with the teacher.
In my opinion, a diminished unison is like dividing by zero. An answer cannot be found. The idea of an interval is the distance between two notes. We can adjust those distances and make them smaller or larger. No matter what is done to a unison, it is made larger. C to Cb is an augmented unison. C to C# is an augmented unison.

Intervals: Diminished unison?


Commerce free shipping for orders over €500

Question: I am carrying on with this project where we are supposed to ship for free for orders over €500. I have two rules; Free shipping and NL/BE. I make an address based comparison and role based comparison for NL/BE and amount based in Free shipping. Now, the problem is, when I test if the customer places an order for over €500 and the shipping address is in Belgium, I am still asked whether I want a free shipping or a NL/BE shipping. Obviously this shouldn't happen. What am I doing wrong?
Thanks :)
These are my rules:
{ "commerce_shipping_service_nl_be" : {
    "LABEL" : "Rate NL\/BE",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "rules", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce_order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "value" : "BE"
        }
      },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "6" : "6" } }
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "nl_be",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}
}

and
{ "commerce_shipping_service_free_shipping" : {
    "LABEL" : "Rate Free shipping",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "type" : "commerce_order", "label" : "Order" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4", "6" : "6" } }
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "free_shipping",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

Answer: I at last managed to find out. I should have paid more attention to the video I've watched. What I needed to do was add the exact opposite condition to NL/BE rule, that is if the order's total amount is lower than €500.


MYSQL#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near

Question: CREATE TABLE IF NOT EXISTS 'users' (
    'id' int(11) NOT NULL AUTO_INCREMENT,
    'username' varchar(255) NOT NULL,
    'first_name' varchar(255) NOT NULL,
    'last_name' varchar(255) NOT NULL,
    'email' varchar(255) NOT NULL,
    'password' varchar(255) NOT NULL,
    'sign_up_date' date NOT NULL,
    'activated' enum('0','1') NOT NULL,
    PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Comment: And your **question** is?
Comment: Please read this post: https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-back-ticks-in-mysql
Answer: When you create your database you will need to initialize the defaults. For example:
CREATE DATABASE {your-db-here}
DEFAULT CHARACTER SET latin1;

USE {your-db-here};
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
first_name varchar(255) NOT NULL,
last_name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
sign_up_date date NOT NULL,
activated enum('0','1') NOT NULL,
PRIMARY KEY (id)
);

InnoDB is the default engine


In which format messages are sent in WCF

Question: Context
I am new to WCF.
I was reading an article about message contract and found that WCF is sending message using SOAP.
My doubt is, if we are enabled REST in WCF service, then will it still use SOAP format for exchanging data.
In WebGet and WebInvoke attribute[which are for REST], we are mentioning the inputformat like JSON or XML.
Question
If messages are sent through SOAP, then why are those needed ?
If all message contracts are sent using SOAP format, then message contract should not work in case of webHttp binding.
Comment: Possible duplicate of [Why is a message in WCF seemingly always in SOAP format?](http://stackoverflow.com/questions/10024367/why-is-a-message-in-wcf-seemingly-always-in-soap-format)
Answer: The protocol format will depend on the binding you select. Here's a list of the different system provided bindings and the underlying protocol they use.

In WebGet and WebInvoke attribute[which are for REST], we are
  mentioning the inputformat like JSON or XML.
  If messages are sent through SOAP, then why are those needed.

If you use the WebHttpBinding which uses standard HTTP instead of SOAP then those attributes allow you to specify whether you want to format the requests using plain XML (not SOAP) or JSON.
Comment: Will MessageContract work in case of webHttp ? I read that MessageContract works on SOAP protocol.
Comment: No, message contracts are SOAP specific. You need to use Data Contracts with webHttp. By the way if you want to expose a RESTful API, wouldn't ASP.NET Web API be a more suitable solution than WCF for you?
Comment: Thanks a ton Darin..I got the answer.


Explodir linhas de um textarea e separá-los por virgulas

Question: Opa,
Preciso capturar o texto do textarea, separá-lo por linhas e então dar um explode e separá-lo pelas virgulas.
        $lines = explode("\n", $respostas);
        $i = 0;
        if ( !empty($lines) )
        {
            foreach ($lines as $line)
            {
                $i++;
                    //Adiciona Respostas
                    foreach($respostas as $key)
                    {
                        $sql = mysqli_query($conn, "INSERT INTO respostas
                            VALUES (
                                NULL, $i, '$key'
                        )");
                    }
                    //Adiciona Respostas

            }
        }

Em que no insert do mysql, preciso salvar o conteúdo ($key) a linha ($i), mas, está duplicando os inserts de acordo com a quantidade de linhas.
Exemplo do textarea:
teste, teste1, teste2
teste3, teste4

Comment: O que tem no $respostas?
Comment: Conteúdo do textarea:

`
teste, teste1, teste2
teste3, teste4
 `

Deve ser separado as palavras separadas por virgula e por linha
Comment: entendi, ele vem dessa forma então
Comment: No Caso @AndréBaill, aqui não exibe a formatação de exibição, adicionei o conteúdo exemplo do textarea na pergunta
Comment: me diga uma coisa, todos serão separados por virgula já? e outra coisa... o objetivo é inserir estes registros no banco de dados?
Comment: Sim, o usuário já digitará as palavras separando-as com a virgula, inclusive com a separação entre linhas e será para cadastro no banco
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/43688/discussion-between-andre-baill-and-snniffer).
Answer: Fiz aqui e imagino que seja isso que você quer, veja se atende:
$respostas = "teste, teste1, teste2
        teste3, teste4";
        $lines = explode("\n", $respostas);
        $i = 0;
        if ( !empty($lines) )
        {
            $aWords = [];
            foreach($lines as $line){
                $aWords[] = explode(',', $line);
            }
            //Adiciona Respostas
            foreach($aWords as $key => $aWord2)
            {
                $linha = ($key+1);
                foreach($aWord2 as $word){
                    $word = trim($word);
                    $query = "INSERT INTO respostas VALUES (NULL, $linha, '{$word}')\n";
                    echo nl2br($query);
                    //$sql = mysqli_query($conn, $query);
                }
            }
        }

Resultado ficou assim:
INSERT INTO respostas VALUES (NULL, 1, 'teste')
INSERT INTO respostas VALUES (NULL, 1, 'teste1')
INSERT INTO respostas VALUES (NULL, 1, 'teste2')
INSERT INTO respostas VALUES (NULL, 2, 'teste3')
INSERT INTO respostas VALUES (NULL, 2, 'teste4')

Descomente a linha do $sql para inserir na base ou altere conforme necessidades extras.
Boa sorte!
Comment: Boa tarde Fabil, seu script funcionou perfeitamente, mas, ao upar para o server online, está me retornando `Parse error: syntax error, unexpected '[' `, isso no local onde está a linha `$aWords = [];`. Há algo que possa ser feito para contornar? Abraço
Comment: substitua as chaves [] por:
array();
ficando:
$aWords = array();


$f_n(x) = \int_{0}^1 t^{x-1} (1-t)^{n-1} dt$ does not converge uniformly to zero in $(0,\infty)$

Question: The problem says to show that $f_n(x) = \int_{0}^1 t^{x-1} (1-t)^{n-1} \, dt$ converges pointwise to $0$ but not uniformly for $x > 0$.
To show pointwise convergence, since $\left| (1-t)^{n-1} \right| \leq 1$ then if I define $\phi_n(t) = t^{x-1} (1-t)^{n-1}$ we have that $\left|\phi_n(t) \right| \leq t^{x-1}$ and
$$
\int_{0}^1 t^{x-1} \, dt = \frac{1}{x},
$$
so by the dominated convergence theorem $\lim\limits_{n \to \infty} f_n(x) = \int_{0}^1 \lim\limits_{n \to \infty} \phi_n(t) \, dt = 0$.
I have two problems here:

I would prefer a proof that does not use the dominated convergence theorem, as this is a question from a practice exam that does not assume measure theory.
How to approach uniform convergence? So far what I tried is to show that a particular sequence, like $f_n(1/n)$ does not go to zero, but when I solve the integrals I don't see why it would be true.
Answer: $$f_n(x)=B(x,n)=\frac{\Gamma(x)\Gamma(n)}{\Gamma(x+n)}$$
you could use Sterling's approximation that states:
$$y!{\large{\text{~}}}\sqrt{2\pi y}\left(\frac{y}{e}\right)^y$$
and this is very accurate for large values of $y$
Answer: Convergence
By IBP,  for all $a_n \in (0,1)$
$$\begin{align}f_n(x)&=\frac{n-1}{x} \int_{0}^1 t^x(1-t)^{n-2}dt \le \frac{n-1}{x}  \left[ \int_{0}^{a_n} t^xdt +\int_{a_n}^1 (1-t)^{n-2}dt\right]\\
&=\frac{(n-1)a_n^{x+1}}{x(x+1)}+\frac{1}{x}(1-a_n)^{n-1}=:A_n(x)
\end{align}$$
Choosing $a_n=(n-1)^{-1/(x/2+1)}$, we can see that $$\lim_n A_n(x)=0$$
Hence the pointwise convergence.

Not uniform
We have
$$f_n(x) \ge \int_0^{1/2} t^{x-1} (1/2)^{n-1}dt=\frac{2^{-x-n+1}}{ x}$$
Thus
$$f_n(2^{-n}) \ge 2^{-2^{-n}+1} \ge 1$$
Hence the conclusion.


Why does the following simple piece of Java code using pooled connections from commons.dbcp block?

Question: I have written a simple Java code, which attempts to store files in an hsqldb database. All it does is reads the files from a certain directory and puts them in the DB. It is single threaded, but I am using pooled connections from the apache commons.dbcp in order to be able to cope with the multithreaded access later.
The problem is that the code blocks after reading a few files.
Please, find below the entire source code.
Program.java
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.KeyedObjectPoolFactory;
import org.apache.commons.pool.impl.GenericKeyedObjectPoolFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

public class Program {
  public static DataSource getPoolingDataSource(String driverClass, String url, String user, String password) throws ClassNotFoundException {
    Class.forName(driverClass);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, password);
    GenericObjectPool connectionPool = new GenericObjectPool();
    KeyedObjectPoolFactory stmtPool = new GenericKeyedObjectPoolFactory(null);
    new PoolableConnectionFactory(connectionFactory, connectionPool, stmtPool, null, false, true);
    return new PoolingDataSource(connectionPool);
  }

  public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException, InterruptedException {
    String root = args.length == 0 ? "c:/Work/java/ntxdb" : args[0];

    Runtime run = Runtime.getRuntime();
    Process pr = run.exec("cmd /c del /s/q c:\\tmp\\file.db*");
    pr.waitFor();
    DataSource ds = getPoolingDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:c:/tmp/file.db", "sa", "");
    HsqldbFileStorage fs = new HsqldbFileStorage(ds);
    putFiles(fs, new File(root));
  }

  private static void putFiles(HsqldbFileStorage fs, File parent) throws IOException, SQLException {
    for (File child : parent.listFiles()) {
      if (child.isDirectory()) {
        putFiles(fs, child);
      } else {
        System.out.println(child.getCanonicalPath());
        fs.put(child);
      }
    }
  }
}

HsqldbFileStorage.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

public class HsqldbFileStorage {
  private static final String SET_SQL = "MERGE INTO test" +
    "  USING (VALUES ?, CAST(? AS BLOB)) I (name, data)" +
    "  ON (test.name=I.name)" +
    "  WHEN MATCHED THEN UPDATE SET test.data = I.data" +
    "  WHEN NOT MATCHED THEN INSERT (name, data) VALUES (I.name, I.data)";
  private DataSource m_dataSource;

  public HsqldbFileStorage(DataSource dataSource) throws SQLException {
    super();
    m_dataSource = dataSource;
    Connection c = dataSource.getConnection();
    c.createStatement().execute("Create Cached Table IF NOT EXISTS test (name VARCHAR(256), data BLOB(10M));");
  }

  public void put(File file) throws IOException, SQLException {
    put(file.getCanonicalPath(), file);
  }

  public void put(String name, File file) throws IOException, SQLException {
    InputStream is = new BufferedInputStream(new FileInputStream(file));
    try {
      put(name, is);
    } finally {
      is.close();
    }
  }

  public void put(String name, InputStream data) throws SQLException, IOException {
    PreparedStatement set = m_dataSource.getConnection().prepareStatement(SET_SQL);
    try {
      set.setString(1, name);
      set.setBinaryStream(2, data);
      set.executeUpdate();
    } finally {
      set.close();
    }
  }
}

The code depends on commons-dbcp 1.4, commons-pool 1.6 and hsqldb 2.2.9
Running it on the project directory itself should put 62 files in the DB (I have much more files there than the two aforementioned source files), printing a line for each file.
Unfortunately, it blocks on the eighth file with the following stack trace:
  at java.lang.Object.wait(Object.java:-1)
  at java.lang.Object.wait(Object.java:485)
  at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1118)
  at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
  at HsqldbFileStorage.put(HsqldbFileStorage.java:41)
  at HsqldbFileStorage.put(HsqldbFileStorage.java:34)
  at HsqldbFileStorage.put(HsqldbFileStorage.java:28)
  at Program.putFiles(Program.java:42)
  at Program.putFiles(Program.java:39)
  at Program.putFiles(Program.java:39)
  at Program.main(Program.java:33)

What am I doing wrong?
Answer: You are calling:
m_dataSource.getConnection()

in your put(String, InputStream) method. This creates a new connection, which you never close.
So when you are hitting putting 62 files in at some stage it will hit the maximum number of connections in your pool, after which the pool will wait for a connection to be returned to the pool.
If you modify your method as such:
  public void put(String name, InputStream data) throws SQLException, IOException {
    Connection con = null;
    PreparedStatement set = null;
    try {
      con = m_dataSource.getConnection();
      set.prepareStatement(SET_SQL);
      set.setString(1, name);
      set.setBinaryStream(2, data);
      set.executeUpdate();
    } finally {
      if (set != null) {
        set.close();
      }
      if (con != null) {
        con.close();
      }
    }
  }

Note, when you access connections through a pool, you still need to call close. This won't actually close the connection but return it to the pool.


Prove that the subgroup $\langle a, b \rangle$ has order 6

Question:
Let $a = \begin{pmatrix}0 & 1 \\ 1 & 0\end{pmatrix}$ and $b = \begin{pmatrix}0 & 1 \\ -1 & -1\end{pmatrix}$ be elements of $\mathrm{GL}_2\left(\mathbb{Q}\right)$.
Prove that the subgroup $\langle a, b \rangle$ has order 6.

I can show that $\left|a\right| = 2$, $\left|b\right| = 3$, and $\left|ab\right| = 2$. By LaGrange's theorem it follows that the order of $\langle a, b \rangle$ must be a multiple of 6.
But how can I prove that $\left|\langle a,b \rangle\right|=6$?
My best idea so far is to enumerate all possible products (i.e., $e, a, b, aa, ab, ba, bb, \ldots$) up to redundancy and show that they generate only 6 elements.
Is there a more clever way to show this?
Hints preferred, please!
Comment: Here's a hint. I wrote out a few members of your group and found, indeed, six distinct elements. Then I made a little 6 by 6 multiplication table, filled in all the products, and confirmed that the set of 6 is closed under multiplication.  You should do the same.
Comment: If $|ab| = \infty$, then $\langle a, b \rangle \supseteq \langle ab \rangle$ has infinite order too.
Comment: $|ab|$ is not $\infty$.
Comment: @GeorgeLaw Yes, you're right. Sorry for my error.
Comment: It should be easy enough to show that $\{I, a, b, b^2, ab, ab^2\}$ are in your group.  Clearly if you multiply any of those on the right side by $b$ you get an element already accounted for.  Multiply by $a$ and $ba = ab^2, b^2 a = ab, aba = b^2, ab^2 a = b$
Answer: Groups of order 6 are either $C_6$(cyclic) or $D_6$(Dihedral). $a$ and $b$ don't commute so you just need to check $aba=b^{-1}$. i.e You only have to check one relation
Answer: The dihedral group of degree 3 (order 6) is characterized as follows:
$$D_3\ =\ \langle \rho,\sigma \mid \rho^3=\sigma^2=e,\,\sigma\rho=\rho^{-1}\sigma \rangle$$
You have shown that $b^3=a^2=I$. It remains to show that $ab=b^{-1}a$. This will mean that the mapping $a\mapsto\sigma,\,b\mapsto\rho$ is an isomorphism from $\langle a,b\rangle$ to $D_3$.
Answer: Your original idea is fairly straight forward also.
Since $|a|=2$ and $|b|=3$ you can construct the set $H=\{e,a,b,b^2,ab,ab^2\}$. Notice that each of the six element must be distinct. You can show that $H$ is subgroup of $GL_2(\mathbb{Q})$, and thus a group of order $6$. Now $\langle a,b\rangle$ is the smallest subgroup generated by $a$ and $b$, and thus $\langle a,b\rangle =H$and  has order $6$.


ASP.NET - Security Reflected XSS problem with some codes

Question: Here where I work they use an application called checkmarx to analyze the security of the application
In one of these analyzes the application detected the following problems:
Reflected XSS All Clients:

The application's GetBarcosNaoVinculados embeds untrusted data in the
generated output with Json, at line 1243 of
.../Controllers/AdminUserController.cs. This untrusted data is
embedded straight into the output without proper sanitization or
encoding, enabling an attacker to inject malicious code into the
output. The attacker would be able to alter the returned web page by
simply providing modified data in the user inputusuarioId, which is
read by the GetBarcosNaoVinculados method at line 1243 of
.../Controllers/AdminUserController.cs. This input then flows through
the code straight to the output web page, without sanitization.

public JsonResult GetBarcosNaoVinculados(string usuarioId)
.....
.....
 return Json(barcosNaoVinculados, JsonRequestBehavior.AllowGet)

Elsewhere in the system it gives the same problem but with these two methods

The application's LoadCodeRve embeds untrusted data in the generated
output with SerializeObject, at line 738 of
.../BR.Rve.UI.Site/Controllers/InfoApontamentoController.cs. This
untrusted data is embedded straight into the output without proper
sanitization or encoding, enabling an attacker to inject malicious
codeinto the output.The attacker would be able to alter the returned
web page by saving malicious data in a data-store ahead oftime. The
attacker's modified data is then read from the database by the Buscar
method with Where, at line 78 of .../Repository/Repository.cs. This
untrusted data then flows through the code straight tothe output web
page, without sanitization.

public virtual IEnumerable<TEntity> Buscar(Expression<Func<TEntity, bool>>predicate)
   return Dbset.Where(predicate);

public string LoadCodeRve()
  return JsonConvert.SerializeObject(items);

It seems that it has to do with the treatment given to the JSON format, would anyone know how to treat this type of problem?
Answer: As the warning message indicates, you need to perform either some form of input validation (or sanitization), and also as a secure coding best practice - output encoding before rendering the output into the page. Checkmarx searches for the existence of these "sanitizers" and these are predefined in their Checkmarx query. One for instance is the use of the AntiXSS libraries (i.e. JavascriptEncode function)
The two critical lines to look out for is already pointed out by Checkmarx:
return Json(barcosNaoVinculados, JsonRequestBehavior.AllowGet)

and
return JsonConvert.SerializeObject(items);

whichever pages these values (JSON or String) are going to end up, they needed to be escaped. Now depending on the templating engine you are using, you might already get instant XSS protection. For example, "The Razor engine used in MVC automatically encodes all output sourced from variables, unless you work really hard to prevent it doing so." and unless of course you used the Html.Raw helper method.
As promoters of application security we believe in not trusting the input and having layers of defenses so my suggestion is to explicitly indicate that you want to encode the output by passing in JsonSerializerSettings argument:
return JsonConvert.SerializeObject(items, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml });

The only dilemma here is that Checkmarx might not recognize this is as a sanitizer because it may not be in their predefined list of sanitizers. You could always present this solution as an argument to the Security team that is running the Security scans
For the case of the JsonResult return, you may want to javascript encode the barcosNaoVinculados variable:
return Json(HttpUtility.JavaScriptStringEncode(barcosNaoVinculados), JsonRequestBehavior.AllowGet)

Now, this too Checkmarx may not recognize. You can try using the ones that Checkmarx recognizes (i.e. Encoder.JavascriptEncode or AntiXss.JavascriptEncode) but I don't think these Nuget packages will work in your project type
Comment: I think he should solve the problem first of all. Then if Checkmark not identify the solution, he need to ignore this result in Checkmark product, and send the case to the Checkmark company.
Comment: @roman Thx for the tips, I am using razor, I will try the solution you indicated. About the JsonResult, im using the .net framework 4.6.1, and on the MS docs, indicates that it is compatible, I will test and return to mark your answer as a solution


How do I use a properties file in Java?

Question: In the web application, which I am going to build, I need some SQL queries, which I can store in a properties file, and get them into my Java code, and then execute.
I have found many suggestions on the internet, but nothing helped me. Some of them are
this.getClass().getClassLoader().getResourceAsStream("resources/file.properties");
this.getClass().getResourceAsStream("resources/file.properties");

I have kept the properties file in resources, and in the same directory in which my Java file is present. Nothing worked. I am using Eclipse and Struts2.
Comment: Where do you want to use the values from the properties file? in your action class? If so, there is a struts way of doing it.
Comment: I need to read the sql query in Dao.
Answer: Make sure that your properties files goes to WEB-INF\classes, where your struts.xml is. This folder is on the classpath. Then
this.getClass().getClassLoader().getResourceAsStream("file.properties");

should work as expected. Or of course, if you create a resources folder in classes, the aforementioned code should work too.
If by resources folder you mean src/main/resources, then it is managed by Maven, and it is copied directly to WEB-INF/classes. So you do not need to specify the resorces folder in the method.
Comment: I kept it in the same place(resources) where struts.xml file is present. Still I am getting "java.lang.NullPointerException"
Comment: I am just using struts2 and tiles.
Comment: My project is working fine when I placed SQL queries in the java directly. Now I want to keep them in separate file and use in java.
Comment: Could you add a print screen about your project layout to the question? Also make sure that the properties file is actually in the WAR file!

How do I use a properties file in Java?


htmlagilitypack remove row attributes

Question: How do we remove the inline height attribute from html?

I want only height attributes to be removed from all tr tags.
Thanks a lot in advance,
Answer: You can:

If your trs have no other styles other than height, you can simply remove strip them from their style attribute (the line I commented out)
Otherwise, you can write something like the snippet below to filter which style keys you want to remove
string html = @"

";

    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(html);

    var trs = doc.DocumentNode.SelectNodes("tr");

    foreach (var tr in trs)
    {
        Console.WriteLine(tr.OuterHtml);
        //tr.Attributes.Remove("style");

        var filteredStyles = GetStyles(tr.GetAttributeValue("style"), "height");
        tr.SetAttributeValue("style", string.Join(":", filteredStyles));

        Console.WriteLine(tr.OuterHtml);
    }

Helper function:
 private static List<string> GetStyles(string style, params string[] keysToRemove)
        {
            List<string> styles = new List<string>();
            var stylesKeyPairs = style.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            if (keysToRemove != null)
            {
                foreach (var styleKeyPair in stylesKeyPairs)
                {
                    var styleKeys = styleKeyPair.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    if (!keysToRemove.Contains(styleKeys.FirstOrDefault()))
                        styles.Add(styleKeyPair);
                }
            }
            else
                styles.AddRange(stylesKeyPairs);

            return styles;
        }

Output (for both solutions, in this case):

htmlagilitypack remove row attributes