Swap items in a doubly linked list

Question: I am studying for my Algorithms exam and I have an exercise where I need to swap two items of a doubly linked list if a condition is true. (Language: C)
More specifically, I have a list of this kind:
H <-> |prev|Frequency1|VALUE1|next| <-> |prev|Frequency2|VALUE2|next| <-> ... <-> NULL

The frequency field increases every time I search for the relative value. The list must be ordered according to the frequency (in decreasing order, so at the very top there is the most searched item)
The problem is, I am not very good in exchanging pointers, I tried many times to do it but I have no clue. I guess that the problem I am facing is that I don't know how to use a temp item to keep track of what I am doing without loosing data.
I think that the case I have to consider are:

First item of the list
Last item of the list
Item is in the middle of the list.

My attempt, certainly wrong is:
int Search(int x, list* head) {

    int contapos = 0;
    list* i;
    list* aus;

    for (i=head; i!=NULL; i = i->next, contapos++)
    {

        if (i->key == x)
        {
            i->freq++; // Increase frequency

            aus = i->prev;

            while ((i->freq > aus->freq))
            { // Keep ordered the frequencies

                if (i->next != NULL)
                {
                    i->next->prev = aus;
                }

                if (aus->prev != NULL)
                {
                    aus->prev->next = i;
                }

                aus->next = i->next;
                i->prev = aus->prev;
                aus->prev = i;
                i->next = aus;

            }

            /* Return counter */
            return contapos;

        }

    }

    return -1; // In case the item i am searching is not there
}

Thank you in advance for everything!
Edit:
as requested, I am adding the main (and the whole code just to be sure) of the program at the moment
typedef struct _list {
int key;
int freq;
struct _list *next;
struct _list *prev;
} list;

list* head;
list* tail;

void swap(list *lhs, list *rhs) {
list *temp;

temp = lhs->prev;
lhs->prev = rhs->prev;
rhs->prev = temp;

temp = lhs->next;
lhs->next = rhs->next;
rhs->next = temp;
}

void InsertAtTail(int value) {
list *newNode;
newNode = (list*)malloc(sizeof(list));
newNode->key = value;

if(head == NULL)
{
    head = newNode;
}
else
{
    tail->next = newNode;
    newNode->prev = tail;
}

tail = newNode;
tail->next = NULL;
}

int SearchAndIncrement(int x, list** head) {
int contapos = 0;
list* i;

// Let's find the element with the matching key
for (i = *head; i != NULL; i = i->next, contapos++)
    if (i->key == x)
        break;

// If we did not find the node, return -1 to denote failure.
if (i == NULL)
    return -1;

// Increase frequency
i->freq++;

// Move this node forward while the frequency is not in the correct position.
while (i->next && i->prev && (i->freq > i->prev->freq))
    swap(i, i->prev);

// The head might have been moved.
while ((*head)->prev != NULL)
    (*head) = (*head)->prev;

// Return the original position
return contapos;
}

int main () {

int N;
scanf("%d", &N);

head = NULL;
tail = NULL;

int i, value;
for (i=0; i<N; i++) {
    scanf("%d", &value);
    InsertAtTail(value);
}

/* Initializing frequencies */
list* aus;
for (aus=head; aus; aus = aus ->next) {
    aus->freq = 0;
}

int x, pos;
do {
    scanf("%d", &x);
    pos = SearchAndIncrement(x, &head);
    printf("%d ", pos);
    printf("[");
    aus = head;
    while (aus!=NULL) {
        printf("%d ", aus->key);
        aus = aus->next;
    }
    printf("]\n");

} while (pos != -1);

return 0;

}

Comment: Assuming this is *not* a circular list (and the picture makes that seem a safe leap), I see one issue immediately. If the item you're incrementing is at the *head* of a list of more than one item, the code invokes undefined behavior. Hint: what is the value of `aus` when `i` references the head of the list, and what value do you expect from `aus->freq` in that case?
Comment: I'm a little worried that the while condition does not change, even after you (correctly?) switch the pointers.  Does it get stuck?
Comment: I print the list every time to see what is actually happening and basically what happens is that the item i search disappears, then I search some other item and it appears again!

I can post the whole code if it is helpful, basically in the main I have a while that only stops when I have a -1 and it changes the positions of the items every time I do a new search, ordering them according to their frequencies.
Answer: Let's simplify the problem. The complicated pointer portion is when we are trying to move a node forward in the list. So let's create some functions just for that.
void RemoveNode(list *node) {
    if (node->prev)
        node->prev->next = node->next;
    if (node->next)
        node->next->prev = node->prev;
}

void InsertNodeBetween(list *lhs, list *node, list *rhs) {
    if (lhs) assert(lhs->next == rhs);
    if (rhs) assert(rhs->prev == lhs);

    if (lhs) lhs->next = node;
    if (rhs) rhs->prev = node;

    node->prev = lhs;
    node->next = rhs;
}

Once we've done that, then we can more easily talk about the operation that you want to do.
int SearchAndIncrement(int x, list** head) {
    int contapos = 0;
    list* i;

    // Let's find the element with the matching key
    for (i = *head; i != NULL; i = i->next, contapos++)
        if (i->key == x)
            break;

    // If we did not find the node, return -1 to denote failure.
    if (i == NULL)
        return -1;

    // Increase frequency
    i->freq++;

    // Move this node forward while the frequency is not in the correct position.
    while (i->next && (i->freq > i->next->freq)) {
        list *prev = i->next;
        list *next = i->next->next;
        RemoveNode(i);
        InsertNodeBetween(prev, i, next);
    }

    // The head might have been moved.
    while ((*head)->prev != NULL)
        (*head) = (*head)->prev;

    // Return the original position
    return contapos;
}

Some commentary:
The important thing to note here is that we have the ability to create multiple functions. And we can use those functions to make the amount of the problem that we need to keep in our head at any one time smaller.
Comment: Firstly, thank you. I am sorry if my english isn't very reach in its syntax, so I might do some mistakes.

I forgot to mention that something that might be useful is that the nodes that we need to swap are always consecutive (because this function should keep it ordered), moreover I don't know if this is of any use but the data of the list is ordered too in the test sets.

What you are suggesting is to create a search function to insert in the function that increments the frequency and keeps them ordered? I don't understand if your lhs and rhs are consecutive
Comment: +1 for not just debugging OP's code but giving advice how to design things to make life easier. Also spotted a typo: `if(i == null)` should be `NULL`, I think.
Comment: @user3790865: The `swap()` function is implemented in such a way that it does not require that the elements are neighbors, but it will work fine if they are.
Comment: @user3790865: I was able to infer that the initial dataset was sorted. Otherwise, the problem statement would not make sense.
Comment: I am trying to understand the code right now, sorry if I am a bit slow but this is the first time I swap pointers in doubly linked lists. Why in the Next steps you used 3 arguments in the SearchandIncrement functions? By the way you were right assuming that     contapos is returning the value of the position of the element I am searching.
Comment: @user3790865: I've added some additional commentary that you might find helpful.
Comment: @sharth I am trying the SearchandIncrement() but it doesn't swap any item, besides, as you stated, if I search the first value:
Example:
List of 3 values: [1 2 3]
SearchAndIncrement(1,head)
Returns:
0 [1 ]

So the position is correct, but it looses the other nodes
Comment: @user3790865: I believe that the commentary I've added would cover this. Note that if you were to call `SearchAndIncrement(2, head)` the code above as given will work fine. The only reason that `SearchAndIncrement(1, head)` fails is because it is operating on the head of the list. So after calling it, `head->prev` points to __3__. and `head->prev->prev` points to __2__.
Comment: @sharth How does it point to 3? It is not circular. By the way, I tried to draw an example list on paper, and I tried the swap code. Thing is, it seems to swap the values, but the item before the two items that are being swapped has no reference to the next one, am I right? Indeed, I also tried it on the PC and even if I search a value in the middle (the 2) it looses the third value
Comment: @user3790865: Oops. There's a bug in my swap code. I've changed the last line of `swap()`.
Comment: @sharth To be honest, I don't know what's happening, if I use the code, with the corrected swap function it doesn't swap, but at least it doesn't loose any element of the list.
Thing is, at a certain point it DOES loose an element, and if I search for the first element it doesn't print the list anymore giving me: 99% cpu and a very high energy and memory impact.

Should I try to put the first-last node conditions in the swap function?

PS:the condition shouldn't be this?
while (i->next && i->freq prev->freq)
Comment: Can you add a main() to the post and I'll take a look if I missed anything else.
Comment: @sharth I just edited the main post, thank you!P.s. I tried to change the while condition, but I only get segfault
Comment: @Roberto: Yeah, my `swap()` function is trash... I'm not sure what I was thinking. One mintue.
Comment: The code I've posted should actually work now: http://ideone.com/HM8vAP Sorry for the mess on the way to this result.
Comment: @sharth Thank you, now it does move the elements, not in the way I wanted to, though -  but in the opposite. I am now trying to fix that by myself :)
I wanted to ask you: I never used the assert, is that necessary? If so, I am going to read something about them :)
Comment: @sharth sorry for the further stupid question, why you removed the function swap and you used the Remove and Insertbetween functions? What was the problem with a function like the swap one?
Comment: @Roberto: If we swap neighbors like I was doing, then afterwords: `lhs->next == lhs`. Which is terrible. The asserts are simply contracts that the function is supposed to have. They simply cause the program to error out at that line if the condition is not held. They are a useful way to make sure that your code is sane, which is what I was using them for.
Comment: @sharth I was just trying to do that change I told you before (the list item should move backwards and not forward) and I always get a SEG. Fault, why in your opinion?
      if (i->prev!= NULL) {
    while ((i->freq > i->prev->freq)) {
        list *prev = i->prev->prev;
        list *next = i->prev;
        RemoveNode(i);
        InsertNodeBetween(prev, i, next);
    }
    }

EDIT: Sorry, it wasn't supposed to paste in this way! How can I paste it like a code?
Comment: @Roberto: By backwards, do you mean that the elements with the largest frequency should be at the front of the list? That is, closer to the head?
Comment: @sharth I don't know if I am doing something wrong, but I should consider the two items before the element. The error is given at the while condition, but perhaps the problem is that a certain node doesn't have two elements backwards?
Comment: @sharth Yes sorry, I hadn't seen your reply. The frequencies should be decreasing. As you said, the more an element is searched, the closer it is to the head
Comment: @shart That removes the elements i am searching.
Correction after some tests: It removes the element i am searching if it's frequency is larger than the previous
Comment: @Roberto: I can't recreate that problem: https://gist.github.com/sharth/03f54d06bc2cf1b4e612 What input are you using?
Comment: @sharth I never have been good at coding, so I guess a day is not a big problem :) The input is:
3 // Size of list
1
2
3
3 Output: 2 [1-2 - ]
2 Output: 1 [1 - ]
1 Output: 0 [list remains 1 and frequencies are increased]
Comment: With the code posted in that gist, I'm not able to recreate that: https://gist.github.com/sharth/03f54d06bc2cf1b4e612#comment-1255165
Comment: @sharth Ugh, I am sorry it is my fault! I changed the Insert function in this way: http://pastebin.com/TBb8VtHv thinking it was the same, but apparently it isn't! Now everything works, thank you for your time, really! You were of great help to me, sorry if I kept this thread too long!

