Prove whether $xyz =1$ implies that $yzx=1$ or $yxz=1$.

Question: Let $x,y,z$ be elements of a group $G$ and $xyz=1$. I am trying to prove whether this implies $yzx=1$ or $yxz=1$.
My proof goes as follows: Let $x^{-1}$ denote the inverse of $x$, then $xx^{-1} = 1 = x(yz)$. By the cancellation property of groups, $x^{-1}= yz$. This implies $(yz)x = x^{-1}x = 1$. Therefore $xyz = 1 \implies yzx = 1$.
By applying the same argument to $y(zx) = 1$ one can prove that $xyz = 1 \implies yxz =1$.
However while trying to my proof online I stumbled upon the following counterexample for the proposition $xyz = 1 \implies yxz =1$. If we take $G$ to be the group of $2\times 2$ matrices and let $x = \left( \begin{array} { c c } { 1 } & { 2 } \\ { 0 } & { 2 } \end{array} \right)$, $y = \left( \begin{array} { l l } { 0 } & { 1 } \\ { 2 } & { 1 } \end{array} \right)$ and $z = \left( \begin{array} { c c } { - 1 / 2 } & { 3 / 4 } \\ { 1 } & { - 1 } \end{array} \right)$. Then $x y z = \left( \begin{array} { c c } { 1 } & { 0 } \\ { 0 } & { 1 } \end{array} \right) = 1$ but $y x z = \left( \begin{array} { c c } { 2 } & { - 2 } \\ { 5 } & { - 9 / 2 } \end{array} \right) \neq 1$.
I don't understand where my proof went wrong.
Comment: I think you need to double-check your "By applying the same argument..." line. Are you sure it works out?
Comment: Intuitively, this argument shows you can "peel off" a variable on one side, and slap it on the other.
Answer: You just mixed up some letters. $xyz=1$ implies $yzx=1$ and $zxy=1,$ not $yxz=1.$
Answer: Well, if $xyz=1$, then by multiplying with the inverse of $x$ from the left, $yz=x^{-1}$. Now multiply the equation with $x$ from the right. Then $yzx=1$.
Answer: For any group we have $aa^{-1}=a^{-1}a=1$.  From $xyz=1$ we know that $(xy)z=1$, from where the first claim follows.
Answer: Since $G$ is a group then if $x\in G$ , there exists $x^{-1}\in G$ such that $$x\cdot x^{-1}=x^{-1}\cdot x=e\in G$$having this result and exploiting the other properties of group we obtain $$x^{-1}\cdot (xyz)=(x^{-1}\cdot x)\cdot yz=e\cdot yz=yz=x^{-1}\cdot e=x^{-1}$$therefore  $$yz\cdot x=yzx=x^{-1}\cdot x=1$$and the statement has been proved.
Answer: Here $xyz=1$ gives
$$\begin{align}
x^{-1}xyz=x^{-1}1 & \iff yz=x^{-1} \\
&\iff yzx=x^{-1}x \\
& \iff yzx=1,
\end{align}$$
which gives
$$\begin{align}
y^{-1}yzx=y^{-1}1 & \iff zx=y^{-1} \\
& \iff zxy=y^{-1}y \\
&\iff  zxy=1.
\end{align}$$


Add/Remove CSS class attributes to respect to the class not based on Div id

Question: I have a CSS elements defined as below:
.myRedClass
{
  background-color:red;
}

And it is assigned to many Divs( that are having similar appearance). At some point i need to assign some left-margin also. What i am currently doing is; I will add and remove a Predefined Class .redClass-margin{margin-left:10px} to each of the required div. The code for this is:
$( "myDiv1" ).addClass( "redClass-margin" );
$( "myDiv2" ).addClass( "redClass-margin" );
$( "myDiv3" ).addClass( "redClass-margin" );

and so on... Instead for this Can i do changes in the existing css class. Is their any possibility to change the  .myRedClass like the following :
.myRedClass
    {
      background-color:red;
      margin-left:10px;
    }

Either Through script or through c#
Answer: You can't edit an existing css stylesheet.
There's a different approach though. If you just want to find all divs that have class myRedClass, and add redClass-margin, you can find them all with jquery and add class.
$('.myRedClass').addClass('redClass-margin');

Answer: I really don't get why you want to do this I would just create a new classand append the class name to each element like Eric mentioned.
However there is a here that tell you how to do what your asking.
Alternatively you could inject rules into your style sheet, again a weird way to do it. See this.


Trigonometry Identity (Proof): $ \sin^4\theta +\cos^4 \theta =1-2\sin^2 \theta \cos^2 \theta $

Question:

Question: Prove that  $$ \sin^4\theta +\cos^4 \theta =1-2\sin^2 \theta \cos^2 \theta $$

What I have attempted (Usually I start of with the complex side)
So starting with the LHS
$$ \sin^4\theta +\cos^4 \theta =1-2\sin^2 \theta \cos^2 \theta $$
$$ (\sin^2\theta)^2 + \cos^4 \theta =1-2\sin^2 \theta \cos^2 \theta $$
$$ (1-\cos^2\theta)^2 + \cos^4 \theta =1-2\sin^2 \theta \cos^2 \theta $$
$$ (1-\cos^2\theta)(1-\cos^2\theta) + \cos^4 \theta =1-2\sin^2 \theta \cos^2 \theta $$
$$ 1 - 2\cos^2\theta + \cos^4\theta + \cos^4\theta =1-2\sin^2 \theta \cos^2 \theta $$
$$ 1 - 2\cos^2\theta + 2\cos^4\theta  =1-2\sin^2 \theta \cos^2 \theta $$
Now I am stuck... is my approach correct?
Comment: I'd try substituting $(1-\cos^2\theta)$ for $\sin^2\theta$ in your last line, to get everything in terms of cosines. EDIT: Or, if you don't want to change the right hand side, factor out $2\cos^2\theta$ from two of the terms on the left.
Comment: Hint:

$\cos^4\theta+\sin^4\theta = (\cos^4\theta+2\sin^2\theta\cos^2\theta+\sin^4\theta) -2\sin^2\theta\cos^2\theta$

can you show that
$\cos^4\theta+2\sin^2\theta\cos^2\theta+\sin^4\theta = 1$?
Answer: Alternatively, you may just square the identity

$$
\cos^2\theta +\sin^2 \theta=1
$$

giving
$$
\cos^4\theta+2\cos^2\theta\sin^2\theta +\sin^4 \theta=1.
$$
Comment: @dydxx So take your identity, add $2\sin^2\theta\cos^2\theta$ to both sides, and factor the left hand side.
Comment: But don't I have to use the identity given and manipulate it and thus prove it?
Comment: You are allowed to do so, but I don't know if your approach can lead easily to the answer.


Radio button & Option list values migrate successfully with Feeds Importer but disappear in node edit

Question: I'm doing a couple data migration projects. I'm using Feeds Importer and for the most part, things are going well.
But when I migrate option list fields, I get this weird thing where the data is migrated OK (I see it when I view the node and I see it in the appropriate table in the database), but when I edit the node, the option list field is empty/not-selected.
On one of the projects, I was using the radio button widget and the work-around ended up being changing the field's widget from that to Select list.
But on my second project, I was already using the Select List widget, and I can't seem to work around the problem. Tried changing it to radio buttons (hey - I'm not picky), but it didn't help.
It's a really sinister problem because it means I migrate the client's data OK, but when they edit one of these nodes, they will essentially delete data because the radio button or select list widget is not displaying the data. Help?
Comment: Did you go the field settings for that field and made sure that the values of the field list are present there?
Answer: I don't have enough reputation to comment, so I'm posting this as an answer.
I'd suggest that you install and enable the devel module to compare the data structure of the field in question in these three situations:

when the data is input manually
when the data is loaded via feeds
when the data loaded via feeds is later edited

If you haven't used it, with Devel installed, you can get the 'devel' view of the node.
Comment: Thanks, caelbtr! Good advice. I didn't actually use the devel module though it is great for many things. But I did set one of the fields manually and saved it so I could scrutinize it in the database. While doing that, I realized my mistake: I had a trailing space at the end of my key! So I had my Option list value settings like this:
Answer: Thanks, caelbtr! Good advice. I didn't actually use the devel module (though it is great for many things).
But I did set one of the fields manually and saved it so I could scrutinize it in the database. While doing that, I realized my mistake: I had a trailing space at the end of my key! So I had my Option list value settings like this:
Yes |Yes
No |No

Changing it to...
Yes|Yes
No|No

...makes the migration (using Feeds Importer) work correctly.
It's fascinating that a trailing space would cause this behavior - but there you go! ; )


Can I use Python 3 super() in Python 2.5.6?

Question: Can I use clean Python 3 super() syntax in Python 2.5.6?
Maybe with some kind of __future__ import?
Answer: I realize this question is old, and the selected answer may have been correct at the time, but it's no longer complete. You still can't use super() in 2.5.6, but python-future provides a back-ported implementation for 2.6+:
Install python-future with:
% pip install future

The following shows the redefinition of super under builtins:
% python
...
>>> import sys
>>> sys.version_info[:3]
(2, 7, 9)
>>>
>>> super
<type 'super'>
>>>
>>> from builtins import *
>>> super
<function newsuper at 0x000000010b4832e0>
>>> super.__module__
'future.builtins.newsuper'

It can be used as follows:
from builtins import super

class Foo(object):
    def f(self):
        print('foo')

class Bar(Foo):
    def f(self):
        super().f() # <- whoomp, there it is
        print('bar')

b = Bar()
b.f()

which outputs
foo
bar

If you use pylint, you can disable legacy warnings with the comment:
# pylint: disable=missing-super-argument