Swap items in a doubly linked list


Sharing printer on windows server 2008 using net use

Question: We have a server running Windows Server 2008 and we have a printer Epson LQ 2180.
We need to share this printer with users on two computers (userA and userB).
Commonly, we use Net Use command like
Net Use lpt1: /delete
net use lpt1: \\userB\sharedPrinter /Persistent yes

But this command does not work. How do we set things up so userB can access the printer?
Thanks so much for the help.
Answer: So the easiest way for users on both computers to access the printer is to install the printer on the server and then share it on the network.
To do that do the following.

Install the printer on the server
On the server go to Control Panel
Go to Devices and Printers
Go to the printer properties (either right click and click Properties or double click and click Customize printer)
Go to the Sharing tab
Check the box that says Share this printer
Enter a name for the shared printer (officeprinter)
Click Apply
Click OK

On each of your computers you will need to connect to the printer. You can create a batch file that will do this. An example of what you would put in the batch file is below.
START \\SERVER\officeprinter

A better way would be to do this with a Visual Basic Script.
Set objNetwork = CreateObject("Wscript.Network")
objNetwork.AddWindowsPrinterConnection "\\SERVER\officeprinter"
objNetwork.SetDefaultPrinter \\SERVER\officeprinter

Comment: The problem is, the printer is located on 2nd floor of my building, then the server on 4th floor. How about that ?
Comment: If they are connected to the same network and they can communicate with each other that is not a problem.


Regression model for edge-sensitive data set

Question: I have data sets in which important information is allocated in the edges, which are also very sensitive to inaccuracies. I would like to find a regression model based on edge recognition that brings my data closer to the expected avoiding overfitting. Here is an example:

Please note that although I could simulate the data behavior for this very specific case,  in reality, I do not have prior knowledge or known model of the data.
Several edge-detection algorithms are based on derivative computations, however for such scarce (and frequently noisy) data, derivatives are not a very robust solution. So far, the closest I have got with derivatives is performing y-y'' transformation. Therefore, I am looking in the direction of regression models with machine learning methods, however I have very little experience on that.
Is there any regression model which is suitable for edge detection and enhancement?
I also provide a link with the corresponding data. Any idea/suggestion/help would be very appreciated, I am currently working on Matlab and Python.
Thanks in advance!
.imgur.com/vfqv0.png
Answer: In working with similar looking data, I have not had luck with regression models. Instead, I am currently using Symbolic Aggregate approXimation (SAX) as a means to cluster and classify edges and have had reasonable success with this approach. It seems to be resistant to noise, amplitude variations and focuses a lot more on shape. It might be worth a look.
Comment: Thank you Jason, you have opened a new window to explore. I will definitely have a look at it.
Comment: If this does not work for you and you do find any other approaches that work, I would appreciate any updates as it is always good to find alternatives.
Comment: Sure! Always new ideas are welcome! I will keep you updated and hopefully more people come to the discussion as well...
I implemented a simple code to my data and, as you mentioned, the algorithm cares more about edges. Therefore, it is good to model the data itself.
However, one of my major issues are also the random shifts of the experimental data respect to the model. So, at the moment, I am trying to put some constraints based on differences to see if the result improves.


Para que serve a chave estrangeira (SQL)

Question: Pelo que andei pesquisando, na hora de puxar a informação de duas tabelas em um banco de dados, usa-se o JOIN, que nada tem haver com chave estrangeira.
Então para que serve declarar um campo como foreign key (chave estrangeira)? Não vejo sentido. Alguem me explica por favor?
Comment: Integridade dos dados!
Answer: Declarar um campo como chave estrangeira explicita qual o campo que liga as duas tabelas no join, tanto para quem for produzir querys para ele, quanto para o próprio banco lidar com a otimização.
Um dos pontos primordiais da normatização em um banco de dados é garantir a integridade deles, declarando uma chave estrangeira, você se assegura de que aquele relacionamento ira acontecer sempre que for possível, não preenchendo a tabela com valores inexistentes na outra.
Chave Estrangeira
Uma chave estrangeira é chamada quando há o relacionamento entre duas tabelas.
Sempre em chave estrangeira vai haver relacionamentos entre tabelas, por exemplo, se uma tabela que tem uma chave primária de outra tabela.
Junção de Tabela
Tabela de banco de dados são semelhantes a conjuntos numeros e algumas vezes, precisamos achar a interseção entre eles, como pode ver abaixo:

Estas tabelas são ligadas por um campo comum entre elas, estes campo deve ser a chave estrangeira entra elas.
Normalização de Bancos de Dados Relacionais
Normalização é um processo a partir do qual se aplicam regras a todas as tabelas do banco de dados com o objetivo de evitar falhas no projeto, como redundância de dados e mistura de diferentes assuntos numa mesma tabela.
Leia Mais


How to create dummy fields

Question: I use Drupal7. I want to create some dozens of dummy fields in my test node quickly. But, it will take long if I do at "manage fields page"(admin/structure/types/manage/CONTENT_TYPE).
Unfortunately, I couldn't find any modules to do it(Devel Generat can create contents, but not fields). Any suggestions to do it?
Thank you.
Answer: You could use this module:
https://www.drupal.org/project/bundle_copy

Create a field
Export the bundle/content type
Copy the field in the exported text, paste several times, changing stuff for each field that you want to change for each new field
Import the same bundle/content type
Comment: Hi Emil, Thank you for your answer.
Yes, this worked! Actually, I did it with a combination with excel, replacing those stuffs in effective way. Thank you so much!

How to create dummy fields


In Unity .Net WebSocket, solving SendAsync "already one outstanding" problem

Question: In Unity with .Net I'm using websockets, so as a client:
using System.Threading;
using System.Net.WebSockets;
async void Connect()
{
    cws = new ClientWebSocket();
    try
    {
        await cws.ConnectAsync(u, CancellationToken.None);
        if (cws.State == WebSocketState.Open) Debug.Log("connected");
        ... begin receive result loop, etc ...
    }
    catch (Exception e) { Debug.Log("woe " + e.Message); }
}

To send to the server, I use:
public async void SendString(string msg)
{
    ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));
    await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
}

Hence throughout the app,
ThatClass.SendString("some command");

and
ThatClass.SendString("some other command");

However at one point I do this,
ThatClass.SendString("a command");
ThatClass.SendString("another command");

One immediately after another.
Of course, it doesn't work.  The error is

InvalidOperationException: There is already one outstanding 'SendAsync' call for this WebSocket instance. ReceiveAsync and SendAsync can be called simultaneously, but at most one outstanding operation for each of them is allowed at the same time.
System.Net.WebSockets.ManagedWebSocket.ThrowIfOperationInProgress (System.Threading.Tasks.Task operationTask, System.String methodName) (at :0)
System.Net.WebSockets.ManagedWebSocket.SendAsync (System.ArraySegment`1[T] buffer, System.Net.WebSockets.WebSocketMessageType messageType, System.Boolean endOfMessage, System.Threading.CancellationToken cancellationToken) (at :0)

Is there a simple solution here?  Or do you have to build a queue?
I thought perhaps Monitor would help, so
public async void SendString(string msg)
{
    ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));
    //await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);

    Monitor.Enter(cws);
    try
    {
        cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
    }
    finally
    {
        Monitor.Exit(cws);
    }
}

However, in that case I get this error:

ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
System.Net.Sockets.NetworkStream.EndRead (System.IAsyncResult asyncResult) (at :0)
System.IO.Stream+<>c.b__43_1 (System.IO.Stream stream, System.IAsyncResult asyncResult) (at <980ae0ed635b4a3296831396fcc0a4a0>:0)
System.Threading.Tasks.TaskFactory1+FromAsyncTrimPromise1[TResult,TInstance].Complete (TInstance thisRef, System.Func`3[T1,T2,TResult] endMethod, System.IAsyncResult asyncResult, System.Boolean requiresSynchronization) (at <980ae0ed635b4a3296831396fcc0a4a0>:0)

Is there a simple solution?  (Or any solution!)

As a curiosity (this could be Unity related, IDK) if you add any statement between the two calls,
ThatClass.SendString("a command");
x = 1;
ThatClass.SendString("another command");

disturbingly, it then does work!  :O (As often as I tested it.)
Comment: PS for anyone googling here, in practice nowadays in Unity you basically **must** use the socket library https://github.com/Marfusios/websocket-client (it's the only currently maintained one - as of 2021 )  It would be totally impractical to start from scratch and - essentially - write that library.
Answer: You should be awating the SendAsync call and return a Task that represents this operation. If you do not await the call, the flow of the method continues before finishing the execution of SendAsync. Try this:

using System.Threading.Tasks;

public async Task SendStringAsync(string msg)
{
    ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));

    Monitor.Enter(cws);
    try
    {
        await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
    }
    finally
    {
        Monitor.Exit(cws);
    }
}

And call it like this:
await mySockerWrapper.SendStringAsync("Hello World!");

Comment: I would not lock the entire `cws` object to make sure that only one write operation can be done at a time. Instead I would either create a `sendLock` or make sure that only one type of event (like receiving something) can trigger a send.
Comment: `private object _sendLock = new object();`.  and then `Monitor.Enter` as in the code. so it's minimal difference make the intent is much more clear and you don't have to worry that something in your code will lock `cws` for other purposes and by doing that degrade performance.
Comment: I can see that the fact is you have to have a QUEUE for outgoing messages.


Twig: How to access multiple values from node reference field with number_format

Question: I'm adding fields to array:
{% for item in content.field_notes | field_target_entity %}
   {% set field_component_pages = item.field_component_pages|view|number_format %}
{% endfor %}

In my scenario the value of item.field_component_pages|view is equal "16", but when I convert it to number with number_format I get value of 1.
I presume the item.field_component_pages|view is not a real value. How can I access field field_component_pages correctly in this case?
Answer: You can get it form the value. something like item.field_component_pages.0.value properly works for you
{% for item in content.field_notes | field_target_entity %}
   {% set field_component_pages = item.field_component_pages.0.value|number_format %}
{% endfor %}

Comment: The output is  Warning: strip_tags() expects parameter 1 to be string, array given in and returns 0
Comment: @adpo can you please tell me what is the response of {{ dump(item.field_component_pages) }}
Comment: @adpo , ok , then try {{ dump(item.field_component_pages|view) }}
Comment: @adpo would you please share a screenshot of  this fields ( while you are not able to dump it) . I should know the type and field settings somehow
Comment: @yosef Thank you for you support. I have decided to dump this value from hook_preprocess_node. and tthe correct value is item.field_component_pages.0.value
Comment: @adpo you're welcome. I've updated the question base on your solution. maybe it will be helpful for another guy in the future. :)


SAS/RAID controller non-ecc ram

Question: I have Adaptec 51245 controller (I know it is old but I got it for free) that I use in my server.
As far as I know it is highly recommended to use ECC RAM as system memory, but what about RAID controller? It has 512MB DDR2 RAM. Should I turn it off? I do not want any data corruption.
Answer: You can doesn't mean you should. Don't experiment here, you'll save pennies literally on non-ECC memory, but you risk your data indeed.
Comment: basically doing just that, experimenting. I am a student running server for testing. I got that raid controller for free and now I am using it, for now cache is off, but I am not sure if I will put the data at risk if i turn it on? (if yes I won't buy new controller, I will just use this without cache)
Comment: You'll benefit from learning something recent and decent like say MDRAID or maybe ZFS, hardware RAIDs are legacy (obsolete?) tech and you won't see them around soon. IMHO.
Answer: ECC is essential for (large) server memory. Whether you need it somewhere else depends on your environment and your requirements.
Data sitting in memory for a long time is subject to corruption. DRAM bits can flip on their own with an extremely low probability - however, that probability can significantly grow in electrically noisy environments or with elevated levels of (background) radiation. So, if you either cannot tolerate any bit errors ever or the location is subject to EMI or radiation you practically cannot live without ECC.
That said, RAID controllers without cache perform very poorly. This is in part caused by the additional latency they introduce into the data path and may get really significant when used with a RAID variant that actually requires cache, like RAID-5 or RAID-6. You can use RAID-5 or RAID-6 without cache but the write amplification will kill you.
Does the computer have ECC support for its main memory? If not, the RAID won't make a difference. If you want to eliminate all data corruption risk (it's very low for moving data anyway) you can try without cache. Likely, you won't like the performance, so you should consider getting a RAID controller with ECC support and main memory with ECC.

SAS/RAID controller non-ecc ram


odftoolkit NoClassDefFoundError exception

Question: I've read this topic, and I've used odfdom library as was described, but I ve got an excption
<code> Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xerces/dom/DocumentImpl
</code>
How can I deal with that? Thank you!
P.S.: Here is gist
Answer: I've had the same problem. Adding xercesImpl.jar (can be found in Xerces2 Java archive on http://xerces.apache.org/mirrors.cgi#binary) to my libs has solved it.


Is there a specific name or descriptive term for happy, productive melodies/tunes that you see on ads?

Question: Example
Feel free to include some of your favorite ones also!
Comment: This is a word identification question, not a music theory or practice question. Please check out https://english.stackexchange.com/ for questions like this.
Comment: Thank you! What can I do to put this post in its proper community?
Comment: Go to the site that I linked and ask the question again there. There isn't a way for you to move this over to there.
Comment: I'm voting to close this question as off-topic because it is a word request better suited for English.SE.
Answer: Commercial jingles? I'm pretty sure that's the term in English... "Advertisement song" would be understood, but "Commercial Jingles" are a real phrase, I believe.


Change merge pull into rebase pull

Question: It is now possible to rebase when accepting pull requests on GitHub, thus making no merge commits. Is it possible to convert my older accepted pull request to rebase instead then merge, so there is no merge commit in the history?
Comment: If you're already merged it, then no
Comment: Can I rebase my commit history locally and force push to the remote to achieve the same effect?
Comment: Yes, but you'll rewrite any commit history after the first commit that you change - if you're the only one using the repository then that's OK, but it'll be a pain for anyone else using it
Comment: I'm the only one. How can I do so?
Comment: Read up on `git rebase`
Comment: I know how to use it, but whenever I do `git rebase -i `, I do not see the merge commit in the text file that opens.
Comment: Merge commits are automatically removed when you rebase, unless you tell it to include them. Really all you need to do is continue without doing anything and it will remove all the merge commits
Comment: Found it. To anyone who stumbles here, the command line argument to use is: `-p`
Comment: You should write an answer with your findings in it - might be useful to others in future\
Answer: Run git rebase -i <first commit hash> -p and simply drop the merge commit(s), then force push.
The -p argument is required, or else Git will hide merge commits during the rebase.

Change merge pull into rebase pull


How to write rests in triplet semiquaver groups

Question: In the second bar of this exercise, I have to add the correct rest into a triplet semiquaver group:

Do you have to use separate semiquaver rests like I have done, or could I have used one quaver rest instead?
Comment: Personally, I prefer the way you've written it, especially since the following rests are both quavers — a quaver rest with the triplet would create visual confusion.
Comment: Related: [Adding missing rests to 9/8 meter](https://music.stackexchange.com/questions/118253/adding-missing-rests-to-9-8-meter)
Answer: Just as inside a normal measure, within a tuplet any note or rest values that sum up to the length of the tuplet are permissible. Inside this triplet semiquaver group, it would be acceptable to use a quaver rest instead of two semiquaver rests.
Best practice for notation would likely involve visually separating each of the three semiquaver notes within reason. If there were something strange going on, such as a double-dotted demisemiquaver note within the triplet, I would highly recommend splitting it along the individual semiquaver divisions and tying them for visual clarity (with rests, ties are of course unnecessary).
This case is a bit debatable; as one commenter pointed out, the visual similarity between the quaver rests inside and outside the triplet may be confusing enough to warrant the two semiquaver rests. But I am not aware of any general rule forbidding note values larger than the unit of tuplet division.
Answer: In reference to rests in compound time, Gould (p.163) states:
"Rests at the beginning of a beat may be combined"  and "Rests that follow a beat should expose all three divisions."
I think the same would apply to triplets.   So, combine rests that start a triplet group, don't combine rests that end one.
DOES the question specifically ask for a rest'?   Or 'rest or rests'?
Comment: rest or rests.. there are other questions where you have to put more than one
Answer: Either will do, both are technically correct. However, the point of writing out any music is to make it the easiest to read for future players. Since triplets are essentially three, it's more simple to use those two semi rests rather than a quaver rest - it sort of follows the pattern, thus will be easier for some to read.
However, on a technical point in the question itself, an asterix denotes one rest, I guess from that question - which may well indicate that one rest is expected within the triplet, and one other for the rest (sic) of the bar. Could rest (sic) on the way the question is phrased - as far as the question itself is concerned. Not the point of OP's question, but a point nevertheless.
Comment: (To be pedantic, an [Asterix](https://en.wikipedia.org/wiki/Asterix) denotes a French comic-book character; I suspect you meant an [asterisk](https://en.wikipedia.org/wiki/Asterisk).)  Good spot about the original exercise prompting OP's question.
Comment: @gidds - yes - and you get the star for spotting the deliberate mistake! Nothing wrong with pedantix...


Determinar conteúdo para preencher UITableView com base em uma tag de UIButton

Question: Vou explicar o cenário para ficar o mais claro possível para entenderem a questão:
 Na tela principal do meu app eu tenho 4 UIButton e cada um deles abrirá uma tela diferente contendo cada uma sua própria UITableVIew e respectivo conteúdo.
Os botões são os seguintes:
Botão Restaurantes -> Irá abrir uma UITableView com um restaurante diferente em cada célula.
Botão Lojas -> Irá abrir uma UITableView com uma loja para cada célula.
Botão Lugares -> Irá abrir uma UITableView com lugares distintos em cada célula.
Botão Hoteis -> Irá abrir uma UITableView com um determinado hotel em cada célula.
Com este cenário, eu precisaria criar uma UIViewController para cada tela e sua respectiva UITableView. Oque acaba "poluíndo" o código e a tela do Storyboard.
Gostaria de saber um modo de utilizar somente uma única tela para exibir (com UITableView implementada) para exibir esses conteúdos separadamente, de acordo com o botão escolhido, já que o layout de exibição irá seguir o mesmo padrão. A solução que pensei seria utilizando a propriedade tag de UIButton para distinguir os botões e carregar o conteúdo adequado.
No caso oque desejo saber é: Como mostrar conteúdo diferentes usando a mesma UITableView, distinguindo o conteúdo a ser mostrado através do botão selecionado?
Qualquer dúvida sobre a questão basta deixar um comentário que poderei explicar novamente caso seja necessário.
Comment: Suas views estão sendo feitas com `storyboard` ou `xib`?
Comment: Estou usando Storyboard.
Answer: Bem como você disse, não precisa mesmo ter vários controllers para cada conteúdo diferente. Vamos supor que você tenha estes botões:
@property (nonatomic, weak) IBOutlet UIButton *btnRestaurantes;
@property (nonatomic, weak) IBOutlet UIButton *btnLojas;
@property (nonatomic, weak) IBOutlet UIButton *btnLugares;

Estes mesmo botões respondem a uma única ação:
- (IBAction)abrirConteudo:(UIButton *)sender {
    [self performSegueWithIdentifier:@"abrirConteudo" sender:sender];
}

Criei também um enum para cada tipo:
enum tipos {
    T_RESTAURANTES = 0,
    T_LOJAS,
    T_LUGARES
};

E ao preparar a segue do seu storyboard:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"abrirConteudo"]) {
        ViewConteudoController *viewConteudo = [segue destinationViewController];

        UIButton *button = (UIButton *)sender;

        if ([button isEqual:[self btnRestaurantes]]) {
            [viewConteudo setTipoConteudo:T_RESTAURANTES];
        } else if ([button isEqual:[self btnLojas]]) {
            [viewConteudo setTipoConteudo:T_LOJAS];
        } else if ([button isEqual:[self btnLugares]]) {
            [viewConteudo setTipoConteudo:T_LUGARES];
        }
    }
}

Pronto, no seu destino, que aqui eu chamei de ViewConteudoController, a variável tipoConteudo recebe um destes valores e a partir dele você decide o que exibir no conteúdo da sua tabela.
Acredito que isto também responda sua outra pergunta.
Espero que tenha ajudado.
Comment: Muito obrigado @Paulo-Rodrigues!!

 Vou testar e te falo como ficou!
Comment: quando vc criou o enum, vc setou 0 para T_RESTAURANTES, mas os outros? Devem seguir a ordem crescente? 1, 2... ?
Comment: Na verdade nem precisava, foi só um exemplo, pois definindo o primeiro os próximos elementos serão incrementados. Se o primeiro fosse 5, os demais seriam 6, 7, 8 etc.
Comment: Paulo vc usa skype? me add la se puder falar: email@example.com


One domain with several mx records, allowing some users to use Google Workspace and others to use roundcube from the server

Question: All setup and MX records have been configured for the domain example.com, which I added to my Google Workspace account. I also own the website example2.com. These two domains belong to two separate businesses with various users. In the case of example.com, all users are required to have a Google Workspace account and a Gmail address, such as firstname.lastname@example.com, whereas, in the case of example2.com, some users are not required to have a Google Workspace account. Of course, the two businesses have two distinct populations of users.
What I need to do is configure the second domain, example2.com, so that if a user has a Google Workspace account, they can send and receive emails using their Google Workspace account and mail, but if they don't, they can still use the default mail server to send and receive emails from the server, not Google Workspace.
I consider creating several MX records so that everyone with an email address and user for example2.com in Google Workspace can utilize Gmail, Google Workspace features, and other services. However, if someone only has a standard email set up for them in the domain's mail server rather than a Google Workspace account, they can still use that email. I'm referring to setting domain mail server MX records as the second priority after Google MX records.
Answer: Multiple MX records does not make all the MX servers receive a copy of the message, but only the first one available in the preferred order will get it; that is the one with the lowest number in the priority field. Whether it is Gmail or an own SMTP server, it has no clue what to do with messages sent to non-existing users from its own perspective.
In your mail infrastructure, you need MX servers that can accept inbound mail for all the users and then direct it to the correct mail storage (there are many strategies for this). Only outbound mail can have multiple sources directly.