Answer: You cannot use a bare super() call that contains no type/class.  Nor can you implement a replacement for it that will work.  Python 3.x contains special support to enable bare super() calls (it places a __class__ cell variable in all functions defined within a class - see PEP 3135

Update
As of Python 2.6+, bare super() calls can be used via the future Python package. See posita's answer for an explanation.
Comment: Thanks. I was confused because an earlier version of this PEP said you'd import it with `from __future__ import new_super` which doesn't work.
Answer: No you cannot.  But you can use Python 2's super() in Python 3.
Answer: Note This is a terrible "solution", I post it only to make sure you don't do this at home!
I repeat: do not do this
One may think about using this mixin
class Super(object):
    def super(self):
        return super(self.__class__, self)

to obtain a self.super():
class A(object, Super):
    def __init__(self):
        print "A"

class B(A):
    def __init__(self):
        print "B"
        self.super().__init__()

yielding:
 >>> a = A()
 A
 >>> b = B()
 B
 A

But beware: This self.super() is not equivalent to super(B, self) - if A also called self.super().__init__(), the construction of a B would cause the A constructor to call itself indefinitely, since self.__class__ will remain B. This is due to the lack of the __class__ mentioned in the accepted answer. You can possibly work around this issue with a hidden state machine or a sophisticated metaclass that e.g. checks the actual class's position in self.__class__.mro(), but is it really worth it? Probably not...


Textbooks on permutation groups?

Question: I need good texts on group theory that cover the theory of permutation groups. I think there is a book called Wielandt. Is it good? are there newer alternatives? Can I find books that are not specifically about representation groups that cover thoroughly the most important results? Also, when browsing Amazon I kept getting sent to books on representation theory of finite groups, would this be a good way to approach the topic? I got interested in the topic thanks to this question I asked recently.
Thank you very much in advance.
Regards.
Comment: you can always start with knuth's volume 4a.
Comment: @M.Vinay, not abstract permutation groups. if you are looking for abstract/pure permutations groups then there is wielandt or sagan that i know of.
Comment: @abel I found a PDF online (http://www.cs.utsa.edu/~wagner/knuth/fasc2b.pdf) and it does have some group theory (definition of group of permutations, and Cayley graphs), but focuses on algorithmic aspects. It doesn't have anything on more group theoretic topics such as subgroups and automorphisms.
Answer: Wielandt's book is quite old now, but still good. If you are looking for more recent books, at the beginning postgraduate level, then there is "Permutation groups" by Peter J. Cameron, and (believe it or not) "Permutation groups" by J.D. Dixon abnd B. Mortimer.
Comment: I was just going to suggest Dixon. I came across this in a citation on an algebraic graph theory paper!
Comment: I am planning to read Dixon's book. So I wonder why there is a "(believe it or not)". Is there some minor disadvantage for this book?
Comment: I am struggling to remember, but I think that was just a reference to the fact that several books on permutation groups have the title "Permutation Groups". No there is no particular disadvantage to the book by Dixon and Mortimer, but it is aimed at people who already have some general knowledge of group theory.
Answer: A very good book is Donald S. Passman, Permutation Groups. And yes, Helmut Wielandt's book Finite Permutation Groups.
Answer: You might appreciate Sagan's book The symmetric group; it covers, well, its namesake. It is largely focused on the representation theory of $S_n$, but covers other topics as well.

Textbooks on permutation groups?


Having problems with else statement

Question: I am currently trying to make an order game. The user had to press the buttons in the order given. How ever I am having some problem with the else statement. This is my code.
private OnClickListener click2 = new OnClickListener() {
        List<Integer> mClickedButtonIds = new ArrayList<Integer>();

        @Override
        public void onClick(View v) {

        mClickedButtonIds.add(v.getId());
        if (mClickedButtonIds.size() > 4 )
        {
            mClickedButtonIds.remove(0);
            int[] mDesiredOrder = new int[] { R.id.imageButton1, R.id.imageButton2, R.id.imageButton3, R.id.imageButton4 };

            if (mClickedButtonIds.get(0) == mDesiredOrder[0]
                && mClickedButtonIds.get(1) == mDesiredOrder[1]
                && mClickedButtonIds.get(2) == mDesiredOrder[2]
                && mClickedButtonIds.get(3) == mDesiredOrder[3]
                )
            {
                tv1.setText("Correct");

            }

            else
            {
                 tv1.setText("Wrong");
            }

        }
    }
    };

If I play the game for the first time, the else statement work perfectly. But if I play the game again without closing the application, the else statement start to have problem. Every single button I press will come out the else statement which make my tv1 to set text as Wrong. But the ifstatement still work perfectly. Means that although it keep on set text as Wrong but if I click the final button of the correct order it will set text as Correct. Is there any solution for this?
Comment: `private OnClickListener click2 = new OnClickListener() {
        List mClickedButtonIds = new ArrayList();` do this in onResume(), not onCreate().
Answer: Probably you didn't create a new OnClickListener every game, so the ArrayList was not cleared.
Comment: I solved my problem. I looks like I need to change to ` if (mClickedButtonIds.size() >= 4 )` and remove `mClickedButtonIds.remove(0);`
Comment: See [`ArrayList.clear`](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clear()).
Comment: okay thanks a lot after clearing the `arraylist` it become good. However I still have some problem. This game only need to click 4 time, however I need to click it 5 time in order for it to work if I play the game for the 2nd time after clearing the `arraylist`. Cause if I didn't clear the `arraylist`, the 1st time, I need to click 5 timse but 2nd time, I only need to click 4 times. Is there any method to solve this.
Comment: Does not work. If i change to 3, the word `Correct` did not come out even if I press it in order. I think is due to `mClickedButtonIds.get(3) == mDesiredOrder[3]` requirement is not fulfilled.
Comment: I guess I will just need to add another button for the user to click for nothing. Anyway thanks for helping me to solve my `arraylist` problem.
Comment: `mClickedButtonIds.remove(0);` <-- it's because you removed the first element...!?
Comment: it seems like without the `mClickedButtonIds.clear();` it will not work
Answer: Try Else If for the second block rather than just " Else "
Comment: but if I use `else if` then what is the condition for it?

Having problems with else statement


Como criar uma classe e passar um valor de um atributo no construtor da classe em C#

Question: Olá, estou fazendo uma integração com a API da Tray Comerce e pensei em gerar uma classe genérica com a resposta de listas. Em todas as listagens, a API implementa a seguinte classe de retorno:
public class Response<T>
{
    [JsonProperty("paging")]
    public ResponsePaging Paging { get; set; }

    [JsonProperty("sort")]
    public Dictionary<string, string> Sort { get; set; }

    [JsonProperty("availableFilters")]
    public List<string> AvailableFilters { get; set; }

    [JsonProperty("appliedFilters")]
    public List<string> AppliedFilters { get; set; }

    [JsonProperty(????)]
    public List<T> List { get; set; }

    public class ResponsePaging
    {
        public int total { get; set; }
        public int page { get; set; }
        public int offset { get; set; }
        public int limit { get; set; }
        public int maxLimit { get; set; }
    }
}

O problema é que para cada rota da API que faz uma listagem, o resultado dessa listagem é definido com um nome diferente (ex em {web_api}/orders retorna Orders, em {web_api}/products retorna Products, etc...)
Como eu faço para passar como parâmetro à classe qual será o nome da propriedade que será atribuída ao [JsonProperty(????)] da propriedade List<T> List?
Comment: Pesquisei e parece que você poderá substituir `DefaultContractResolver` e implemente seu próprio mecanismo para fornecer o PropertyName (em JSON). https://stackoverflow.com/a/26883987/194717
Comment: Eu fiz meu ContractResolver, só não sei como implementá-lo. Você tem algum exemplo?, eu to caçando aqui mas só acho como criar mesmo..
Answer: Consegui resolver meu problema com base no que o @tony disse no comentário e também nesse fiddle que encontrei. A resposta foi gerar uma DefaultContractResolver personalizada com esse tratamento em específico e um método de retorno que aplica essa conversão. A solução ficou assim:
public class Response
{
    private JsonSerializerSettings settings { get; set; }

    public Response(string listName)
    {
        settings = new JsonSerializerSettings
        {
            ContractResolver = new ResponseContractResolver(listName),
            Formatting = Formatting.Indented
        };
    }

    public JsonResponse deserializeObject(string json)
    {
        return JsonConvert.DeserializeObject<JsonResponse>(json, settings);
    }

    public class ResponseContractResolver : DefaultContractResolver
    {
        private string ListName { get; set; }

        public ResponseContractResolver(string listName) => ListName = listName;

        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
            list.Where(x => x.UnderlyingName == "List").First().PropertyName = ListName;
            return list;
        }
    }

    public class JsonResponse
    {
        [JsonProperty("paging")]
        public ResponsePaging Paging { get; set; }

        [JsonProperty("sort")]
        public Dictionary<string, string> Sort { get; set; }

        [JsonProperty("availableFilters")]
        public List<string> AvailableFilters { get; set; }

        [JsonProperty("appliedFilters")]
        public List<string> AppliedFilters { get; set; }

        [JsonProperty("List")]
        public List List { get; set; }

        public class ResponsePaging
        {
            [JsonProperty("total")]
            public int Total { get; set; }

            [JsonProperty("page")]
            public int Page { get; set; }

            [JsonProperty("Offset")]
            public int Offset { get; set; }

            [JsonProperty("Limit")]
            public int Limit { get; set; }

            [JsonProperty("MaxLimit")]
            public int MaxLimit { get; set; }
        }
    }

}

A partir dessa classe genérica, eu só preciso tratar o retorno e dizer qual é o nome que irá retornar. Assim 1 só classe "inteligente" e sem gambiarra (né não @rovann-linhalis) resolve o problema da resposta da API inteira e reduz o código drásticamente, como no exemplo abaixo:
class Foo
{
    public int Id { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        // resposta em string json da api (mockup de exemplo)
        string jsonResponse = "{\"fooListTest\":[{\"Id\":1},{\"Id\":2},{\"Id\":4}]}";
        List<Foo> foos = new Response<Foo>("fooListTest").DeserializeObject(jsonResponse);
    }
}

Comment: Muito bom =] +1
Answer: O ideal seria uma herança, assim:
public class Response
{
    [JsonProperty("paging")]
    public ResponsePaging Paging { get; set; }

    [JsonProperty("sort")]
    public Dictionary<string, string> Sort { get; set; }

    [JsonProperty("availableFilters")]
    public List<string> AvailableFilters { get; set; }

    [JsonProperty("appliedFilters")]
    public List<string> AppliedFilters { get; set; }

    public class ResponsePaging
    {
        public int total { get; set; }
        public int page { get; set; }
        public int offset { get; set; }
        public int limit { get; set; }
        public int maxLimit { get; set; }
    }
}

public class ProductsResponse : Response
{
    [JsonProperty("products")]
    public List<Product> List { get; set; }
}

public class OrdersResponse : Response
{
    [JsonProperty("orders")]
    public List<Order> List { get; set; }
}

Dessa forma, quando executar a request para Produtos, se espera um ProductsResponse e para pedidos, OrdersResponse
Comment: sim, entendo que se eu fizer uma herança eu posso resolver o problema mas se caso eu tivesse que implementar novas respostas, eu teria que a todo tempo estender a classe Response por causa de 1 referência. Isso geraria um "mundo" de classes que se resolveria com apenas 1 genérica
Comment: não não...nao disse das classes genéricas.... falei que tem outro método da gambiarra... mas nao coloquei na resposta
Comment: a sim sempre tem rsrs
Comment: uma outra alternativa.... pode ser a famosa gambiarra........ rsrs
Comment: não acho que trabalhar com classes genéricas seja uma gambiarra. Principalmente porque venho de linguagens inteligentes como Python e Javascript que não dependem tanto do tipo...


C Program Sorted Linked List

Question: This program is supposed to create a sorted list and sort each user by first and last name. I cant seem to figure out how to sort the names properly.
I only have an issue with the append_to_list function, the rest of the functions work fine.
When I first start inputting names:
user ID:    Last Name:    First Name:
3                Alex          Alex
2                Jones         Alex
1                andrew        john

it sorts fine until I enter a name that should sort inbetween two of the names
when I enter the name Andrew, Alex this happens.
 user ID:    Last Name:    First Name:
 4                Andrew        Alex
 3                Alex          Alex
 2                Jones         Alex
 1                andrew        john

but Andrew, Alex should be between user 2 and 3

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "user.h"
#include "readline.h"

// function append_to_list takes user input from user, id, name and puts it     to the end of the list
// as well as sorts each name alphabetically
struct user *append_to_list(struct user *family)
{
    struct user *cur, *prev, *new_node;

    // generate memory
    new_node = malloc(sizeof(struct user));

    if (new_node == NULL) {
        printf("malloc failed in append\n");
        return family;
    }

    printf("Enter user ID: \n");
    scanf("%d", &new_node->number);
    printf("Enter user last name: \n");
    read_line(new_node->last_name,NAME_LEN);
    printf("Enter user first name: \n");
    read_line(new_node->first_name,NAME_LEN);

    for( cur=family; cur != NULL; cur = cur->next) {
        if (new_node->number == cur->number) {
                printf("user already exists: %s, %s\n",new_node->first_name,     new_node->last_name);
                free(new_node);
                return family;
        }
    }
    for (cur=family, prev = NULL; cur != NULL
        && (strcmp(new_node->first_name,cur->first_name) < 0)
        && (strcmp(new_node->last_name,cur->last_name) < 0);
            prev = cur, cur = cur->next) {

        if((strcmp(new_node->last_name,cur->last_name) < 0)) break;

        if((strcmp(new_node->first_name,cur->first_name) == 0))

        if((strcmp(new_node->first_name,cur->first_name) < 0)) break;
        ;
        }
        // use strcmp == 0 to see if name already exists
        if (cur != NULL && (strcmp(new_node->first_name,cur->first_name) == 0)
            && (strcmp(new_node->last_name,cur->last_name)) == 0)
        {
                printf("user already exists: %s, %s\n",new_node->first_name, new_node->last_name);
                free(new_node);
                return family;
        }

    // append the linkedlist to the end
    new_node->next = cur;
    // check to see if the node is empty
    if (prev == NULL) {
        return new_node;
    } else  {
        prev->next = new_node->next;
        return family;
    }
}
// function delete_from_list removes a user from the family
struct user* delete_from_list(struct user *family)
{
    struct user *prev, *cur;
    int id;
    int not_found = 0;
    printf("Enter user ID: \n");
    scanf("%d", &id);

    for (cur = family, prev = NULL; cur != NULL; prev = cur, cur = cur->next) {
        if (id == cur->number) {
                // if only one user on family
            if (prev == NULL) {
                family = cur->next;
            // if user is in the middle of family
            // connects prev node to cur node
            } else {
                prev->next = cur->next;
            }
            printf("user deleted: %s ,%s\n",cur->first_name, cur->last_name);
            free(cur);
        }
        else
            not_found = 1;
    }
    if (not_found == 1) {
        printf("user not found\n");
    }
    return family;
}
// function find_user searches the family by ID and matches it with the users name
void find_user(struct user *family)
{
    struct user *p = family;
    int id;
    int count = 0;
printf("Enter user ID: \n");
scanf("%d", &id);

    // compares the family with the user entered ID
    // if the ID is the same count set to 1
    if (p != NULL) {
        for (p = family; p != NULL; p = p->next) {
            if (id == p->number) {
                count = 1;
                break;
            }
        }
    }
    // if count is 1 we know the function found that specific user
    if ( count == 1) {
        printf("user found: %s, %s\n", p->last_name, p->first_name);
    } else {
        printf("user not found");
    }
}

// function printList prints the entire family
void printList(struct user *family)
{
    struct user *p;
    printf("user ID:\tLast Name:\tFirst Name:\n");
    for (p = family; p != NULL; p = p->next) {
        printf("%d\t\t%s\t\t%s\n", p->number, p->last_name, p->first_name);
    }

}

// function clearList clears the entired linked list
void clearList(struct user *family)
{
    struct user *p;
    while (family != NULL) {
        p = family;
        family = family->next;
        if (p != NULL) {
            free(p);
        }
    }
}

Comment: Why do you have name comparisons both in the loop termination condition and in the body of the loop in `append_to_list()`?
Comment: In any case, I think the comparisons in the termination condition and in the loop body are *both* wrong.  At minimum, the case of same last name appears to be handled incorrectly in both places.
Answer: The problem is in the way you compare nodes:
for (cur=family, prev = NULL; cur != NULL
    && (strcmp(new_node->first_name,cur->first_name) < 0)
    && (strcmp(new_node->last_name,cur->last_name) < 0);
        prev = cur, cur = cur->next) { ... }

You should skip nodes that have a lesser family or (the same family name AND a lesser first name).  Fix the comparison this way:
for (cur=family, prev = NULL;
     cur != NULL
     && ((strcmp(new_node->first_name, cur->first_name) < 0)
     ||  ((strcmp(new_node->first_name, cur->first_name) == 0)
     &&   (strcmp(new_node->last_name,cur->last_name) < 0)));
     prev = cur, cur = cur->next) { ... }