How should I exclude state resources from being deleted when redeploying to a new Kubernetes cluster with Terraform?

Question: I want to redeploy to a new cluster using the terraform destroy command, but I want to keep the state resources managed outside the cluster like "google_storage_bucket".
How can I exclude some resources from being deleted?
Or is there a better practice to do this?
Answer: When you use destroy command, all resources from terraform state are planned to be destroyed.
I assume you are talking about the bucket that is also a part of terraform code, but not a part of a cluster that was created using this code.
The best option would be to delete only the resources you want to be destroyed using:
terraform apply -destroy -target=resource.to_be_destroyed
# example:
terraform apply -destroy -target=google_container_cluster.main

which means the destroy plan is going to be only about those specific resource (you can add a couple at the same time using more -target flags).
The other option is to use -replace option. This marks a module or resource to be recreated in next apply, example:
terraform apply -replace=module.gke

Sources:

https://developer.hashicorp.com/terraform/cli/commands/plan#replace-address
https://developer.hashicorp.com/terraform/cli/commands/plan#resource-targeting


magento worldpay doesn't redirect

Question: I've upgraded from magento 220.127.116.11 to magento 188.8.131.52 and I have the Phoenix Worldpay extension installed. When in the checkout, the cart no longer redirects to worldpay after step 5.
If I go to /worldpay/processing/redirect, I get the error: No order for processing found
This is thrown from:
<code>    $session = $this->_getCheckout();

    $order = Mage::getModel('sales/order');
    $order->loadByIncrementId($session->getLastRealOrderId());
    if (!$order->getId()) {
        Mage::throwException('No order for processing found');
    }
</code>
Any ideas why?
Answer: this error is thrown cause no order is loaded, check if the session has the data this extension needs
Answer: I found the solution, it's not the plugin, it's in fact a problem with the checkout.xml layout file. I replaced it with a brand new version and it worked fine

magento worldpay doesn't redirect


Divisão de registros listados em Lotes PHP

Question: Tenho uma listagem com 37 itens, retornando em forma de array do banco de dados na seguinte forma:
SELECT * FROM tabela WHERE id = '5';

Nesta listagem, eu tenho um dividendo:
$total = 37; // quantidade retornada do banco de dados
$dividir = 2; // quantidade que eu desejo dividir
$resultado = floor($total/$dividir); // arredondo para baixo

O total do resultado será 18. Sobram então 1 item.
O que eu preciso é inserir estes dados no banco de dados na seguinte forma:
INSERT INTO tabela2 (total, lote, campo1, campo2)

O que representa: total = 37, lote = 1 (eu dividi por 2, então os primeiros 18 registros serão com lote 1) e os demais campos
INSERT INTO tabela2 (total, lote, campo1, campo2)

O que representa: total = 37, lote = 2 (eu dividi por 2, então os outros 18 registros serão com lote 2) e os demais campos
E por fim, como sobrou um, eu preciso inserir como um terceiro lote
INSERT INTO tabela2 (total, lote, campo1, campo2)

O que representa: total = 37, lote = 3 (eu dividi por 2, então o que sobrou será o lote 3) e os demais campos
Como eu faria para que eu consiga inserir corretamente no banco de dados? Minha dúvida se resume apenas a divisão dos registros em lotes.
Answer: Modifiquei o código, veja se atende melhor:
<?php
$registros = [];
for($j = 0; $j < 51; $j++){
    $registros[$j] = "Registro " . $j;
}

$total = count($registros);
$dividir = 10;
$resultado = floor($total/$dividir);
$totalLotes = $dividir + ($total % $dividir > 0 ? 1 : 0);

echo "Total por lote: $resultado.
";
echo "Total de lotes:  {$totalLotes}.
";

$lote = 1;
$contador = 0;
foreach($registros as $chave => $registro){
    if($contador == $resultado){
        $contador = 0;
        $lote++;
    }
    $contador++;

    echo "INSERT INTO tabela2 ({$total}, {$lote}, {$registro}, {$chave})" . "
";

}

?>

Comment: É quase isso, mas ele não retorna o que seria preciso, os lotes não batem, preciso inserir cada um no seu lote... mais é por ai, me disseram que posso usar como efeito de paginação, e vai inserindo conforme as paginas, usando o for, mas não consegui fazer.
Comment: @AndréBaill, modifiquei o código. Dá uma olhada.


Error: GetCharacters System.InvalidCastException: Specified cast is not valid server

Question: Error

System.InvalidCastException: Specified cast is not valid.

Line 71
Tamer.Partner = GetDigimon((uint)(int)dr["partner"]);