And simplify the subsequent code.  You actually do not need any code.  The loop will stop at the insertion point.  Just check if the same last name and first name exists (but what if there are 2 John Does?) and insert between prev and cur, or before family if prev is NULL.
The for loop looks ugly: hard to read, easy to get wrong.  Write a separate comparison function that takes 2 nodes and returns -1, 0, +1 according to the phone book order.  You will use this function for append_to_list and delete_from_list, writing less code, more readable and more consistent.
Comment: The comparison function you mention is sometimes called the 'spaceship' operator <=> in some languages.
Comment: @ChuckCottrill: The spaceship operator comes from Perl. I'm not sure I regret not having it in C...  `<=>` would be more useful in C as a swap operator between 2 lvalues.
Comment: Yes, perl (numerics), ruby (http://stackoverflow.com/questions/26581619/rubys-operator-and-sort-method), php, python (spelled cmp), and ocaml (spelled compare).
Comment: A swap operator would be nice as well.
Comment: @ChuckCottrill: perl predates all of these, except maybe caml if it had this operator at all.  I am not a perl advocate: *if perl did not exist, it should not be invented*.  A swap operator would be nice for C and in the spirit of C, since it is often available as a machine instruction and is quite cumbersome to implement as a function.
Comment: The compare operator `a <=> b` can be written this way in C: `(a > b) - (a < b)`, but the arguments are evaluated twice, so unfit for a macro.
Answer: I think that is a better idea to overlap the comparation operators, and then after that sort your list with some of exists algorithms.
Answer: You have problem with conditions in this loop:
 for (cur=family, prev = NULL;
        cur != NULL && (strcmp(new_node->first_name,cur->first_name) < 0)
                    && (strcmp(new_node->last_name,cur->last_name) < 0);
                prev = cur, cur = cur->next)

Loop will not execute:
(cur=family, family exist)
cur != NULL -> True
(Alex == Alex)
((strcmp(new_node->first_name,cur->first_name) -> 0) < 0 -> False
(Andrew > Alex)
((strcmp(new_node->last_name,cur->last_name) -> 1) < 0 -> False
True && False && False -> False

As a result, you will add new record at the beginning.
Furthermore in the loop you have a bad 'if' code:
if((strcmp(new_node->first_name,cur->first_name) == 0))

if((strcmp(new_node->first_name,cur->first_name) < 0)) break;
;

Doc. strcmp
Tip: Delete useless code in question.
Cheer!
Answer: The for loop will stop right at the point of insertion (between the previous and cur node).
The next part will sort the list even if the new_node is greater than the last node.
If the new node is greater than the last node, cur becomes null, which is //assigned to new_node_>next. prev is therefore equal to cur; thus, prev->next = new_node;
           for (cur=family, prev = NULL; cur!=NULL && ((strcmp(new_node->first_name,
           cur->first_name)>0) || ((strcmp(new_node->first_name,
            cur->first_name)==0)&&(strcmp(new_node->last_name,
            cur->last_name)>0))); prev = cur, cur = cur->next);

      new_node->next = cur;
           if(prev==NULL)
            return new_node;
           else {
           prev->next = new_node;
           return family;
           }

C Program Sorted Linked List


Include image in RSS feed Views display

Question: I'm creating an RSS feed of a basic Blog using Views. This is being picked up by Facebook's Graffitti module. Everything works fine here, except that the image isn't being added to the RSS feed... I've incuded a screenshot of my views settings... I'm using a Style of RSS Feed and Row Style: Node (this is the only type allowed).
How can I get a link to the image into feed?!
screenshot
Answer: If the image is a CCK field, make sure the correct formatter has been selected for the image field and it has not been excluded from the RSS display at admin/content/node-type/YOUR-TYPE/display/rss.
If it's an attached image, check that it is displayed as part of teaser (or full body) and that Feed content is set to teaser (or Full text) at admin/content/rss-publishing.

Include image in RSS feed Views display


UnauthorizedAccessException or how to Enable Microfone for UWP Application

Question: For my very first UWP application project, I wanted to build a small test Programm with speech recognition.
After searchin through some tutorials I came up with the following Code:
private async void initSpeechParts() {
    try {
        if (_recognizer == null) {
            _recognizer = new SpeechRecognizer();
            var lang= _recognizer.CurrentLanguage;
            var functionGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "Functioncall");
            _recognizer.UIOptions.AudiblePrompt = "Give me the name of a Function";
            _recognizer.UIOptions.ExampleText = "Function A";
            _recognizer.Constraints.Add(functionGrammar) ;
            await _recognizer.CompileConstraintsAsync();
        }

        try {
            // Start recognition.
            SpeechRecognitionResult speechRecognitionResult = await _recognizer.RecognizeWithUIAsync();
            var recognizedText = speechRecognitionResult.Text;
            recognizedText = removetokens(recognizedText);
            callTestfunction(recognizedText);
        } catch (Exception ex2) {
            var ee = ex2.Message;
            throw;
        }
    } catch (Exception ex) {
        //Check if user has approved the privacy policy
        const uint HresultPrivacyStatementDeclined = 0x80045509;
        if ((uint)ex.HResult == HresultPrivacyStatementDeclined)
        {
            var messageDialog = new Windows.UI.Popups.MessageDialog(
                "You must accept the speech privacy policy to continue", "Speech Exception");
            messageDialog.ShowAsync().GetResults();
        }
    }
}

My current issue with this Code, is that on the line where it says:
SpeechRecognitionResult speechRecognitionResult = await _recognizer.RecognizeWithUIAsync();

I always get a UnauthorizedAccess Exception. After reading some Posts on Google I came to think that this might be because the application has some Issue with my microphone. So how can I enable the microphone for my application?
Answer: You probably miss the microphone capability in your package.appxmanifest
Just open the manifest in Visual Studio and add the microphone capability from the capabilities tab.
You can also find a sample of speech here if needed : https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/SpeechRecognitionAndSynthesis/cpp/Package.appxmanifest


Let $X,Y$ be r.v.'s on $\Omega$. Do there exist for all laws $\pi$ on $\mathbb R^2$ with marginals $\mu_x,\mu_Y$, a r.v. $Z$ s.t. $\pi=\mu_Z$?

Question: Fix a probability space $(\Omega,\mathcal F,\mathbb P)$, and let $X,Y:\Omega\to\mathbb R$ be random variables with laws $\mu_X,\mu_Y$ respectively. Let $\pi$ be a probability measure on $\mathbb R^2$ with marginal distributions $\mu_X,\mu_Y$. Does there exist a random variable $Z:\Omega\to\mathbb R^2$ such that $\mu_Z=\pi$?
Intuitively this seems true, and if it is true, it seems like something that would be a classical well-known fact in probability. However, I have not read any such statement anywhere.
Answer: Not necessarily. Let $\Omega = \{0,1\}$ have two points and have the probability measure assign equal weight to both of them. Let $X$ and $Y$ both be the inclusion function into $\mathbb R.$ Then these are two random variables with the Beroulli distribution $p=1/2.$ But it's pretty clear we can't, for instance, make a RV $Z:\Omega\to \mathbb R^2$ that has the distribution of $(Z_1,Z_2)$ where $Z_1, Z_2$ are independent Bernoulli's with $p=1/2$ since $(Z_1,Z_2)$ can take at most two values.
Comment: As a somewhat related question, can we construct a probability space which admits $\mathbb R^n$-valued rvs with arbitrary law? This is really all I need.
Comment: @MonstrousMoonshine Yes. $(\mathbb R^n, \mathcal B(\mathbb R^n), \mu)$ with $\mu$ the law in question is such a probability space. (Let the $\mathbb R^n$-valued RV be the identity function.)
Comment: I should have clarified – I meant a single probability space which can simulate *all* $\mathbb R^n$-valued laws.
Comment: @MonstrousMoonshine Do you mean a single space on which for any measure on $\mathbb R^n,$ a random variable with that law exists?
Comment: @MonstrousMoonshine Definitely for $\mathbb R.$ Lebesgue measure on $[0,1]$ should suffice where we map $x$ to $F^{-1}(x)$ (where $F^{-1}$ is the generalized inverse CDF.) For higher dimensions I want to say yes too. Measures with support on the whole space (or any other family of equivalent measures) can always be pushed between one another via the RN-derivative. But I'm not sure how to make it work in general. Sounds like a good question to ask on here (I suspect I'm missing something that is 'standard knowledge').
Comment: Yes, that is what I mean.


How to print entity referenced fields (node) title in node.tpl.php?

Question: I want to print an entity referenced fields (node) title in node--customtype.tpl.php.
<?php print render($content['field_my_entity_reference']); ?> prints the field with some CSS class as below:

Entity Title

What I want to do is to print this field without any pre-defined CSS classes etc..
[field_my_entity_reference] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [target_id] => 11
                            [entity] => stdClass Object
                                (
                                    [vid] => 41
                                    [uid] => 1
                                    [title] => Entity Title
                                    [log] =>
                                    [status] => 1
                                    [comment] => 1
                                    [promote] => 0
                                    [sticky] => 0
                                    [nid] => 11
                                    [type] => project
                                    [language] => es
                                    [created] => 1466009429
                                    [changed] => 1466502663
                                    [tnid] => 0
                                    [translate] => 0
                                    [revision_timestamp] => 1466502663
                                    [revision_uid] => 1
                                    [body] => Array
                                        (
                                            [und] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [value] =>

I tried <?php print $node->field_my_entity_reference['und'][0]['entity']['title']; ?> but it gives error:

Fatal error: Cannot use object of type stdClass as array in

How can I print the title value of entity referenced field in node.tpl.php?
Comment: You can actually print the reference entity using `print render($content['field_machine_name']);`.
Comment: My bad..see my answer.
Answer: OK, without knowing anything about stdClass Object these kind of questions are normal :)
So, after reading a question about stdClass Object in SO I did what I want as below:
<?php print $node->field_my_entity_reference['und'][0]['entity']->title; ?>

This prints the title as plain text.
Note: Is there another way or better way you're always welcome.
Answer: Alternative using the API is to use field_get_items and field_view_value.
Consider this example:
$field = field_get_items('node', $node, 'field_machine_name');
$title = field_view_value('node', $node, 'field_machine_name', $field[0]);
print render($title);

$title will produce...
Array
(
    [#markup] => test lang
    [#access] => 1
)

which is a renderable array.
The advantage of this against print $node->field_my_entity_reference['und'][0]['entity']->title; is the API will take care of the translation.
If you want to still use print $node->field_my_entity_reference['und'][0]['entity']->title I advice to avoid using und instead I will useLANGUAGE_NONE or much better $node->language.
print $node->field_my_entity_reference[$node->language][0]['entity']->title;

Comment: It is the most elegant way.


Ajax e PHP para upload de imagens + cadastro de informações

Question: Estou me batendo desde ontem com um upload de imagens em AJAX. Vou publicar os avanços que tive em estudo e as dificuldades que ainda tenho caso alguém consiga me auxiliar :)
Meu script como sempre fiz (sem imagens) era, basicamente, o formulário
<form id="cadastrar-evento" method="POST" enctype="multipart/form-data">

    Título
    <input class="form-control" type="text" placeholder="Título do Evento" name="titulo">

    Descrição
    <textarea class="form-control" type="text" placeholder="Descrição do Evento" name="descricao" id="descricao-evento" maxlength="240"></textarea>

    Fotos

    <input id="selecao-arquivo1" type="file" name="imagem1">
    <input id="selecao-arquivo2" type="file" name="imagem2">
    <input id="selecao-arquivo3" type="file" name="imagem3">

    <input type="submit" class="btn btn-success" value="Cadastrar Evento" id="botao">

Meu Ajax
//Cadastrar
$('form#cadastrar-evento').submit(function(e){
    e.preventDefault();

    var form = $(this);

    //(...) Validações

    var valores = form.serialize();

    $.ajax({
        type : 'POST',
        url : 'dados/cadastro-evento.php',
        data : valores,
        dataType : 'json',
        success : function(data){
            if(data.status == 1){
                alert(data.msg);
                window.location.href="index.php?pg=eventos";
            }else{
                alert(data.msg);
            }
        }
    });
});

Mas aí, pesquisando, verifiquei precisava trocar o serialize pelo método formData e fiz isso:
//Cadastrar
$('form#cadastrar-evento').submit(function(e){
   e.preventDefault();

   var form = $(this);

   //(...) Validações

   valores = new FormData(form);
    //var valores = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'dados/cadastro-evento.php',
        data: valores,
        contentType: false,
        cache: false,
        processData:false,
        dataType: 'json',
        success: function(data){
            if(data.status == 1){
                alert(data.msg);
                window.location.href="index.php?pg=eventos";
            }else{
                alert(data.msg);
            }
        }
    });
});

Porém meu console apresenta como se o formData não tivesse definido?

No PHP eu retorno um jSON, mas pelo que entendi também não posso utilizar mais o retorno dessa forma. Ou posso?
if($sqlInsereEvento){
    $retorno = array("status" => 1, "msg" => "Evento cadastrado com sucesso!");
    echo json_encode($retorno);
    exit;
}else{
    $retorno = array("status" => 0, "msg" => "Ocorreu algum erro ao cadastrar este evento, tente novamente.");
    echo json_encode($retorno);
    exit;
}

Agradeço desde já se alguém conseguir elucidar essas dúvidas.
UPDATE
Agora não aparecem erros no JS, essa é minha última versão:
    (...)
    valores = new FormData(form);
    //var valores = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'dados/cadastro-evento.php',
        data: {valores},
        contentType: false,
        cache: false,
        processData:false,
        dataType : 'json', //Sem o JSON não recebo retorno do PHP. Recebo Undefined.
        success : function(data){
            if(data.status == 1){
                alert(data.msg);
                window.location.href="index.php?pg=eventos";
            }else{
                alert(data.msg);
            }
        }
    });

Mas aparentemente os valores não chegam no meu PHP. Tentei imprimir os posts e ele só me retorna "oi" no alert.
//(...)

$titulo      = mysqli_real_escape_string($conn, $_POST['titulo']);
$descricao   = mysqli_real_escape_string($conn, $_POST['descricao']);

//Verifica Campos Vazios caso js esteja com problemas
if(empty($titulo) || empty($descricao)){
    $retorno = array("status" => 0, "msg" => "oi $titulo $descricao");
    echo json_encode($retorno);
    exit;
}

Comment: acredito que o seu problema esteja que no post do ajax, você diz que está enviando um dado json, e não está, remova o datatype
Comment: De uma olhada aqui https://pt.stackoverflow.com/questions/9704/fazer-upload-de-arquivo-com-ajax
Comment: @AndersonHenrique aí meu PHP retorna "undefined" pro Ajax e cai naquele último problema que eu mencionei ali. Não tenho certeza como posso retornar os erros pro js :/
Comment: @AndersonHenrique Ah sim, já vi essa questão. Mas sigo com dificuldade de implementar. Nesse arquivo ali ele considera somente envio de imagem (pelo que entendi)
Comment: tenta assim: data:{valores}
Comment: @JorgeMatheus hummm, parou de retornar erro no console. Agora o js apresenta um alert vazio. Vou fazer uns testes no meu PHP e confirmo. Mas talvez tenha resolvido :)
Comment: Então, você tem que mandar  um objeto no data, por isso tem que ter as {}. Se for isso, eu respondo e você marca como correto.
Comment: @AryanaValcanaia Acredito que o problema esteja no php, vamos lá, siga os passos, indique a posição do new Form, sei que está pegando o evento por id mas só por precaução, data = new Form($('form#cadastrar-evento')[0]), remova o datatype: json, para que o ajax use o metodo correto automaticamente, e se puder edite e coloque o seu php recebendo o POST
Comment: @AndersonHenrique acho que o js mesmo :/
Comment: @JorgeMatheus o problema é no ajax que não envia as infos pro PHP. se eu refazer o ajax usando o serialize() ele passa todas as infos (exceto $_FILES)
Answer: Ajustei o js e resolvido :)
HTML
<form id="cadastrar-evento" method="POST" enctype="multipart/form-data">

   Título
   <input class="form-control" type="text" placeholder="Título do Evento" name="titulo">

   Descrição
   <textarea class="form-control" type="text" placeholder="Descrição do Evento" name="descricao" id="descricao-evento" maxlength="240"></textarea>

   Fotos

   <input id="selecao-arquivo1" type="file" name="imagem1">
   <input id="selecao-arquivo2" type="file" name="imagem2">
   <input id="selecao-arquivo3" type="file" name="imagem3">

   <input type="submit" class="btn btn-success" value="Cadastrar Evento" id="botao">

</form>

Ajax
$("form#cadastrar-evento").submit(function(e) {
    e.preventDefault();

    var data = new FormData(this);

    $.ajax({
        url: "dados/cadastro-evento.php",
        type: "POST",
        data: data,
        mimeType: "multipart/form-data",
        dataType : 'json',
        contentType: false,
        cache: false,
        processData:false,
        success: function (data) {
            alert(data.msg);
        }
    });
});

PHP capturo post e files e manipulo normal de acordo com o que eu quiser
//Textos
$titulo      = $_POST['titulo'];
$descricao   = $_POST['descricao'];

//Imagens
$imagem1     = $_FILES['imagem1']['name'];
$imagem2     = $_FILES['imagem2']['name'];
$imagem3     = $_FILES['imagem3']['name'];

//Exemplo de retorno
//Verifica Campos Vazios caso js esteja com problemas
if(empty($titulo) || empty($descricao)){
    $retorno = array("status" => 0, "msg" => "Você precisa preencher os campos obrigatórios.");
    echo json_encode($retorno);
    exit;
}

Comment: posta a resposta completa!!
Comment: @LeoCaracciolo Achei que em conjunto ao enunciado havia ficado claro. Resposta editada.
Comment: Assim sua resposta ficou melhor de entender!!


Datepicker é mostrado por de trás do modal bootstrap

Question: Tenho um modal em bootstrap:

    <button type="button" class="close" data-dismiss="modal">×</button>

Agendar reunião do evento <?php echo $row- >denominacao; ?>

        <?php echo form_open('utilizador/alterarAgendamento'); ?>

              Data

                <input type="hidden" value="<?php echo $row->idevento; ?>" name="idevento" />
                <input type="text" class="form-control data_inserir" readonly="readonly" name="data" />

              Hora

                <input type="text" class="form-control timepicker" name="hora" />

              Notas
              <textarea class="form-control" rows="3" name="nota" placeholder=""> </textarea>

          <button type="submit" class="form-control">Re-Agendar</button>
          <?php echo form_close(); ?>

O input com a class data_inserir está a chamar a função dataPicker, mas esta aparece por trás do modal e não estou a conseguir fazer com que fique à frente.
Answer: Isso normalmente é um problema com o z-index, tente adicionar um valor de z-index mais alto na sua class de exibição do DatePicker como por exemplo:
.suaClassDatePicker {
    z-index: 100000;
}

Comment: Brunno, Obrigado, com o .datePicker não funcionou, mas alterei no css .datepicker.dropdown-menu {z-index:1000;} para  .datepicker.dropdown-menu {z-index:10000;} e já funcionou obrigado
Comment: @LaranjaMecânica, amigo de um olhada nesse [**jsfiddle**](http://jsfiddle.net/buh159/93eTU/1795/), nele eu estou forçando o z-index. Se por acaso não funcionar na sua aplicação, sugiro atualizar a biblioteca para versão mais nova. teste e me de um feedback aqui :)
Comment: já tentei, até ja alterei o código do .js com a versão que diz que está corrigida mas não funciona :/
Comment: Qual datepicker voce está usando ? O do jquery-ui?
Comment: olá, é este, https://github.com/eternicode/bootstrap-datepicker/
Comment: @LaranjaMecânica, legal qualquer coisa é só chamar :)


Powershell EnvDTE Switch Visual Studio Session (Multiple Separate Solutions open)

Question: Here is what I am trying to do... I have two separate Visual Studio solutions open, they are completely separate solutions, and I want it to remain that way.  Solution 1 is what my powershell DTEObject is pointing to.  I want to be able to switch to Solution 2, and open a file in that session.
Here is the powershell code I am using to get the DTE object and executing the open file command:
<code>$dteobj = [runtime.interopservices.marshal]::getactiveobject('VisualStudio.DTE')
$dteobj.ExecuteCommand("Open ""$file""")
$dteobj.ExecuteCommand("Edit.Goto $line")
</code>
The reason why I want to switch solutions is because I want to then bring focus to the window of the solution that contains that file so that it doesn't confuse people about what files are in what solutions.  Hopefully that makes enough sense.
Comment: In order to do this, you need to delve down into the running object table.  Here starts the rabbit hole for ye https://stackoverflow.com/questions/11835617/understanding-the-running-object-table don't take any pills while underground.
Answer: I figured it out.  You can use the powershell command Get-RunningObject from the PSCX module, and you have to select that object's DTE
<code>$dteObj = Get-RunningObject | Where-Object {$_.FullName -eq "$solutionDir$solutionName"} | Select-Object DTE
$dteobj.DTE.ExecuteCommand("Open ""$file""")
$dteobj.DTE.ExecuteCommand("Edit.Goto $line")
</code>
Comment: Oh, lol I didn't even know that. I know I have that module though. I have edited my answer to include that info
Comment: Powershell 5.1, no modules to install. same idea though. https://github.com/jefflomax/visual-studio-dte-utilities/blob/main/getDteBySolutionName.ps1
Comment: You might want to add some details that the `Get-RunningObject` command comes from the open source PSCX module, and is not built in.


Updating has_one :though with a has_many-style join table

Question: I have the following models
class Widget
  has_one :widget_sprocket
  has_one :sprocket, through: :widget_sprockets
end

class Sprocket
  has_many :widget_sprockets
  has_many :widgets, though: :widget_sprockets
end

class WidgetSprocket
  belongs_to :widget
  belongs_to :sprocket
end

This works fine in the console, but I'm struggling with view updates for Widget. has_many :through gives Sprocket widget_ids, which I believe can be treated like a local attribute for most purposes, but the Rails docs evidently expect a different table configuration for has_one :through and therefore doesn't define a sprocket_id on Widget. As a result code like this throws an unknown attribute error
<%= f.collection_select(:sprocket_id, Sprocket.all, :id, :sprocket_type)  %>

Of course I could use has_many :through for both models, but I consider it a last resort.
Answer: I think you're falling for a classic trap and overcomplicating this. If you want a one to many assocation between Sprocket and Widget you should just be using belongs_to and adding a sprocket_id foreign key column to the widgets table:
class AddSprocketToWidgets < ActiveRecord::Migration[6.1]
  def change
    add_reference :widgets, :sprocket, null: false, foreign_key: true
  end
end

class Widget
  belongs_to :sprocket
end

This guarentees on the database level that a Widget can only have one Sprocket because the column can only hold one single value. Your join table gives no such guarentee. You're really just selecting the first matching row off the join table and its actually a many to many relation. Unless thats acceptable or you prevent it with unique indexes thats an invitation for some nasty bugs.
While there are scenarios where you actually need an intermediadary table that describes a one to many relation - YAGNI.

has_many :through gives Sprocket widget_ids, which I believe can be treated like a local attribute for most purposes

Its not an attribute in any way or form. Its a method which will actually do a SELECT id FROM other_tablequery unless the assocation is preloaded.

but the Rails docs evidently expect a different table configuration for has_one :through and therefore doesn't define a sprocket_id on Widget.