Code Sample Below
public static List<Character> GetCharacters(uint AcctId)
{
    List<Character> chars = new List<Character>();
    try
    {
        using (MySqlCommand cmd = new MySqlCommand(
            "SELECT * FROM `chars` WHERE `accountId` = @id"
            , Connect()))
        {
            cmd.Parameters.AddWithValue("@id", AcctId);

           using(MySqlDataReader dr = cmd.ExecuteReader())
           {
               if (dr.HasRows)
               {
                   while (dr.Read())
                   {
                       Character Tamer = new Character();
                       Tamer.AccountId = AcctId;
                       Tamer.CharacterId = Convert.ToUInt32((int)dr["characterId"]); ;
                       Tamer.Model = (CharacterModel)(int)dr["charModel"];
                       Tamer.Name = (string)dr["charName"];
                       Tamer.Level = (int)dr["charLv"];
                       Tamer.Location = new Helpers.Position((short)(int)dr["map"], (int)dr["x"], (int)dr["y"]);

                       Tamer.Partner = GetDigimon((uint)(int)dr["partner"]);
                       if (dr["mercenary1"] != DBNull.Value)
                       {
                           int mercId = (int)dr["mercenary1"];
                           Digimon merc = GetDigimon((uint)mercId);
                           Tamer.DigimonList[1] = merc;
                       }
                       if (dr["mercenary2"] != DBNull.Value)
                       {
                           int mercId = (int)dr["mercenary2"];
                           Digimon merc = GetDigimon((uint)mercId);
                           Tamer.DigimonList[2] = merc;
                       }

Comment: The error is happening with line 71.
Comment: Thank you Sateesh!
Comment: you are welcome! Please mark it as answer it this answers your question.
Answer: Not sure why you are trying do this conversion. But, try this
Convert.ToUInt32(Convert.ToInt32(dr["partner"]))


Tratando null pointer exception

Question: Estou recebendo, no meu back end, um objeto json da tela dessa forma:
{
    "pessoa": {
        "nome": "aa",
        "nomeSocial": "aa",
        "tipoPessoa": "F",
        "nomePai":"",
        "dataNascimento": "15/06/1983",
        "nomeMae": "a"
    },
    "cns": "aa",

    "pessoasEnderecos": {
        "cep": "a",
        "nomeLogradouro": "a",
        "nomeBairro": "a"
    }
}

A questão é que estou tendo um nullPointerException porque, por óbvio, o meu json nomePai está vazio, como eu faço para tratar esse erro e persistir os dados no banco passando o nomePai null, já que não é obrigatório pela regra de negócio?
Existem vários atributos que se enquadram nessa regra, coloquei apenas um para demonstração.
Meu método:
@RequestMapping(method = RequestMethod.POST, value = "/pacientes")
    public HttpStatus cadastrarPacientes(@RequestBody ObjectNode json) throws ParseException  {

        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

            entidades.setIdEntidade(json.get("pessoa").get("entidade").get("idEntidade").asLong());

            Pessoas pessoas = new Pessoas();
            pessoas.setNome(json.get("pessoa").get("nome").textValue());
            pessoas.setNomeSocial(json.get("pessoa").get("nomeSocial").textValue());

            pessoas.setNomePai(json.get("pessoa").get("nomePai").textValue());
            pessoas.setNomeMae(json.get("pessoa").get("nomeMae").textValue());
            pessoas.setDataNascimento(formato.parse(json.get("pessoa").get("dataNascimento").textValue()));

            pessoas.setTipoPessoa(json.get("pessoa").get("tipoPessoa").textValue());
}

Comment: `pessoas.setNomePai(json.get("pessoa").get("nomePai") == null ?
 null : json.get("pessoa").get("nomePai").textValue());`
Comment: @Articuno funcionou !! Posta seu comentário como resposta. Obrigado !
Comment: @Articuno Funcionou somente para os valores em String.. no caso, por exemplo;; `entidades.setIdEntidade(json.get("pessoa").get("entidade").get("idEntidade").asLong());` continua dando erro..
Comment: Ai tem que ler a documentação do método `asLong` e ver que tipo de retorno ele dá quando nada é retornado. Eu não sei que api você está utilizando, então, nem tem como sugerir algo. Da uma olhada na documentação deste método e qualquer coisa, posta o link da doc aqui se ficar em duvida.
Answer: Uma resolução simples seria utilizar operação ternária para evitar a tentativa de acesso a um retorno nulo:
pessoas.setNomePai(json.get("pessoa").get("nomePai") == null ? null : json.get("pessoa").get("nomePai").textValue());

Dessa forma, mantem-se o retorno nulo caso o valor retornado seja vazio, mas o textValue() só irá ser chamado caso não seja nulo.

Tratando null pointer exception


Slave Failover to other Master in MySQL Master-Master-Slave Scenario

Question: I have a Master-Master MySQL Setup (5.6) with an additional Slave attached to Master 1:
Master 1 (alive) <---> Master 2 (alive)
   |
Slave 1

Now when Master 1 dies, i want the Slave to automatically switch to the other Master and receive updates from there:
Master 1 (DEAD) <---> Master 2 (alive)
                         |
                      Slave 1

Is there any tool that handles this for me?
I believe this HA Failover scenario is not very uncommon, but unfortunately I could not find any tool to automate this.
Answer: HAproxy does a great job with this kind of stuff. I'd suggest moving to Percona though, if that's an option, and using a Xtradb cluster. Percona uses mysql.
http://www.haproxy.org/
http://www.percona.com/
HAProxy is very easy to set up and use, also gives visibility as to which node is answering, primary, etc, based on what it sees and your config.
Comment: HAProxy is a loadbalancer and yes, it would move the TCP connections to the other master. But it is totally unaware of the MySQL binary log - so i would expect this to fail. any other suggestions?
Comment: note: i don't want a client to connect to another node. i wan't a *mysql slave* to connect to another master, which requires more logic and involves correctly handling binary log positions.
Comment: Again, I suggest moving to Xtradb cluster, I used multiple slaves for some time and it can be problematic. I never found a way other than manually failing it over, not that was reliable anyway.


Is there any way to send a message to everyone except the sender?

Question: This question is similar to this one, but that was for JavaScript whereas mine is for Python.
How do I send a message to every connected client from the server except a selected client in Python using the sockets library?
I am making a simple game, where I want to detect the first person to press a button among three clients, and then notify the other two clients that they lost while notifying the winner that they won.
Usually, to send information to a client you do (on a new thread):
connected_client.sendall(data)

To receive, you do:
data = socket.recv()

But from what I searched, I couldn't find a way to send data to every connected client except a certain client.
I thought I could get around this by creating an 'identifying name' for each thread which ran the receiving function, but I couldn't find a good way to do this due to which I decided to search for a better option.
How can I do this?
Comment: If you're sending a broadcast message, you can attach an `ignore` tag with the identifiers of clients that should ignore the message. If a client recognise itself, then it will drop the message.
Comment: @crissal By identifiers of clients do you mean identifiers of the thread in which the receiving function is in or can you obtain a different identifier of a client?
Comment: Anything that is unique will work as identifier; btw your sender should know the various identifiers, and send to one rather than another accordingly.
Comment: What does: `first person to press a button` mean when you are talking about socket connections?
Comment: @quamrana Its the concept of the game I'm making, just to give you an idea of why I need an answer to this
Comment: Are you saying that: `press a button` gets translated to `receive a message` about pressing a button?
Comment: @crissal How do I set an identifier? (I'm new to the sockets library)
Comment: @quamrana Yes, the button press sends a message to the server.
Comment: If they're thread, you can read about [`get_ident()`](https://docs.python.org/3/library/threading.html#threading.get_ident), or you can set your own unique `name`.
Comment: So, when you receive a message, you know who sent it. So now you know who to congratulate and by default the others you commiserate with.
Answer: Inserting them into a list can help. For example...
For the server side:
import socket
import threading

# This is where you store all of your Client IP's
client_list = []

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = "yourip"
server_port = 8888
server.bind((server_ip, server_port))

def check_client(client_ip):
    while True:
        data = client_ip.recv(1024).decode()

        if "condition" in data:
            for ip in client_list:
                if ip != client_ip:
                    ip.send("something".encode())

def check_connection():
    server.listen()
    while True:
        client_ip, client_address = server.accept()
        client_list.append(client_ip)
        threading.Thread(target=check_client, args=(client_ip,), daemon=True).start()

check_connection()

So what happens is you call the check_connection function to check for incoming connections. After it receives one, it appends the connection inside the client_list variable. At the same time, it creates a thread to the current connection, check_client, which checks for any info being sent. If there's an info being sent by one of your clients, it checks if the "condition" string is inside your sent data. If so, it sends "something" string into all of your clients with exception to itself. Take note that when you send data, it must be in bytes.
For the client side:
import socket
import threading

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = "serverip"
server_port = 8888
server.connect((server_ip, server_port))

def receive_info():
    while True:
        data = server.recv(1024).decode()

        if "something" in data:
            print("Someone already sent something")

threading.Thread(target=receive_info, daemon=True).start()

while True:
    user_input = input("Type 'condition': ")
    server.send(user_input.encode())

What this only does is, it sends your input into the server. If you typed "condition" on your input, it will send "something" on the other clients except you. So you need to setup 2 more clients in order to see the results.
Don't forget to set server_ip and server_port's values!


Can we apply stepwise forward or backward variables selection in negative binomial regression in SPSS?

Question: I am trying to adjust my covariates in a model. My dependent variable is count data variance is greater than mean which means I have to apply negative binomial regression, main independent variable (bullying) is binary (0/1), and I have few covariates such as age, gender, family status and so on which I want to adjust in the model. One options for the adjustment is that I can adjust the main independent variable and age (model I), bullying, age and gender (model II), bullying, age, gender and family status (model III) and add other covariates one by one and have more models. However, some of the reviewers in my previous commented of not applying forward or backward method for covariates adjustment. So my main question is can we apply stepwise forward or backward selection for negative binomial regression in SPSS?
Answer: I don't use SPSS, so I don't know if you can do this, but I do know that you shouldn't.
When you use stepwise, forward, or backward, the output is all wrong. Standard errors are too small, p values too low, and parameter estimates biased away from 0.
In addition, automated methods stop the investigator (that's you!) from thinking, and there are reasons to include covariates that won't show up in any automated method, e.g. a variable could be an important covariate, and a low parameter estimate might be interesting.
I wrote a short and somewhat informal paper on this called "Stopping Stepwise". If you search my name and that title, you can find it at various spots on the web.
For a more extended discussion, with proofs, see Regression Modeling Strategies by Frank Harrell.
Comment: +1 ($+\infty$, really :) [There](https://stats.stackexchange.com/a/174232/44269) [are](https://stats.stackexchange.com/a/97495/44269) [many](https://stats.stackexchange.com/a/338807/44269) [similar](https://stats.stackexchange.com/a/118456/44269) [answers](https://stats.stackexchange.com/a/115850/44269) [on CrossValidated](https://stats.stackexchange.com/a/138543/44269) [providing the](https://stats.stackexchange.com/a/558101/44269) [same insight](https://stats.stackexchange.com/a/96227/44269) to Peter Flom's answer.
Comment: Very ex cathedra view @peter-flom:) I disagree in general, i.e. that significance levels are a required condition that prevents overfitting. I agree in particular: the problem is the misguided attempts such as in step-wise regression to automate inference rather than get rid of if altogether. Regularized models such as LASSO (still in "pre-inference" state, despite being obsoleted by boosted trees and then DNNs) trained properly (i.e. with cross-validation) on tiny data sets with noisy targets can have entirely insignificant features, yet still achieve decent generalization.
Comment: @peter  thank you so much.


Flutter container inside a container

Question: I'm practicing with flutter Container these days, and this example I came up with is simply astonishing
I put a Container of size 50x50 inside a Container of size 200x200. Strange is that the inner Container expand to 200x200 even though it has a tight constraint of 50x50.
Here's the code
Container(
  width: 200.0,
  height: 200.0,
  color: Colors.orange,
  child: Container(
    width: 50.0,
    height: 50.0,
    color: Colors.blue,
  ),
)

I expect a small blue box inside a bigger orange box.
Could someone explain why?
Answer: You need to specify where in the orange box you would like the blue box displayed, otherwise the blue box will grow to the size of its parent.
  Container(
    width: 200.0,
    height: 200.0,
    color: Colors.orange,
    alignment: Alignment.center, // where to position the child
    child: Container(
      width: 50.0,
      height: 50.0,
      color: Colors.blue,
    ),
  ),

Comment: It's almost 3 years later.  Having to still specify the alignment as shown to avoid the unexpected expansion of the inner container is still very non-intuitive.  Couldn't have the Flutter team specified a default Alignment such as Alignment.topLeft to then avoid such illogic?!
Answer: In the code below we created a container that has a child called text and tried to style them a bit to make them look better.
Container(
  width: double.infinity,
  decoration: BoxDecoration(
    color: Colors.amber,
    borderRadius: BorderRadius.circular(15)
  ),
  padding: const EdgeInsets.all(10),
  margin: const EdgeInsets.all(10),
  child: const Text('orange juice is very delicious',
     textAlign: TextAlign.center,
     style: TextStyle(
       color: Colors.white,
       fontSize: 22,
       fontWeight: FontWeight.bold
     ),
  ),
),

Flutter container inside a container


Whether to enable a security-protected feature

Question: An Excel spreadsheet needs programmatic access to its Project structure.  However, this access is disabled by default.  It can be enabled programmatically, by writing to the registry with this snippet:
Set wsh = CreateObject("WScript.Shell")
'key to modify'
str1 = "HKEY_LOCAL_MACHINE\Software\Microsoft\Office\" & Application.Version & "\Word\Security\AccessVBOM"
'enable access'
wsh.RegWrite str1, 1, "REG_DWORD"
'read the vba project name'
MsgBox Application.NormalTemplate.VBProject.Name
'disable access'
wsh.RegDelete str1

Although it can be done (and reset) programmatically, this could create a security issue.
In my project, it attempts to modify the Project structure, and throws an error if it cannot.  The error can be caught, and at this point it can either run the snippet to enable access or display an error message to the user to enable access manually.  Is it better to enable the access via the program, where it can be disabled later, or instruct the user to do so?
Answer: It seems to me that the fact it can be done programmatically is a security issue. Given the existence of such a simple mechanism to override the default "protection", you're not exposing the user to a significantly greater risk by turning it off. Any virus writer worth their salt would be doing this anyway.
That said, turning it off for 20 seconds while you do your work and then turning it on again leaves the (broken) window open for far less time than asking the user to turn it off.
I'd be inclined to ask the user for permission to turn it off temporarily, and then make damn sure that I turned it back on again (since leaving it off would be a no-no).
Answer: Well, two things: It's pretty well known you can modify office security settings via the registry. So Office circumvents this by only reading the settings when the file opens. So if you change the settings with your code you will also need to close and reopen the file for the setting to take effect. Secondly tampering with the users security settings would be considered "rude" software. If the user want's to allow your code they will. Simply prompt them to enable the setting and restart the program. Anything past that would be considered poor behavior.
Remember, just because you can, doesn't mean you should:)
Comment: I posted this question with the best-practices tag because of the concern about writing "rude" software.  Your mention of Office only reading the setting on launch could render this moot -- does it check the registry on file open or on app open?


Suppressing windows command line PAUSE command

Question: I have been tasked with consolidating out entire teams' build process. Including build servers, CI, etc.
The way our project is structured is that each sub team is responsible for the development of their own code bases.
Over time, each team has usually created their own python/sh/bat/Wix depending on the requirements of their deployment.  I've been tasked with consolidating all the builds into one primary Team City system.
Problem is that I've found that  many build scripts (bat files) contain commands such as UI prompting and PAUSEing.
Does anybody know of any way to perhaps suppress those commands prior/during the script execution.
I have considered preprocessing the batch files and removing/REM'ing the Pauses but that is not ideal. Since there are +- 350 individual projects spread across +- 35 HG repositories (which are, in themselves, spread across 4 cities).
Ideally we don't want to perform pre-building cleanup.
Does anyone know of any supper-dupper magic trick to do this or does it required making changes to each build file,
Answer: You can disable input by redirecting input to nul: <nul yourScrpt.bat. This will effectively disable any PAUSE commands, but it will also disable any SET /P or other command that prompts for input.
If you disable input for a master bat script that calls other scripts, the child scripts will inherit the disabled input.
Comment: The more familiar equivalent is `yourScrpt.bat <nul`. +1 for considering `SET /P` etc.


Confidence intervals for series of Covid tests

Question: Suppose I take two antigen tests and each test has a specificity of 75.3% (95% confidence interval from 65.8% to 83.4%) e.g. from https://pubmed.ncbi.nlm.nih.gov/33455451/
A. what is the sensitivity of the two tests together?
Taking the equation off of https://radiopaedia.org/articles/sensitivity-and-specificity-of-multiple-tests
Combined sensitivity: (A)sen + [1 - (A)sen] x (B)sen
That would be 93.9%.
B. But what would I do with the confidence interval? Is it the same calculation?
That would give me 88.3 to 97.2%…
Is the correct way to calculate the confidence interval of the combined test?
C. In layman's terms... If I test negative both times, would I say that I am 95% confident that the result is at least 88.3% sensitive?
Answer: Let's begin with assuming the two tests are independent of one another (maybe run by a different lab, with reactants sourced from different companies, etc etc).
Sensitivity as a probabilistic concept is the probability you test positive given you have the disease, $P(T+ \vert D+)=p$.  I suppose the sensitivity of taking two tests is the probability at least one test is positive given you are disease positive.  If $p$ is the sensitivity of both tests, then the probability at least one is positive out of 2 is $2p(1-p) + p^2 = 2p - p^2$, which agrees with what you have presented.
As for the confidence interval, you could use the Delta method. The Delta method states that
$$ \operatorname{Var}(g(X)) = [g'(X)]^2 \operatorname{Var}(X) $$
Here, $g(x) = 2x - x^2$.  Some alegbra yields...
$$ \operatorname{Var}(2p-p^2) = [2-2p]^2 \operatorname{Var}(p) = \sigma^2 $$
Here, $\operatorname{Var}(p)$ would be whatever was reported as the variance for the sensitivity in the paper you linked. The last step is to take your estimate and add/substract two standard deviations (square root of the quantity obtained from the delta method).  Note that use of the Delta Method assumes asymptotic normality of the statistic of interest.


bootstrap editable rails type select has empty results

Question: I'm trying to use the type =  select with the gem 'bootstrap-editable-rails'.
The field pops up and there is a select box, but the values don't show up.
The Task record has a foreign key = rating_id and the value I want to show from the rating table is = ratingname
This is my view code:
<a href="#" class="answer" data-type="select" data-placement="right"  data-resource="task" data-source="/ratings" data-name="ratingname" data-url="/tasks/<%= task.id %>" data-original-title="Select Rating">
  <%= textarea_format(task.rating.ratingname) %>

UPDATE 1
Do I have to change the ratings.json to contain "text" and "value"?
UPDATE 2
I used RABL like this:
object @rating
attributes :id => :id, :ratingname => :text, :ratingvalue => :value

And now the selection values show up!
But, I get this error:
`call'
(gem) journey-1.0.4/lib/journey/router.rb:68:in `block in call'
- (gem) journey-1.0.4/lib/journey/router.rb:56:in `call'
- (gem) actionpack-3.2.12/lib/action_dispatch/routing/route_set.rb:601:in `call'
- (gem) rack-pjax-0.7.0/lib/rack/pjax.rb:12:in `call'
- (gem) meta_request-0.2.2/lib/meta_request/middlewares/app_request_handler.rb:11:in `call'
- (gem) rack-contrib-1.1.0/lib/rack/contrib/response_headers.rb:17:in `call'
- (gem) meta_request-0.2.2/lib/meta_request/middlewares/headers.rb:16:in `call'
- (gem) meta_request-0.2.2/lib/meta_request/middlewares/meta_request_handler.rb:13:in `call'
- (gem) pdfkit-0.5.3/lib/pdfkit/middleware.rb:16:in `call'
- (gem) warden-1.2.1/lib/warden/manager.rb:35:in `block in call'
- (gem) warden-1.2.1/lib/warden/manager.rb:34:in `call'
- (gem) actionpack-3.2.12/lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
- (gem) rack-1.4.5/lib/rack/etag.rb:23:in `call'
- (gem) rack-1.4.5/lib/rack/conditionalget.rb:35:in `call'
- (gem) actionpack-3.2.12/lib/action_dispatch/middleware/head.rb:14:in `call'
- (gem) remotipart-1.0.5/lib/remotipart/middleware.rb:30:in `call'
- (gem) actionpack-3.2.12/lib/action_dispatch/middleware/params_parser.rb:21:in `call'
- (gem) actionpack-3.2.12/lib/action_dispatch/middleware/flash.rb:242:in `call'
- (gem) rack-1.4.5/lib/rack/session/abstract/id.rb:210:in `context'
- (gem) rack-1.4.5/lib/rack/session/abstract/id.rb:205:in `call'
- (gem) actionpack-3.2.12/lib/action_dispatch/middleware/cookies.rb:341:in `call'
- (gem) activerecord-3.2.12/lib/active_record/query_cache.rb:64:in `call'

...

UPDATE 3
I've almost got it to work.
My RABL:
object @rating
attributes :ratingname => :text, :id => :value

I get the ratingname as the dropdown list !
I have the following happen when a value is selected !!
UPDATE "tasks" SET "rating_id" = 2, "updated_at" = '2013-03-28 08:21:36.869872' WHERE "tasks"."id" = 36

So, the dropdown list is good, the update is good.
BUT, the popup box with the rating select list turns red and doesn't go away!  And there are no errors in the browser console.
Answer: Got it to work.  I had to change the controller for tasks in the update section.
From:     format.json { head :ok }
To:       format.json { render json: @task }

Answer: Sometimes you may got js conflicts ,so check for console
Uncaught TypeError: Cannot use 'in' operator to search for 'value' in undefined
solution: use it inline as
$.fn.editable.defaults.mode = 'inline';


Proof by induction $\left(1 - \frac{1}{n^{2}}\right)^n \left(1 + \frac{1}{n}\right) < 1$

Question: I'm trying to prove that for every integer $n > 0\quad (P)$ :
$$\left(1 - \frac{1}{n^{2}}\right)^n \left(1 + \frac{1}{n}\right) < 1$$
This is what I did so far, using induction :
$$\text{for }(n = 1) : (1 - 1/1^2)^1 (1 + 1/1) = 0 < 1$$
Let's suppose that $(P)$ is true for all integers from $1$ to a certain $n$
and let's prove that $P$ is true for $n+1$ also :
I simplified the formula and now it looks like this :
$$(P) : \left(\frac{n-1}{n}\right)^n < \left(\frac{n}{n+1}\right)^{(n+1)}$$
So if we define $Q(n) = (\frac{n-1}{n})^n$
We have $Q(n) < Q(n+1)$
and we need to prove that $Q(n+1) < Q(n+2)$
That's where my head stopped. Can anyone help me please ?
Comment: I don't think it's true...
Comment: Sorry my bad, I forgot to add the power of n. I just edited the question. Can you take a look ?
Comment: The technique you're trying to use is called "Induction" not "Recurrence".
Comment: @Henrik Sorry I'm just used to the french nomenclature. In french, we call it démonstration par récurrence.
Answer: Consider the function
\begin{eqnarray*}
y= \frac{x^{x+1}}{(1+x)^{x+1}} \\
\frac{1}{y} \frac{dy}{dx} =\frac{1}{x} +\ln x - \ln (1+x) \color{yellow}{>0}
\end{eqnarray*}
Now for $x>0$ we have $e^{\frac{1}{x}} > 1+ \frac{1}{x}$ & so
\begin{eqnarray*}
x+1 < x e^{\frac{1}{x}} \\
\ln (x+1) < \frac{1}{x}+ \ln(x).
\end{eqnarray*}
In other words, our function $y$ is monotonically increasing & so
\begin{eqnarray*}
\frac{(n-1)^n}{n^n} < \frac{n^{n+1}}{(1+n)^{1+n}}
\end{eqnarray*}
This can be rearranged to give your result.


Compare 4 variables to find the lowest C++

Question: I want to find the lowest number of the four, but this looks kinda wierd , isnt there a smarter and shorter way to do it?
That is what I have:
int findlowest(int one, int two, int three, int four) {
    int output = one //as of now , we will be outputting one , except if we find a lower score.
    if(output > two) { out = two;} // if output is proven to be bigger than two, two is our new output.
    if(output > three){ output = three;} //same operation with three
    if(output > four){ output = four;} // same operation with four
    return output;
}

Answer: std::min(a, std::min(b, std::min(c, d)));

Include <algorithm>.
Comment: because std::min(a,b) and std::min(c, d) in my version can be done in parallel.
Comment: @osgx: No functional difference.
Comment: @osgx: None. Why would there be any difference?
Comment: is the balanced tree better `std::min(std::min(a,b), std::min(c, d));`?
Comment: Crap you beat me by 7 seconds, and mine had a mistake!
Comment: @osgx: Compare generated assembly for both. It'll be near identical (order of some instructions might be bit different, but there is exactly the same number of branches and comparisons).
Comment: @CatPlusPlus let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/1143/discussion-between-osgx-and-cat-plus-plus)
Answer: c++11:
int minimum = std::min( { 1,2,3,4,5 } );

Comment: That's 5 values. How do you do 4, like was asked for? :-)
Comment: What compiler are you using? gcc 4.6 with -std=c++0x doesn't like this.
Comment: @juanchopanza Works fine with g++4.5
Comment: Sweet, thanks! I used to write my own variadic `min`, but this is much better!
Answer: min_int = min(min(one, two), min(three, four));

Answer: int a[] = {1,2,3,4,5};
int minimum = *std::min_element(a, a+5);

Comment: This version of `std::min_element` returns an "iterator" to the position of the minimum, so you need to dereference it.
Answer: Lots of answers saying to use the Standard library facilities - they're right, it covers this case!  But, for the educational value, here's a slightly more concise way to do what you were doing:
int findlowest(int a, int b, int c, int d)
{
    int of_a_b = a < b ? a : b;
    int of_c_d = c < d ? c : d;
    return of_a_b < of_c_d ? of_a_b : of_c_d;
}

Easily generalised for different types (though C++03 doesn't make it easy to generalise for arbitrary numbers of arguments):
template <typename T>
T findlowest(const T& a, const T& b, const T& c, const T& d)
{
    const T& of_a_b = a < b ? a : b;
    const T& of_c_d = c < d ? c : d;
    return of_a_b < of_c_d ? of_a_b : of_c_d;
}

Comment: 1) How do you convert `T a` to `int of_a_b`? 2) your `of_*` should be const.
Comment: Kerrek: 1) well spotted, thanks. 2) actually, I'll change them to const references so there's no potential copy invoked there.  Cheers.


Sails mongodb missing connection handling

Question: Very simple and stupid question I came up with today when was playing around with sails and mongo db (adapter of the waterline odm). I just shut down the mongo while my sails server still has been running and saw nothing, neither in logs of sails or in the browser. How I could handle such situation?
Answer: If sails.js attempts a connection to the DB you will most certainly get a message in your console if the Mongo server is shut down, but if no request is made that requires a DB connection, then you will not see any error because no error as of yet exists.
It sounds like you might require a process that will monitor your DB and check to make sure it is still running? There are Sail.js options where you could create a CRON job to check the connection. Or you could use other application monitoring services like New Relic to monitor your DB.
Comment: When i just sarting sails and there is no mongo server, than I get message, you're right. But if sails server is already running and I try to make a request to the mongo server, which might for example be crashed, than I get nothing in logs. It's strange that sails not trows any exceptions about it.
Comment: Seems like mongoose has a such monitoring process.
Mongoose connection error: [Error: failed to connect to [localhost:27017]]


Cannot get rules component to fire on Commerce Completing the checkout process

Question: I have a baffling situation. I created a nice little rules component that retrieves a list, using VBO, of published Drupal Commerce Product Display nodes with referenced product stock of zero or less. And then loops through that list unpublishing each node. This is how I built it - https://drupal.org/node/1345216#comment-8306801
This component works as expected when executing it by itself or when placing it in a rule with the "After updating an existing commerce product" and/or "After updating existing content" events. I cannot get it to run when attaching it to a "Completing the checkout process" event.
Any ideas? Is it a permissions issue, as in customer cannot run the component or access the VBO list?
Is there another event related to a customer completing an order that might work better?
Answer: It's possible the user doesn't have access to execute the rules component. You can check the permission in admin user permissions or on the rule component edit page.
Keep in mind the rules component will need to be attached to a reaction rule to fire on the checkout complete event.
Other than that, if the component can process the passed <code>$commerce_order</code> parameter (passed to checkout complete), then it should be ok.
Comment: The second point you mentioned, "on the rule component edit page" was the setting I needed. There is a toggle in the Settings fieldset that I had missed - '**Configure access for using this component with a permission.**' Allowing all users access lets the process work as intended. Thank you


Find the condition on $a,b,c$ such that $(a,b,c) \in \operatorname{span}((2,1,0) , (1,-1,2), (0,3,-4))$

Question: Find the condition on $a$, $b$, $c$  so that $(a,b,c) \in \mathbb{R^3}$ is in the space generated by $(2,1,0)$, $(1,-1,2)$ and $(0,3,-4)$
If $(a,b,c)$ lies in the space generated by given vectors then it must be equal to the linear span.
$(a,b,c) = \alpha(2,1,0) +\beta(1,-1,2) + \gamma(0,3,-4)$
Upon solving this system for $\alpha$, $\beta$ and $\gamma$  I ended up with following equations
$\alpha - \beta + 2\gamma = b$
$0\alpha + 3\beta - 4\gamma = a-2b$
$0\alpha + 0\beta + 0\gamma =  c-a+2b$
Since the given system needs to be consistent we must have $c-a+2b = 0$
However, my book says the correct answer is $2a - 4b - 3c = 0$
Please tell me what is wrong with my solution and what should be  the correct way to solve it.
Thank you.
Answer:
$(a,\color{blue}{b},c)$ = $\color{blue}{\alpha}(2,\color{blue}{1},0)$ +$\color{blue}{\beta}(1,\color{blue}{-1},2)$ + $\color{blue}{\gamma}(0,\color{blue}{3},-4)$
Upon solving this system for $\alpha$ , $\beta$ and $\gamma$  I ended up with following equations
$\alpha$ - $\beta$ + $\color{red}{2}\gamma$ = $b$

How did you arrive at the equation above? Looking at the second coordinate (in blue); I'd expect:
$$b=\alpha-\beta+\color{purple}{3}\gamma$$
Answer: Your book is right. The system is$$\left\{\begin{array}{l}2\alpha+\beta=a\\ \alpha-\beta+3\gamma=b\\ 2\beta-4\gamma=c.\end{array}\right.$$Multiplying the second equation by $-2$ and adding this to the first one, you get$$\left\{\begin{array}{l}3\beta-6\gamma=a-2b\\ \alpha-\beta+3\gamma=b\\ 2\beta-4\gamma=c.\end{array}\right.$$This is equivalent to$$\left\{\begin{array}{l}\beta-2\gamma=\frac13(a-2b)\\ \alpha-\beta+3\gamma=b\\ \beta-2\gamma=\frac12c\end{array}\right.$$So, the system is consistent if and only if $\frac13(a-2b)=\frac12c$, which is equivalent to the answer provided by your book.
Comment: Thank you for the answer!. I must have done some arithmetic error while solving the equations
Answer: Let us try to find $c_1$, $c_2$, $c_3$ such that the given vectors fulfill the condition $c_1x_1+c_2x_2+c_3x_3=0$. (If this is true, any vector $(a,b,c)$ belonging to their span fulfills the same condition.)
From this we get a system of three linear equations
\begin{align*}
2c_1+c_2&=0\\
c_1-c_2+2c_3&=0\\
c_1+2c_2-2c_3&=0
\end{align*}
Solving this system of equations we get that $(c_1,c_2,c_3)$ has to be a multiple of the vector $(2,4,3)$.
This can be said equivalently like this: The span of the three given vectors is exactly the set of vectors $\{(x_1,x_2,x_3)\in\mathbb R^3; 2x_1+4x_2+3x_3=0\}$.

This is related to the fact that every subspace of $\mathbb R^n$ is equal to solution set of some homogeneous system of linear equations.
By solving the system with unknowns $c_{1,2,3}$ we found such homogeneous system. (In this case it consisted of only one equation.)


Retorno de objetos select (ComboBox) com Hibernate + JSP + VRaptor. Não preenche relacionamento entre tabelas

Question: Tenho um objeto TabelaPrecoItem com todas a estrutura formada e quase tudo funcionando,
segue o modelo do model.
    @Entity
    @Table(name = "fov_tabela_preco_itens")
    public class TabelaPrecoItem implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 7517120126809692389L;

    @Id
    @GeneratedValue
    private int id;

    //    @Column(name = "tab_id")
    //    private Integer tab_id;

    //    @Column(name = "pro_id")
    //    private Integer id_produto;

    @Column(name = "tpi_preco")
    private Double preco;

    @Column(name = "tpi_minimo")
    private Double minimo;

    @Column(name = "tpi_maximo")
    private Double maximo;

    @NotNull(message = "Campo \"Tabela de Preço\" precisa ser informado.")
    @JoinColumn(name = "tab_id")
    @OneToOne(targetEntity = TabelaPreco.class)
    @NotFound(action = NotFoundAction.EXCEPTION)
    private TabelaPreco tabelaPreco;

    @NotNull(message = "Campo \"Produto\" precisa ser informado.")
    @JoinColumn(name = "pro_id")
    @OneToOne(targetEntity = Produto.class)
    @NotFound(action = NotFoundAction.EXCEPTION)
    private Produto produto;

Basicamente tudo está funcionando. O método do controler que seleciona está retornando todos os objetos corretamente, estou com problemas é quando eu tento editar esse objeto.
Criei o JSP da seguinte forma

<form id="formCadastro" method="post"  accept-charset="UTF-8" class="smart-form" onsubmit='<c:if test="${acao != \"exibir\"}">submitForm("tabelaprecoitem", "formCadastro");</c:if> return false;' action="#">
    <fieldset>

                 Tabela de Preço

                        <select name="tabelaPrecoItem.tabelaPreco.id" required  disabled="disabled">
                            <option value="">Selecione uma Tabela</option>
                            <c:forEach var="tabela" items="${tabelaPrecoList}">
                                <option value="${tabela.id}" <c:if test="${tabela.id eq tabelaPrecoItem.tabelaPreco.id}">selected="selected"</c:if>>${tabela.descricao}</option>
                            </c:forEach>
                        </select >

                ID

                        <input type="text" value="${tabelaPrecoItem.id}" disabled="disabled">
                        <input type="hidden" name="tabelaPrecoItem.id" value="${tabelaPrecoItem.id}">

                 Produto

                        <select name="tabelaPrecoItem.produto.id" required  disabled="disabled">
                            <option value="">Selecione um Produto</option>
                            <c:forEach var="produto" items="${produtoList}">
                                <option value="${produto.id}" <c:if test="${produto.id eq tabelaPrecoItem.produto.id}">selected="selected"</c:if>>${produto.descricao}</option>
                            </c:forEach>
                        </select >

                 Preço

                        <input type="number" step="0.01" placeholder="Ex: 20" name="tabelaPrecoItem.preco" value="${tabelaPrecoItem.preco}" required>

                 Mínimo

                        <input type="number" step="0.01" placeholder="Ex: 20" name="tabelaPrecoItem.minimo" value="${tabelaPrecoItem.minimo}" >

                 Máximo

                        <input type="number" step="0.01" placeholder="Ex: 20" name="tabelaPrecoItem.maximo" value="${tabelaPrecoItem.maximo}">

    </fieldset>

             Campo(s) Obrigatório(s).

        <c:if test="${acao != \"exibir\"}">
            <button id="salvarModal" class="btn btn-sm btn-success" type="submit"> Salvar</button>
        </c:if>
        <button id="fecharModal" type="button" class="btn btn-sm btn-danger" data-dismiss="modal"> Fechar</button>

</form>

Quando eu preencho os objetos com o método
    @Get("/{id}/editarproduto")
    public void editar(Integer id) {
        TabelaPrecoItem TabelaPrecoItemAux = null;

        try {
            TabelaPrecoItemAux = this.repository.loadById(id);

        } catch (Exception e) {
            this.showErrorViewExceptionValidator(e,
                    "Falha ao carregar dados do Item da Tabela de Preços id " + id
                            + ", por favor tente novamente!", "TabelaPrecoItem");
        }

        this.result.include("acao", "editar").
        include("tabelaPrecoItem", TabelaPrecoItemAux).
        include("tabelaPrecoList",this.tabelaPrecoRepository.loadAll()).
        include("produtoList",this.produtoRepository.loadAll()).
        forwardTo(this).cadastroProduto();
    }

A tela é preenchida de forma correta. Mas quando eu chamo o método de edição, para gravar as alterações no banco de dados, os objetos de tabelaPrecoItem.produto e tabelaPrecoItem.tabelaPreco estão retornando como null.
@Post("")
    public void salvar(TabelaPrecoItem tabelaPrecoItem) {
        String message = "";
        try {
            // Realiza a validaçãoo Server-Side
            this.validator.validate(tabelaPrecoItem);

            // Verifica erros e retorna para camada de visão, caso contrario
            // segue o fluxo normal de cadastro
            if (this.validator.getErrors().size() == 0) {

                if (tabelaPrecoItem.getId() == 0) {
                    tabelaPrecoItem = repository.add(tabelaPrecoItem);
                    message = "Novo Produto da Tabela de Preços id " + tabelaPrecoItem.getId()
                            + " cadastrado com sucesso!";

                } else {
                    tabelaPrecoItem = repository.update(tabelaPrecoItem);
                    message = "Produto da Tabela de Preços id " + tabelaPrecoItem.getId()
                            + " alterado com sucesso!";
                }
            }

        } catch (Exception e) {
            this.showErrorViewExceptionValidator(
                    e,
                    "Falha ao tentar salvar dados do Produto da Tabela de Preços, por favor tente novamente!",
                    "TabelaPreco");
        }

        // retorna o objeto de retorno fora do try catch para evitar exception
        // desnecessárias
        if (!message.equals("")) {
            result.use(Results.json()).withoutRoot().from(message).serialize();

        } else {
            this.returnErrorValidatorMessage();
        }
    }

E com isso não passa no validate.
Answer: na hora de carregar sua entidade ele não esta carregando as entidades relacionadas, você pode conseguir isso usando "cascade" que é um atributo das anotações de relacionamento como por exemplo:
@OneToOne(cascade=CascadeType.ALL)
isso faz com que qualquer operação na entidade seja reproduzida nas entidades relacionadas,
mas você pode limitar isso para uma unica operação com os outros tipos de Cascade: PERSISTE,MERGE,REMOVE, REFRESH
Comment: Coloquei a anotação no model `@OneToOne(cascade=CascadeType.ALL,targetEntity = Produto.class) ` e `@OneToOne(cascade=CascadeType.ALL,targetEntity = TabelaPreco.class)` mesmo assim no retorno do objeto do JSP para a classe ele ainda está vindo como null `"tabelaPrecoItem"  (pending)
 id 1
 maximo Double  (id=133)
 minimo Double  (id=137)
 preco Double  (id=138)
 produto null
 tabelaPreco null
` acho que os selects (Combobox) do JSP não estão preenchendo os objetos. Pode ser algum erro no name deles ?
Answer: O comboBox na tela estava como Disabled, por esse motivo o Vraptor não identifica o objeto.
Para solucionar eu habilitei o combobox antes do post e desabilitei novamente após o post.


I want to stop/Pause the designer workflows which are associated with sharepoint list and restart once the new version updated?

Question: We have a sharepoint list and few designer workflows are associated with it. We have made some changes to the existing workflow but not published as it might affect the current list items where we have reassigned permission and status for many list items. In this case we would like to stop workflows which are still running or in progress for specific list items in Sharepoint list. once the deployemnt is done (New version of the workflow is published), we need to restart the workflows for the list items we stopped.
I believe this is possible through Powershell script.
please post our suggestions and solution if you have an idea.
Thanks,
Peter
Answer:

<code>#Site URL
$web = Get-SPWeb "http://urlforsite.com";
$web.AllowUnsafeUpdates = $true;

#List Name
$list = $web.Lists["ListName"];

# Iterate through all Items in List and all Workflows on Items.
foreach ($item in $list.Items) {
foreach ($wf in $item.Workflows) {

#Cancel Workflows
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
}
$web.Dispose();</code>

To restart any workflow, you can just had a column to a personal view as either a yes/no choice.  On the existing workflow do an if statement for the column to change then change back.


Let $G$ be a group. Let $G/K$ be an abelian group. Prove that $C=\{e\}$.

Question: I'm stuck at this exercise:

Let $G$ be a group, with $|G|=pqr$, $p,q,r$ different primes, $q<r$, $r \not\equiv 1$ (mod $q$), $qr<p$. Also suppose that $p \not\equiv 1$ (mod $r$), $p \not\equiv 1$ (mod $q$). Let $C$ (the commutator of $G$) and $K$ be subgroups of $G$, with $C \leq K$, $K \trianglelefteq G$ and $|K|=q$. $K$ is the unique Sylow $q$-subgroup on $G$ (so $K \trianglelefteq G$). Let $G/K$ be an abelian group. Prove that $C=\{e\}$.

I tried using Lagrange theorem, knowing that $C\leq K$, and then $|C|=\{1\ or\ q\}$. But I don't know how to eliminate the option $|C|=q$.
This is a little part from a longer exercise. The definition of $C$ is $C=\langle[a,b]=aba^{-1}b^{-1} \mid a,b\in G \rangle$, $G/C$ is abelian too.
Thank you.
Comment: You must be missing something, since $K = C$ satisfies your problem statement.
Comment: Yes, that's what I came up with too. I'll complete the question with some more information. Thanks.
Comment: @DavidWheeler It changes something if $K$ is the unique Sylow $p$-subgroup of $G$?
Comment: $G= D_6 \times C_5$, $p,q,r=3,2,5$ gives $C=K$. Also how is $H$ involved?
Comment: @DerekHolt There're more restrictions. I'm going to edit it and put the whole exercise because it's leading to confusions.
Answer: $\newcommand{\Span}[1]{\langle#1\rangle}$$G/K$ is abelian of order $p r$, thus cyclic. If you can prove that $K \le Z(G)$, then it follows that $G$ is abelian.
To prove this, let $K = \Span{z}$. We have that $G/C_{G}(K)$ has order dividing $q-1$.
Let $a$ be an element of order $p$, and $b$ an element of order $r$. Since $p > q r > q$, we have that $a$ centralizes $z$. Since $r > q$, we have that $b$ centralizes $z$. Hence $z$ is central, as required.

Lemma. Let $G$ be a group. Suppose $G/Z(G)$ is cyclic. Then $G$ is abelian.
Proof. Suppose $G = \langle a, Z(G) \rangle$. Then two arbitrary elements of $G$ can be written as $a^{i} z, a^{j} w$, with $i, j$ integers, and $z, w \in Z(G)$. Thus
$$
(a^{i} z) (a^{j} w) = a^{i} a^{j} z w = a^{j} a^{i} w z = (a^{j} w) (a^{i} z).
$$
Comment: @Abrahamlure, no way that way.
Comment: Hi @Andreas . There's a way to prove it without using the centralizer? I think that they want us to deduce it, like if it was easier than this.
Comment: @Abrahamlure, perhaps you have further information about $H$, which at the moment, as noted by Derek Holt, plays no role?
Comment: ... I'm so sorry. I use to name $H$ to a subgroup of $G$. Every $H$ is a $K$. It's edited now.
Comment: I think that the important thing here is that $K$ is the unique Sylow $q$-subgroup. There's some way to say that $C\neq K$ because $K$ is the unique Sylow $q$-subgroup?
Comment: why showing that $K \leq Z(G)$ implies $G$ is abelian? I think I'm missing something.
Comment: @Abrahamlure, I have just added the relevant Lemma.
Comment: Thanks, I didn't found any easier way to do my exercise, so I'm going to try to understand your resolution.
Comment: @Abrahamlure, please feel free to ask any further questions.


Android Studio - no image and button color showing in both design and when I run it on my device

Question: there is no image and button color showing in both design and when I run it on my device.
There are no problems with my other images which was in .jpg and .png format. Those images that aren't showing are the background for my button and is also in .png. The same problem with the color of my button, it isn't showing also.
I tried transferring those background images for my button images to 'mipmap-xxxhdpi' but still no changes.
Answer: can you explain in more details what are you trying to do,
If that helps try add the image to the drawable folder
and add this line to your button in the XML file
<code>android:background="@drawable/image_name_here"
</code>
also the name has to be all in lowercase and with not " _ " characters
Comment: it was in the drawable folder first still no showing and tried it by transferring the image in the mipmap but it did not solve the problem.
Comment: I already resolve it. the problem is with my themes, it was in 'darkactionbar', I changed  it to 'Theme.AppCompat.Light.NoActionBar' and it was solve. still, thanks. Now, another problem occured, when I click the button it doesn't go to the new activity I assigned it to. :(
Comment: can you send how are you trying to assigned it to the button via the code?
Comment: @feonicainocen You could do something like "startActivity(new Intent(getApplicationContext(), NextActivity.class));" in case you don't have that in your onClick() method of the button.


Shortest time between separated yellow card cautions for one player?

Question: In the June 10th Copa America match between USA and Paraguay, USA defender DeAndre Yedlin was cautioned with a yellow card, and then 57 seconds later was cautioned a second time and sent off for accumulation of two yellows.  Is this the shortest time between two cautions for one player?  Limit answers to senior international and professional teams.
This is different that the question found here: Can a player receive two yellow cards if advantage is played?.  Both cards could be awarded at the same stoppage of play, but I am looking for a case of "A player knows he has been cautioned, but immediately proceeds to commit another offense" instead of "player commits two offenses when he technically doesn't know he was going to be cautioned for the first offense".
Comment: Di Maria cautioned for failure to respect the required distance twice in a number of seconds: https://www.youtube.com/watch?v=aqwZusZCG04
Answer: The obvious scenario for this is a player being booked for any reason, then showing obvious dissent to the referee, and receiving a second yellow card before play is restarted.
An example of this happened to Brad Evans, captain of the Seattle Sounders, in a match against Colorado Rapids in April 2016.
The match report shows two yellows in the 86th Minute:

86'  Brad Evans (Seattle Sounders FC) is shown the yellow card.
86' Second yellow card to Brad Evans (Seattle Sounders FC).

According to the News Tribune reporter Don Luiz, Evans explained the cards like this:

I asked [the ref] how [the tackle] was different to my tackle in the first half. He said "It's different, it's different'. I said you need to talk to me. He said no. I gave him an expletive; he gave me a yellow card. I said it's your duty to talk to me on the field. He said "No it's not'. I gave him another expletive, and that was the double yellow.

I doubt that this is the record, as Evans and the referee had a short discussion between the two cards, and assume that there must have been quicker double yellows in similar circumstances.


Not Skolem's Paradox

Question: Assume we have a countable, non-standard model of Peano Arithmetic (PA) in ZFC.
http://en.wikipedia.org/wiki/Non-standard_model_of_arithmetic
Let $N^*$ be the universe of this model and let $m \in N^*$ be a non-standard natural number larger than any standard natural number. $2^m \in N^*$ is the size of the $P(m)$, the powerset of numbers less than m, inside the model. We can even encode a bijection between $P(m)$ and $2^m$ inside the model. For example, we can encode a set as an m-bit string. x is a member of the set if the x'th bit of the string is true. Each such string is the binary representation of a natural number less than $2^m$.
Skolem's paradox considers a set that is uncountable inside the model yet countable outside the model. Here, we have a finite bijection inside the model which seems to be uncountable outside the model.
My question is how can the countably infinite set $X = \{x : x \in N^* \land x < m\}$ have a countable powerset? How can $Y = \{y : y \in N^* \land y < 2^m\}$ be a countable set inside ZFC? We can show there is a bijection between $P(X)$ and $Y$.
I know the answer must be something like the model doesn't "see" all of $P(m)$. If this is the answer, would someone give an example of a set of standard natural numbers the model can't "see"? For example, does there exist a binary representation of a standard real number such that this binary string is not a proper subset of the binary representation of some non-standard natural number inside the model.
Answer: First of all, models of $\sf PA$ don't see sets, they see integers. Perhaps what you wanted to say that you have $N$ which is a non-standard model of $\sf ZFC$ whose integers are a non-standard model of $\sf PA$.
Other than that, the reason that you give is correct. Yes, there are uncountably many subsets to that [proper] initial segment of $\omega^N$, but $N$ is countable and don't know them all, and moreover it thinks that collection is finite. An example of a standard set of integers not in the model is easy: $\omega$ itself. If it were there, it would have to be equal to $\omega^N$ in which case the integers were standard.
Comment: @Russell: You seem to confuse the objects of the model with the definable relations on the model, and with other possible things. The model only has integers in it. Not strings, not sets, not anything else. True, these objects are realized as sets in a universe of $\sf ZFC$, but that is hardly the point here. The point is what are the objects which reside inside the model, and what is definable over the model.
Comment: If we represent sets of standard natural numbers as $\omega$ length binary strings then the set of all standard natural number would be a string of all 1's. ($2^m$ - 1) has a binary representation that has $m$ 1's. Since $m > \omega$, the first string is a proper subset of the second.

Not Skolem's Paradox