Classic noob trap caused by the confusing semantics of the method names. has_one means there is a foreign key column on the other models table. Its like has_many but with a LIMIT 1 tacked onto the end of the query. To get the id you would actually call other.id.
In the case of belongs_to its not the relations macro that creates the attribute. Its having an actual sprocket_id column on the widgets table.
If you actually wanted to go though creating an intermediary table you  can't just assign an id. You would have to use nested attributes and fields_for to create or update a WidgetSprocket instance. Again YAGNI.
Comment: Hi Max. I did find your [response](https://stackoverflow.com/a/61039617/965613) to a similar question, but for reasons I won't get into, I'm confident that my situation is different and that the relations I described are the ones I need. What I take from your answer is that I should either use many-to-many on both models or nested attributes / `fields_for` (which I did try to implement for this, but may have done incorrectly).


Do all songs have to be in a major or minor scale? Can a song have random notes that don't belong to any major or minor scale?

Question: For example, every scale has a given set of notes. But is it possible that there's a composition which doesn't fall into one particular scale?
Comment: You should really listen to some Stockhausen for example. Extreme example, but it does answer your question (depending on what you mean by song).
Comment: I have never seen a composition that *does* fall into one exact scale all the way through.
Comment: Whoa, whoa. I did say *some* christmas songs, first of all, and I disagree completely with your statement that children's songs aren't music. How can anyone defend that?
Comment: There is some relevant information here: https://music.stackexchange.com/questions/846/where-should-i-go-to-learn-about-non-western-scales-particularly-turkish-gree
Comment: https://en.wikipedia.org/wiki/Atonality
Comment: @Quintec Childrens' songs? Some christmas songs?
Comment: @user45266 Most christmas songs actually use the II quite often, and children's songs aren't real music :P
Comment: "Apparently, this user prefers to keep an air of mystery about them."
Answer: No, not all songs have to be in a major or minor scale. All that it takes to prove this is to find one example that goes against the rule:

This melody, which has both C♯ and C♮, cannot belong to a single major scale. (It also has both F♯ and F♮.)
Most compositions, however, do have what we call a tonic. This is a pitch center, a "home base" of sorts, to which most works will return. However, all pitches in a work do not have to belong to a member of the tonic pitch's scale.
The pitches that belong to the tonic scale are what we call diatonic pitches. Chromatic pitches are pitches that don't belong to the tonic scale, and they are very, very common.
A composition can certainly have random notes that don't belong to the tonic's major or minor scale, but often there is an underlying logic to which pitches are used. Thus the pitches aren't "random," but often have some function that relates to the sounding pitches.
Your question is well-formed and a good one, but I will make one correction: "Can a song have random notes that belong to any major or minor scale?" The fact is that any pitch will belong to some major or minor scale (however theoretical), so it's impossible (as I see it) for a note not to belong to any scale.
Comment: But then that pitch just belongs to a major scale built on an out-of-tune tonic, no? At least, that was my logic.
Comment: It would make more sense to say there's no major or minor scale with B-C-C# - two semitones in a row.
Comment: `so it's impossible (as I see it) for a note not to belong to any scale.`

Sure it can, if it's out of tune ;)
Comment: C, C#, F and F# all belong to C#/Db major, don't they? The notes of this melody still don't seem to fit in any major scale, but it's not enough to mention those 4 notes.
Comment: @EricDuminil In my view it is enough to just mention those four notes, because C♯ major doesn't have C♯ and C♮, it has C♯ and B♯; there's a big difference!
Comment: Just consider the 11th note of the American National Anthem. It can be considered as a momentary excursion to a related key (the dominant).

Similarly one could harmonise "Wish upon a star" so that as we reach the C#, the harmony is hinting at another scale. Dm would be an obvious choice. It's the ii chord of C. So we might look to do a ii -> V -> I progression. And we CAN harmonize bar 3 with V (G major). But Bar 4, with the F#, is suggesting a IV chord in G Major rather than a I in C Major, which creates a sense of intrigue -- so near yet so far!  Where next?  How to reach home?
Comment: Adding to this: many singers produce notes that are not one of the 12 notes found on the piano. This isn't because they are singing "out of tune", it is because they are using vocal technique to produce exactly the effect they want to achieve. I'm pretty sure I hear this when Nancy Sinatra sings the descending scale in "these boots are made for walking", and Ella Fitzgerald does it all the time.
Answer: The answer is basically you can do what you want, nothing has to be anything in music.
The less trivial answer depends a bit on what you mean. Pieces generally are not described as being in a scale. They are often described as being in a key which has a scale associated with it, but any piece that's more than a simple tune will certainly have notes that are not in the scale associated with the key. Take for example the second note of Beethoven's Für Elise - the piece is in the key of A minor, the second note is a D-sharp. D-sharp is not part of the A-minor scale, but the piece is clearly in A-minor.

It's also possible for a piece not to be in a key, or for the key it is in to be ambiguous. 19th century European music has many example of pieces where the key is difficult to pin down as the composer exploits ambiguity in tonal relationships. A classic example is the first song in Robert Schumann's song cycle Dicterliebe — Im wunderschönen Monat Mai. The key signature has three sharps suggesting A major or F-sharp minor, but it neither begins nor ends on one of those chords and most of the piece shifts between tonalities.
In the 20th century, of course, we get works from a lot of composers including those of the New Viennese School, like Schoenberg and Webern, that explicitly avoids any association with keys writing music described as atonal. You also find microtonal which truly has notes that are not part of any major or minor scale because the composer is asking for smaller divisions of the octave than major or minor scales can accommodate.
Comment: That D# in the first phrase of Fur Elise -- am I the only person who can hear it as the "blues note" (aug 4th) in what would be an A blues scale (i.e. A minor pentatonic + #4, i.e. blues note)?
Answer: There's alot of different types of scales, apart from major and minor. For example: you cannot produce the song, Misirlou in a major or minor scale; you'd have to play it in a special scale called the Phrygian Dominant. And this song, Scarborough Fair, is in Dorian.
But to go to the essence of your question, every song (for the most part) has a certain scale, basically everything you hear on the radio.
There was a study on this on Spotify. Where 66.1% of songs accounted for a major scale, and 33.7% were minor. Which comes out to 99.8% either being in a major and minor scale where the rest 0.2% is other scales or modes (which are also scales btw). 0.2% that seems low. maybe there's a problem in their study. not sure. But regardless, major and minor scales seem to be the most "popular" in western culture.
Similarly, if you look at National Anthems Map. The majority are either in major or minor.
Also there's another study that hooktheory did who analyzed 1300 songs.
Songs may have notes that go outside of a scale from time to time (due to secondary dominants, chromaticism, mode mixing, etc), but the majority of the notes will fall into a certain scale and songs are generally identifiable by their scale/key. That's why musicians spend many hours learning and practicing scales, because they are the basis of music, as both the melody and harmony is derived from a scale. If a song shifts between multiple scales it's called a modulation.
Comment: I'd bet a lot of songs covered in the Spotify study were in a minor key but didn't fit in any one of the harmonic/melodic/natural minor scales, or were in a major key but didn't exclusively use one major scale.
Comment: Another example: I wonder what key the Spotify study would classify "Livin' On a Prayer" as. The piece fluctuates between E minor (relatively Aeolian with the flattened 7th) and G major, then jumps to B flat major. At this point, it isn't using one particular scale anymore, but I'd probably still say that this song has a single key (it's mainly in).
Comment: I see 66.1% major and 33.7% minor, for a discrepancy of 0.2%. There is no suggestion on the linked page that "other scales or modes" account for the discrepancy, which is well within the range of rounding errors in the data reporting. Further, the page does not say that these percentages apply to major scale vs. minor scale usage, but to key signatures. Major scales and major keys are not the same thing.
Comment: The study might consider, e.g. a song in Dorian to be in a minor key, or a song in Lydian to be in a major key. I don't know what the percentages should be, but a fair amount of rock, pop, and hip-hop can be thought of as modal, so I'm guessing that this is the case.
Comment: @DavidBowling ok I fixed it to 66.1. and I agree something is fishy about that study. I would suspect modes and other scales to account for about 10% or so of music atleast. no? :P
Answer: There are no laws forbidding you to include anything in a composition. Any note is allowed, even "false" notes. Some examples are (I suggest doing some googling):

Twelve-tone technique
Microtonality

In some genres of music, the conventions are more rigid in some less. In beginning music theory you will learn about some of these more or less traditional conventions. One example is staying in a certain key or succession of keys: say I, V, IV (example C,G,F). Another example might be staying in a specific scale: say Mixolydian. Learning and knowing how to use these conventions is one part of the handicraft of composing. It might help, or it might hinder depending on where you want to go.
Answer:
Do all songs have to be in a major or minor scale?

No, definitely not! Have a look at https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes to start to get an idea of the possibilities...

every scale has a given set of notes

Hmmm.... I don't think even that's necessarily true - or to put it another way, a scale isn't necessarily only defined as a given set of notes. For example, the blues scale, when played on instruments that allow it, implies bending certain notes within certain ranges - and that can be seen as part of what it means to use that scale.

But is it possible that there's a composition which doesn't fall into 1 particular scale?

It depends what you mean. Often when we talk about the scale used by a piece, it's only an approximation of the tonality of the piece, and notes outside the scale are expected.
Outside of that, a piece might use a definite set of notes without a well-known name, or it might not restrict itself to a definite set of notes. Many songs also use sounds with timbres that might make identification of exact pitch uncertain.
And of course, some compositions have one or more obvious key changes - meaning that they move from using one scale to using another.
Answer: No, they don't:
Even if there no scale exists the composer may everytime invent an own new scale.
https://en.wikipedia.org/wiki/Twelve-tone_technique
Answer: Most of the answers seem to imply that 'keys' are central to music. There are also some conflicting definitions involved - Bach's famous C-major Prelude has sharps and flats everywhere, but most musicians would say that the piece is definitely in C-major, with some "accidentals" thrown in. Most music derived from European cultures works this way, with a central key departed from by harmonies or accidentals to create tension, which then is released by returning to some simple harmony based on that key. But there are other kinds of scales, in, e.g., Iranian or Chinese music; other kinds of criteria for creating satisfying music, in, say, Indonesian gamelan or Indian raga music; and even just doing without any kind of center the way many modernists do. This last kind of music can sound cacophonous, but can also be beautiful, singable, and approachable. Examples:
Bach, 1st C Major Prelude, BWV846:

Iranian: some classical Persian folk music:

Chinese: Ballad of North Henan Province:

Gamelan: Sound Tracker [?]:

Raga: Anoushka Shankar et al., "Joug"[?]:

Anything Goes: William Schuman, "Prayer", from his opera The Mighty Casey:

Wikipedia has a lot of information about these forms and, of course, a whole heck of a lot of other stuff, related and not.
Answer: Yes, if your intention is to commercialize it.  No, if you don't care that no one will ever want to listen to it.
Most commercial music fits rather nicely into a scale; in that way, often music written with the purpose of making money tends to "play by the rules" more than music that is written without that intent, as it is more of a safe bet to stick to the basics (listeners tend to like familiar things).
Comment: And some are making money just with square notes weired tunes. Any way: upvote!


Formalism of syntax in first order logic

Question: I am attending a introductory model theory course this semester. The professor started talking about formulas and sentences without paying much attention to the formalism of the syntax. However, as the course progressed, I began to notice that we need to put the formulas in a set because Zorn's lemma is needed to prove theorems like the compactness theorem. So I was thinking probably we would need to define formulas and sentences as elements of the free monoid generated by the formal symbols.
This construction leads to many questions that were overlooked and that have to be checked, for example, the necessity of introducing parentheses. My thoughts are: Are these technical details that can somehow be avoided, or are they necessary as the foundation of first order logic?
Comment: It is formal because we have to follow rigorousely the syntactical specifications, in order to avoid errors and ambiguities. Details may be different, like the usage of parentheses: we may omit them adoptong abbreviations that can improve human readibility, but we have to consider tha, in princple, formulas must be "machine processed".
Comment: FOL is not a super complicated language, so for most work with FOL I think the professor can get away with not defining a rigorous formal syntax. But when you start proving technical meta-logical results about FOL you really should lay out that syntax. And, as Mario says, if you want a computer to work with FOL, you definitely need it.
Comment: This [question](https://math.stackexchange.com/q/4873895) might be related.
Comment: And see [Logical and non-logical symbols in a logic system](https://math.stackexchange.com/questions/873183/are-variables-logical-or-non-logical-symbols-in-a-logic-system) as well as [In Mathematical Logic, What is a Language?](https://math.stackexchange.com/questions/802963/in-mathematical-logic-what-is-a-language)
Answer: The usual formal approach in textbooks is to treat syntactic classes such as formulas or terms as subsets of the set of all strings (lists) of symbols drawn from a small vocabulary (yes, the set of all lists is a free monoid, but that fact doesn't add much value in this context: you just need to know that you can construct new lists from old by prefixing or postfixing a list with a symbol or by concatenation of two lists). The subset is typically defined by saying that is the smallest set closed under certain constructions.
So, for example, we might have a vocabulary comprising variables  $x_1, x_2, \ldots$, a single (binary) operator symbol $+$ together with brackets and commas as punctuation symbols. We could then define the set $\cal T$ of all terms to be the smallest set of strings of these symbols that:

Contains each string "$x_i$" comprising a single variable.
Contains "$(t_1+t_2)$" whenever it contains $t_1$ and $t_2$ (here I have taken $t_1$, prefixed it with "(", postfixed with "+", concatenated it with "t_2" and then postfixed with ")").

Here, for readability I am letting $\LaTeX$ show the strings with spaces and these are to be ignored. So "$x_1$", "$x_2$" and "$(x_1+x_2)$" are all terms as is "$((x_1+(x_2+x_3))+x_4)$", but "$+x_1$", "$x_1+x_2$", "$((x_1+x_2))$" and $(x_1+x_2)+x_3$" are not.
Typically, formal reasoning about syntactic classes is done at the lowest level by complete induction on the length of the strings. With the above definition, an important property you might want to prove of $\cal T$ is that any term $t \in \cal T$ is either a single variable or has the form $(t_1+t_2)$ for some uniquely determined $t_1, t_2 \in \cal T$. (The definition is very precise about the placement of brackets to ensure this.) Having proved a result like that, you know that every term is either atomic (a variable) or is uniquely represented by combining two sub-terms with the operator symbol (together with some brackets that are just there to make things unambiguous). So you can prove properties of terms at a slightly more abstract level by induction over the structure of a term: i.e., by showing that a property holds of atomic terms and holds of any term if it holds of its sub-terms.
As has been suggested in the comments, in an introductory course, you may be able to skip over some of these details, e.g., just by assuming the more abstract point of view, where a term can be viewed as a tree with leaves labelled by atomic symbols and nodes labelled by operator symbols (and this is how you would represent syntax in a computer implementation of formal syntax). With such an approach you would use informal linear representations of the trees like "$(t_1 + t_2) + t_3$" where the brackets are just there to show the order of construction of the tree. You would also very likely adopt conventions for leaving those brackets out, as we do in arithmetic and most programming languages.
[Disclaimer: I have allowed the set of atomic symbols in my example to be infinite: some authors would object to that and require me to work with a finite vocabulary, so that my infinite set of variables would be defined as strings of of symbols of some particular form (just as happens in the definitions of programming languages.]
Comment: I find it a shame that more emphasis is not placed on structural induction in logic courses. It's used a lot, it's more satisfying than induction on formula length, and it's at the core of some current proof assistants (e.g. Coq, which is based on the calculus of inductive constructions).
Comment: @Sambo: I am very much inclined to agree with you. I suspect a lot of authors don't want to digress into the theory of trees. Hopefully, things will change over time as the barriers between the mechanized theorem proving world and the traditional world of mathematical logic break down. Have you come across [John Harrison's book](https://www.cambridge.org/gb/universitypress/subjects/computer-science/programming-languages-and-applied-logic/handbook-practical-logic-and-automated-reasoning?format=HB&isbn=9780521899574)? It's a great resource in this area.
Comment: I haven't, looks interesting! Thanks for the suggestion.
Answer: I'd argue the technical details are necessary but can be avoided. To say you have to study the syntactic details to understand what logic is about is similar to say you have to learn a programming language to understand what an algorithm is. Or you have to know PA to understand arithmetic. Or you have to know how to construct real numbers from ZFC to study real analysis.
Mathematical logic is arguably about syntax, otherwise it would not exist. It's a fundamental insight of Hilbert: No matter how you think about (a theorem or a proof), eventually it can be represented as a string of symbols. To study syntax, it's a basic tool to do induction on the length of symbols (to prove theorems about term, formula and proof), so some weak theory of arithmetic (e.g. PRA ) is necessary (and sufficient). For example, Manin introduced parentheses and used basic arithmetic to prove the "unique reading lemma": there is a unique way to pairing the parentheses; But "the necessity of introducing parentheses" is false, see e.g. Shoenfield's book that used the Polish notation. One of the reasons for not paying too much attention to the details of syntax is its flexibility: Like designing a programming language, it needs to be precise but this can be achieved in many different ways. Or studying syntax is similar to write a compiler for a programming language but if you can read the programs you don't have to know how to mechanically decode.
However, none of us think in terms of syntax (except perhaps Edward Nelson, whose essays are strongly recommended though you don't have to agree with him). Even if Godel's incompleteness theorem is completely about syntax (in particular, he replaced the semantic notion "truth" by the syntactic one "provable".), we always try to attach some material understanding like "self-reference" to it (otherwise, could even Godel be able to construct his proof?). Model theory is a powerful tool, and to use it we have to assume some kind of set theory axioms which is semantically more satisfying as we mentally attach some Platonic reality to it.
But since logic is all about syntax, how do you understand a result proved using set theory such as ZFC (in particular with the help of AC)? Well, it can be interpreted roughly as follows: the result depends on the consistency of ZFC (which is a syntactic assumption, and equivalent to the consistency of ZF). So we think in terms of semantics (if it's hard to imagine a model of ZFC, we all have no trouble to trust the standard model of PA. Even better, we don't have to play dumb, but assume almost anything we know about mathematics even when studying logic.), but the results can always be interpreted in pure syntax (this is not the only philosophical approach, but probably the best in terms of pedagogy).


Why no pid in node object?

Question: I am setting an alias programatically, using path_set_alias() in Drupal6.
Looking at the code of path_set_alias in path.module, I see that if I pass the pid (path id), the old alias(s) for that node will get deleted, which is what I want.
When I load the node, though, I see no pid property set on the node, but the record for the node's alias exists in url_alias table.
Why doesn't pid exist on the node object? Must I retrieve the pid from the url_alias table and then pass that in to path_set_alias to remove the old alias?
Answer: It looks like a bug, see http://drupal.org/node/633916
It's optional to path the pid to path_set_alias() so it should work without passing it.
Comment: It's optional, but if you don't pass it, it won't delete the old alias. See the code for path_set_alias.
Comment: @Aaron I checked the code I'm pretty sure it works fine without pid, because it looks up the old path and make an UPDATE: `else if ($path && $alias) {
    // Check for existing aliases.
    if ($alias == drupal_get_path_alias($path, $language)) {
      // There is already such an alias, neutral or in this language.
      // Update the alias based on alias; setting the language if not yet done.
      db_query("UPDATE {url_alias} SET src = '%s', dst = '%s', language = '%s' WHERE dst = '%s'", $path, $alias, $language, $alias);
    }`
Answer: As you can see in path_nodeapi(), path.module only loads the alias and adds it to the node object, not the pid.
In fact, it is doing it wrong anyway (it is supposed to return new data, not add it to $node) since that won't work in PHP 4. Not that anyone on this world should still use that, but Drupal 6 still officially supports it.
Also, there is no page_node_load() function in Drupal 7, so this part has been removed completely there, possibily for performance reasons (No need to load the alias if no link for this node is displayed anywhere and since it's not used anyway when a link is generated, it is mostly useless).

Why no pid in node object?


Erro ao conectar Delphi 10.2 + Zeos + PostgreSql

Question: Estou tentando conectar o Zeos em um banco de dados PostgreSql.
Já copiei todas as DLL para a pasta da aplicação.
O Zeos acha as DLL, mas dá um erro de incompatibilidade:

Client-Library libpq.dll found but could not be loaded. Check compile-target and library compatibility!

Já copiei as DLL para a pasta windows e windows/system32 porém creio que o erro seja outro.
Minhas configurações:
Windows 10 64bit - PostgreSql 9 - Zeos 7.2.1 rc
EDITADO
Baixei as duas versões do PostgreSql (32bit e 64bit) e coloquei as dll em duas pastas. Quando o aplicativo abre, o cliente tem duas opções de conexão (32 ou 64). Consegui conectar no meu pc usando o 32bit, porém quando testei em outro pc (com as mesmas configurações), não deu certo.
Já registrei a DLL libpq.dll, mesmo assim, o erro persiste na outra máquina (Na minha conectou).
Comment: Tenta copiar para *Windows/SYSWOW64* porque seu Windows é 64 bits.
Comment: Além de Copiar, é importante registrar a DLL `regsvr32`..., lembrando de apontar o caminho do regsvr32 para o caminho adequado do sistema, 32/64
Comment: Pelas pesquisas que fiz, o erro se deve à DLL ser de 32bit e o SO de 64bit ou vice-versa. Consegui resolver no meu pc, mas quando fui pra outro pc, deu o mesmo erro... @JúniorMoreira sabe dizer se o Delphi faz esse registro?
Comment: No caso a instalação do Zeos deve ter feito, então você deve realizar o registro: `regsvr32 caminho\nome_dll`
Comment: Você quer dizer pra instalar o zeos no cliente?
Comment: Não, registrar a DLL que esta faltando.
Comment: não funcionou, mesmo registrando...
Answer: A solução é incluir a pasta onde estão as DLL, no PATH do Windows.
Meu Computador > Propriedades > Configurações Avançadas do Sistema > Variáveis de Ambiente
Nesse local, acrescentar o diretório das DLL na variável PATH.
Testei em diversos computadores e apenas uns poucos não funcionaram.


Lagrangian of an equation, a particle with a time dependent constraint

Question: I'm currently studying for an exam and I came across the following question. Consider a bead of mass m constrained to move along a wire which is on the vertical $(x, y)$ plane. The wire has equation
$y =x^2/a+ b cos(\omega t)$
where $a$, $b$ and $\omega$ are positive constants. The equation of the wire is interpreted physically as a parabola that vibrates vertically with a prescribed time dependence. The particle is under the effect of gravity with potential $V = mgy$. Find the Lagrangian of the system. I'm struggling to find generalized coordinates to represent it. I was thinking maybe cylindrical coordinates would fit the problem but I'm not sure how to apply it to the question and was wondering if somebody could point me in the right direction? Thank you!
Comment: Why cylindrical? They specify that it's in the plane. Since the bead is constrained to the parabola, just use $x$ and $y$ as the coordinates.
Comment: but if x and y are related then how is it possible to split them up?
Answer: Consider the lagrangian
$$
L(x,y,\lambda) = \lambda  \left(y-\frac{x^2}{a}-b \cos (\omega  t)\right)-g m y+\frac{1}{2} m \left(\dot x^2+\dot y^2\right)
$$
and then after $L_X-\frac{d}{dt}L_{\dot X} = 0$ the movement equations
$$
m\ddot x + \frac{2\lambda x}{a} = 0\\
m\ddot y - m g -\lambda = 0\\
y-\frac{x^2}{a}-b \cos (\omega  t) = 0
$$
now deriving twice the last equation we have the DE system
$$
m\ddot x + \frac{2\lambda x}{a} = 0\\
m\ddot y - m g -\lambda = 0\\
\ddot y = \frac{2}{a}(\dot x^2+\dot x\ddot x)-b\omega^2\cos(\omega t)
$$
Finally solving for $\ddot x,\ddot y,\lambda$ we get
$$
\ddot x= \frac{2 \left(a b \omega ^2 x \cos (\omega  t)-a g x-2 x \dot x^2\right)}{a^2+4 x \dot x}\\
\ddot y= -\frac{a^2 b\omega ^2 \cos (\omega  t)-2 a \dot x^2+4 g x \dot x}{a^2+4 x \dot x}\\
\lambda = \frac{a m \left(a g+2
   \dot x^2-a b \omega ^2 \cos (\omega  t)\right)}{a^2+4 x \dot x}
$$
which are the movement equations. Here $\lambda$ represents the reaction force between the bead and the curve.


How to use compile-time environment variables for [Setup] AppVersion?

Question: I'm using InnoSetup 6 (Windows 10, Visual Studio Code and WSL as my shell) to create an installer. This ISCC compiler is called from from an automated script. That script is in charge of setting environment variables holding the generated installer version and generated installer name. Both of them are intented to be used for the InnoSetup installer compiler (iscc.exe) called by the script.
I'm using envvars because I do not want to mess my ISS file with hard-wired versions numbers.
I thought using environment variables was possible in Innosetup, as per this question here on StackOverflow (Can one use environment variables in Inno Setup scripts?).
Unfortunately, Innosetup complains with "The [Setup] section must include an AppVersion or AppVerName directive.". Like if the GetEnv() yield an empty string.
I tried calling ISCC from the command line manually like this :
export JFROG_DEFAULTGROUPS_VERSION=1.0.0-1 && [path..]\iscc.exe myiss.iss

Or even exporting the environment variable using export :
export JFROG_DEFAULTGROUPS_VERSION=1.0.0-1

, then checking the environment variable was actually set and starting the compiler :
env
[path..]\iscc.exe myiss.iss
In this case, env yield the following :
JFROG_DEFAULTGROUPS_VERSION=1.0.0-1
SHELL=/bin/bash
PATH=[...]
[...]

This makes me think the environment is set, as per my shell (WSL). But both didn't give any better result.
My ISS file is as follow :
#define MyInstName "MyApp"
#define MyInstVersion GetEnv("JFROG_DEFAULTGROUPS_VERSION")

[Setup]
AppName={#MyInstName}
AppVersion={#MyInstVersion}

DefaultGroupName={#MyInstName}
OutputBaseFilename=MyApp_{#MyInstVersion}_setup
AppendDefaultDirName=no
DefaultDirName={commonpf}

[Components]
Name: default_groups_conf; Description: Default Groups Configuration; Types: full

[Run]

[Code]
function InitializeSetup(): Boolean;
begin
    if not ('{#MyInstVersion}' = '') then begin
        MsgBox('MyInstVersion Env Var not set.', mbInformation, MB_OK);
        Abort;
    end;
end;

What is wrong with this ? How to properly catch environment variables in [Setup] and [Code] sections ?
Comment: Compiling your script fails on the very first line with *"Undeclared identifier: "MyApp"."* And rightly. – Let's assume that it's just a mistake, while you were sanitizing your script. And the actual script is more like `#define MyInstName "MyApp"`. The script then does what it should. It works nicely, when I compile it from a batch file with these lines: 1) `set JFROG_DEFAULTGROUPS_VERSION=2.1.4` 2) `ISCC.exe Example1.iss`  – What is `export`? There's no export command in Windows batch file, nor PowerShell. Are you using some *nix shell on Windows?
Comment: This does not look like an Inno Setup question. It's more likely that you actually do not set the environment variables correctly.
Comment: @MartinPrikryl, thank you ! I fixed the sample code, it indeed was a sanitizing error. Yes, my shall is WSL. Listing the environment variable (env command) from the terminal just before calling ISCC successfully shows the environment variable, so looks like it is set correctly (as per WSL), but maybe not understood by InnoSetup for any reason. Just tried from a Windows Command Line Interpreter : works flawlessly. Tagging this issue with WSL instead of Inno Setup. Thank you !
Comment: @MartinPrikryl, thanks for pointing me into the right direction. I read this : https://devblogs.microsoft.com/commandline/share-environment-vars-between-wsl-and-windows/ and made things clearer !
Answer: As per https://devblogs.microsoft.com/commandline/share-environment-vars-between-wsl-and-windows/, it turns out :

Windows environment vars are not made available in the WSL shell

I run Windows 10 [version 10.0.17134.1488], which is post 17063, so, I need to expose to WSL the Windows environment variables by exporting a WSLENV whose value is a combination of the envvar to expose, plus a flag (see link) :
export JFROG_DEFAULTGROUPS_VERSION=1.0.0-1
export WSLENV=JFROG_DEFAULTGROUPS_VERSION/w

Then, the JFROG_DEFAULTGROUPS_VERSION envvar can be read by ISCC.
Conclusion : caution with WSL1 and environment variables.
Answer: I have achieved this using following steps. Please note that I have executed iscc using git-bash shell. In git-bash shell, I define environment variable and expose them using "export <ENV_VAR>" command so that iscc can get it's value
1. In .iss file, I have added following environment variables using #define

    #define XXXAppVersion GetEnv('XXX_VERSION')
    #define YYYRootDir GetEnv('YYY_ROOR_DIR')

2. use these in `[Setup]` section of .iss file

    AppVersion={#XXXAppVersion}
    OutputDir={#YYYRootDir}/bin

3. After these changes, open git-bash shell and define these environment variables as follows

export XXX_VERSION="22.214.171.124"
export YYY_ROOT_DIR="C:\YYY_Home"

4. then execute following iscc using .iss file as follows in same shell which executes successfully.

    iscc.exe "<.iss file>"


Taylor series in distribution sense?

Question: If $f$ is integrable, $\partial_x f$ makes sense in the distributional sense as $(\partial_x f,\phi)=(f,\partial_x \phi)$
Question. Does a sort of Taylor series make sense distributionally?
that is, could the following be valid in any sense?
\begin{align}
\left(\sum_{k=0}^{\infty}\frac{ (\partial_x)^k f}{k!},\phi\right)=\left(f,\sum_{k=0}^{\infty}\frac{(\partial_x)^k\phi}{k!}\right)
\end{align}
Answer: Preliminary note : you forgot a minus sign in $(\partial_xf,\phi) = (f,-\partial_x\phi)$, coming from integration by parts.
Answer to the main question. Note that the operator
$$
T_a := e^{a\partial_x} = \sum_{k=0}^\infty \frac{a^k}{k!} \frac{\partial^k}{\partial x^k}
$$
is nothing else than the translation operator, such that $T_a(f)(x) = f(x+a)$. In consequence, the relation you propose, namely
$$
\left\langle \sum_{k=0}^\infty \frac{1}{k!}\partial_x^kf, \phi\right\rangle = \left\langle f, \sum_{k=0}^\infty \frac{(-1)^k}{k!}\partial_x^k\phi \right\rangle,
$$
is equivalent to
$$
\int \overline{f(x+1)}\,\phi(x) \,\mathrm{d}x = \int \overline{f(x)}\,\phi(x-1) \,\mathrm{d}x,
$$
which corresponds merely to the change of variable $x \mapsto x-1$.
Comment: Under what conditions is $e^{a\partial_x}\phi = T_a\phi$ for a function $\phi$?

Taylor series in distribution sense?


How do I add a method to ANY event's invocation list at runtime (C# + Unity)

Question: I'm trying to create an event-based sound triggering system for Unity (5.x) built on top of a project where existing code should be modified as little as possible.
The existing project has all kinds of events with different delegate signatures,
like so:
public delegate void CustomDelegateType1();
public event CustomDelegateType1 OnCustomEvent1;

public delegate void CustomDelegateType2(CustomClass param);
public event CustomDelegateType2 OnCustomEvent2;

I want to use these events to trigger sounds by adding a method to the invocation list at runtime, treating the new method just like any other subscriber. Basically, start by using reflection to get a list of events on the current GameObject, display those events in an editor dropdown on my Component, and then bind a method to that event on Awake()
The problem is: how do you add a generic method to ANY event type (as long as it returns void), given the different number and types of params used in the different delegates?
[Edit: this also needs to run on mobile devices, and hence Reflection.Emit usage isn't viable]
Comment: Does Unity support `Reflection.Emit`? Then you could build some kind of bridges for the incompatible delegate Types.
Comment: It does, but I forgot to mention that my original question was targeting mobile devices where Reflection.Emit() doesn't work with Unity. Editing original to include this.
Answer: It seems that you only want to register to certain events (since you want to choose in the UI.
Why don't you juste create a classe that manages your audio and that registers to all the events you need.
Then you could create different methods that matches all the needed delegates.
I don't really see why you would need to add the method only at runtime since you plan to do it on Awake, it means you plan to know all the needed methods anyway
Answer: I was able to adapt the code presented in this SO answer to solve my problem:
    public static Delegate AddHandler(this object obj, string eventName, Action action)
{
    // Filter list by event name
    EventInfo ev = obj.GetType().GetEvents().Where(x => x.Name == eventName).FirstOrDefault();
    if (ev == null)
    {
        Debug.LogWarning(eventName + " not found on " + obj.ToString());
        return null;
    }

    // Simple case - the signature matches so just add the new handler to the list
    if (ev.EventHandlerType == typeof(Action))
    {
        ev.AddEventHandler(obj, action);

        return action;
    }

    Delegate del = CreateDelegate(ev, action);
    ev.AddEventHandler(obj, del);

    return del;
}

public static void RemoveHandler(this object obj, string eventName, Action action)
{
    // Filter list by event name
    var ev = obj.GetType().GetEvents().Where(x => x.Name == eventName).FirstOrDefault();
    if (ev == null)
    {
        Debug.LogWarning(eventName + " not found on " + obj.ToString());
        return;
    }

    // Simple case - the signature matches so just add the new handler to the list
    if (ev.EventHandlerType == typeof(Action))
    {
        ev.RemoveEventHandler(obj, action);
    }
    else
    {
        Delegate del = CreateDelegate(ev, action);
        ev.RemoveEventHandler(obj, del);
    }
}

private static Delegate CreateDelegate(EventInfo ev, Action action)
{
    // Retrieve the parameter types of the event handler
    var parameters = ev.EventHandlerType.GetMethod("Invoke").GetParameters();

    ParameterExpression[] parameters2 = Array.ConvertAll(parameters, x => Expression.Parameter(x.ParameterType, x.Name));
    MethodCallExpression call;

    // We are "opening" the delegate and directly using the Target and the Method.
    if (action.Target == null) // Event is static
        call = Expression.Call(action.Method);
    else // Event is instanced
        call = Expression.Call(Expression.Constant(action.Target), action.Method);

    var exp = Expression.Lambda(ev.EventHandlerType, call, parameters2);

    return exp.Compile();
}

Unfortunately I couldn't optimize this method to be efficient enough for production usage, as it causes a massive hit on init() execution time, so I ended up writing a bunch of audio helper classes instead.