Node.js (with socket.io and express) throw "events.js:71 throw arguments[1]; // Unhandled 'error' event"

Question: I'm running express (via nginx proxy) with socket.io and after few moments (app for some time works fine) console throw this:
<code>events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: socket hang up
    at createHangUpError (http.js:1360:15)
    at ServerResponse.OutgoingMessage._writeRaw (http.js:507:26)
    at ServerResponse.OutgoingMessage._send (http.js:476:15)
    at ServerResponse.OutgoingMessage.write (http.js:749:16)
    at XHRPolling.doWrite (/home/xyz/chat/node_modules/socket.io/lib/transports/xhr-polling.js:67:17)
    at XHRPolling.HTTPPolling.write (/home/xyz/chat/node_modules/socket.io/lib/transports/http-polling.js:132:8)
    at XHRPolling.Transport.onDispatch (/home/xyz/chat/node_modules/socket.io/lib/transport.js:222:10)
    at Socket.dispatch (/home/xyz/chat/node_modules/socket.io/lib/socket.js:230:38)
    at Socket.packet (/home/xyz/chat/node_modules/socket.io/lib/socket.js:214:10)
    at Socket.emit (/home/xyz/chat/node_modules/socket.io/lib/socket.js:368:15)
</code>
Any ideas?
Comment: It means that there is an error, maybe at connecting time, and you don't have a handler for that. Can we see the code you are using to setup socket.io ??
Comment: Similar issue here: http://stackoverflow.com/questions/15039089/my-node-js-app-is-getting-an-unhandled-error-event-randomly-on-writing-request
Answer: If you are using node.js version 0.8.20, then this bug was observed by many including myself.
https://github.com/LearnBoost/socket.io/issues/1160
Upgrading node.js to version 0.8.21 solves this problem.
Comment: @otmezger this particular issue happened due to the fix in 0.8.20 (http: Raise hangup error on destroyed socket write) and upgrading node to 0.8.21 had solved this issue for me and as reported by others (https://github.com/ether/etherpad-lite/issues/1541). May be you can try out 0.8.19 or above 0.8.21 to double check.
Comment: it can be. I found an error elsewhere. now it is gone. It was not the same issue.


htaccess redirection

Question: www.source.com should be redirected to www.destination.com
but www.source.com/mypage.html should not be redirect, it should still navigate to www.source.com/mypage.html
I tried this
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) www.destination.com/$1 [R=301,L]

when I accessed www.source.com/mypage.html, it displays page not found as there is no page www.destination.com/mypage.html.
How can I achieve this redirection?
Answer: RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?source\.com$ [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ http://www.destination.com/ [R=301,L]

Comment: source.com, www.source.com, [http://www.source.com](http://www.source.com) all should be redirected. How to achieve this?
Comment: Check out my updated answer.

htaccess redirection


Decomposition in irreducible factors in a factor ring

Question: I'm currently learning for my Commutative Algebra exam and I have the following question:
Given $\mathbb Z$ the ring of all integers and the ring $\mathbb Z[X, Y]$ the ring of polynomials in indeterminates X and Y with coefficients in $\mathbb Z$. We also consider the factor ring:
$R = \mathbb Z[X, Y]/(Y^2+1)$,
I noticed that $5$ is not a prime in $R$, since we can decompose
$Y^2 + 1 = (Y-2)(Y-3)$ in $\mathbb Z_5$.
My question is:

How do I determine the decomposition of $5$ into prime factors in $R$ ? (I need this in order to compute the irredundant primary decomposition of an ideal in this given ring $R$).

More general, how can we determine the decomposition of an element in prime/irreducible factors in such rings of polynomials?
Thank you!
Comment: Please check my edit, and you might also want to check out this MathJax tutorial: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Don't you mean $\Bbb Z[X,Y]/(Y^2+1)$?
Comment: Of couse, thank you.
Answer: Observe that $R \cong \mathbb{Z}[i][x]$ and then use the usual tools (norm map $N \colon \mathbb{Z}[i] \rightarrow \mathbb{Z}$, the ring is an integral domain, so we can argue by degree of polynomials etc.) - one finds $N(5)=25$, so if there is a non-trivial decomposition $5=fg$, then $f$ and $g$ are elements of $\mathbb{Z}[i]$ with $N(f)=N(g)=5$. But $x^2+y^2=5$ has (upto sign permutation) only one solution - namely $x=2$, $y=1$ - which in our case provides a decomposition $5=(2+i)(2-i)$.
Transporting this decomposition via the isomorphism, we have in $R$ that $5=(2+Y)(2-Y)$.
Comment: The answer is great, thank you very much!


C# Read Eventlog from evtx file with EventLog Class

Question: I'm trying to read a stored .evtx with the EventLog Class from System.Diagnostics.
but it doesn't work.
Isn't it possible to read a stored evtx file with EventLog Class or where is the problem?
Below is My Code
<code>string source = @"S:\test.evtx";

                    EventLog eventLog = new EventLog();
                    eventLog.Source = source;

                    foreach (EventLogEntry log in eventLog.Entries)
                    {
                        Console.WriteLine("{0}\n", log.Message);
                    }
</code>
Answer: The Source Property of the EventLog refers to the Application Sources in the Event Viewer and not necessarily the source file that you exported.

You need to supply the Source property with a name of an application, not a file name.
UPDATE: If you insist on reading from an evtx, then the EventLogReader class must be the solution.
<code>//EVENT LOG READER
        string source = @"C:\testev.evtx";

        using (var reader = new EventLogReader(source, PathType.FilePath))
        {
            EventRecord record;
            while ((record = reader.ReadEvent()) != null)
            {
                using (record)
                {
                    Console.WriteLine("{0} {1}: {2}", record.TimeCreated, record.LevelDisplayName, record.FormatDescription());
                }
            }
        }

//EVENT LOG
        EventLog eventLog = new EventLog();
        eventLog.Source = "ESENT"; //name of an application

        foreach (EventLogEntry log in eventLog.Entries)
        {
            Console.WriteLine("{0}\n", log.Message);
        }
</code>
Comment: Thank you for your reply.
But how can I add a source, because the evtx file lies on a network share ?
Comment: I am not sure why do you need to read from an evtx. But if you need to read from an Event Viewer of the other computer, you need to supply the MachineName property.
Comment: I don't know if you tested it or not, but I already found this way in the following thread
https://stackoverflow.com/questions/30809133/read-event-log-file-from-path?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

But the problem is, that record.FormatDescription() returns Null every time..
Comment: FormatDescription gets the event message in the current locale. You may want to counter check if the events in your evtx file has events message by importing it in your local Event Viewer


How to return the combinations of numbers in a function?

Question: I have been trying to solve this python problem involving permutations. For example, this is what should happen when I call the function:
combinations(2, 3) ➞ 6
combinations(3, 7, 4) ➞ 84
combinations(2, 3, 4, 5) ➞ 120
I don't know why but when I call it (down below) it returns 2 for some reason. I know computers just follow instructions so there must be something wrong with my code. I don't know what though, please someone tell me! Thank you!
def combinations(*items):
    permu = []
    for i in range(0, len(items)):
        if i == 0:
            permu.append(items[i]*items[i+1])
        else:
            permu.append(items[i]*permu[i-1])

    return sum(permu)

print(combinations(1,2,3,4))

Comment: can you explain what `combinations` is supposed to do?
Comment: Does this answer your question? [Returning the product of a list](https://stackoverflow.com/questions/2104782/returning-the-product-of-a-list)
Answer: If you are using python > 3.8 then you can simply use math.prod:
import math

def combinations(*items):
    return math.prod(items)

Answer: You can create a list of all the numbers and loop through it.
def combinations(*items):
    mult_list = list(items)
    result = 1

    for mult in mult_list:
        result *= mult

    return result

print(combinations(2, 3, 4, 5))

Comment: `items` is already a `tuple` which is iterable. Converting it to a `list` is not neccessary.
Answer: Here is the shortest solution I could come up with:
def combinations(tuple_):
    exec(f'print({"*".join([str(n) for n in tuple_])})')

combinations((2, 3, 4, 5))

exec() basically interprets the given string as python code and executes it so in this case it prints out 2 * 3 * 4 * 5 because since they all are string then converting to python the string part "disappears" so they are integers again. (if You wanted them to be string You would have to explicitly declare that) it is also important to convert the integers in the tuple to string so that is why there is the list comprehension it creates a list of string n for every n in the tuple


Replace new method dexlib2 failing

Question: I am using dexlib2 to rewriting existing apk through one jar utility. I want to change one instruction with my own instruction. It is basically returning some object and I want to replace it with another method which is returning different object. It is able to replace method but when I have viewed updated dex, I can see next line with .local v1, manager:Lblah/KeyguardManager;
Code which i want to replace
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);

Code which should be replaced against above:
Manager mgr=Manager.getInstance(this)

I have used getInstructionRewriter method to replace it. It replace the method but I am not able to figure out how to replace .local v1, manager:Lblah/KeyguardManager; with .local v1, manager:Lblah/Manager;
Comment: I don't really know but you can check this project to see if there is something similar there https://github.com/khaledblah/dex_tainting
Comment: Your problem is not clear. You can replace `v1` just like you said. To be sure, you can decompile a code which has `Manager mgr=Manager.getInstance(this)` in it, and see how it is in `smali` and then copy it in that file of your `jar` class. If it is not what your question is about, please add the lines of decompiled jar file you want to change (I mean the `smali` code of it not the `java` code).
Answer: You should make sure that Lblah/Manager exists in your apk.
If you just want to make this change in one .smali file and leave other files unchanged, that will be easy. You have to fine all occurance of KeyguardManager in this file and replace the call they make with corresponding call in Manager class. Then repackage your apk and test it.
If you have error in recreating the apk file or after installing new apk, then it may be some mismatches in the cahnges you made and you have to find out what is the problem. In this case, you can post the error here and we will see what we can do! :)

Replace new method dexlib2 failing


How to get the body trimmed when loading nodes programmatically?

Question: I'm getting my nodes directly using db_query (I'm applying some specific conditions), so I can't use the render function allowing me to get the trimmed (or the summary) version of the body that I configured in the Manage display tab of my content type.
For perfomance issue I don't want to use the node_load function on each of my nodes.
Is there a way that I can use a Drupal internal function that would help me to trim the body value?
Answer: You can get the trimmed summary using text_summary() which will allow you to pass the text, input format and choose the text size (length) you want.


Computing $\int_0^1\frac{1-2x}{2x^2-2x+1}\ln(x)\text{Li}_2(x)dx$

Question: Any idea how ot approach
$$I=\int_0^1\frac{1-2x}{2x^2-2x+1}\ln(x)\text{Li}_2(x)dx\ ?$$
I came across this integral while I was trying to find a different solution for $\Re\ \text{Li}_4(1+i)$ posted here.
here is how I came across it;
using the identity
$$\int_0^1\frac{\ln(x)\text{Li}_2(x)}{1-ax}dx=\frac{\text{Li}_2^2(a)}{2a}+3\frac{\text{Li}_4(a)}{a}-2\zeta(2)\frac{\text{Li}_2(a)}{a}$$
multiply both sides by $\frac{a}{3}$ then replace $a$ by $1+i$ and consider the the real parts of both sides we have
$$\Re\ \text{Li}_4(1+i)=-\frac16\Re\ \text{Li}_2^2(1+i)+\frac23\zeta(2)\Re\ \text{Li}_2(1+i)+\frac13\Re \int_0^1\frac{(1+i)}{1-(1+i)x}\ln(x)\text{Li}_2(x)dx$$
For the integral, use $\Re\frac{1+i}{1-(1+i)x}=\frac{1-2x}{2x^2-2x+1}$ which gives $I$.
What I tried is subbing $1-2x=y$ which gives
$$I=\int_{-1}^1\frac{-y}{1+y^2}\ln\left(\frac{1+y}{2}\right)\text{Li}_2\left(\frac{1+y}{2}\right)dy=\int_{-1}^1 f(y)dy=\underbrace{\int_{-1}^0 f(y)dy}_{y\to\ -y}+\int_{0}^1 f(y)dy$$
$$=\int_0^1\frac{y}{1+y^2}\ln\left(\frac{1-y}{2}\right)\text{Li}_2\left(\frac{1-y}{2}\right)dy-\int_0^1\frac{y}{1+y^2}\ln\left(\frac{1+y}{2}\right)\text{Li}_2\left(\frac{1+y}{2}\right)dy$$
I think I made it more complicated. Any help would be appriciated.
Comment: Shater: You're right but, anyway, for $a$ not real the formula holds
Comment: \begin{align}\int_0^1\frac{1-2x}{2x^2-2x+1}\ln(x)\text{Li}_2(x)dx=\frac{1}{2}\ln(x)\text{Li}_2(x)\left(\frac{1-i}{1-(1-i)x}+\frac{1+i}{1-(1+i)x}\right)\end{align} and the identity is true for $a$ complex not equal to $1$.
Comment: @FDP Cornel says the integral must be understood as a Cauchy principle value for a>1.
Comment: @FDP for the case a=0, we better use the limit as a approaches 0.
Comment: @FDP also note that for the case a>1 we need to consider the real part of the right hand side of the identity.
Comment: @FDP I agree with you
Answer: $$I=\int_0^1\frac{y}{1+y^2}\ln\left(\frac{1-y^2}{4}\right)\text{Li}_2\left(\frac{1-y}{2}\right)dy+\frac{7}{32} \zeta (3) \log (2)+\frac{ \text{Li}_4\left(\frac{1}{2}\right)}{8}-\frac{157 \pi ^4}{46080}-\frac{ 11\log ^4(2)}{48}+\frac{19}{384} \pi ^2 \log ^2(2)$$
 Put $$y=\frac{1-x}{1+x}$$
$$\int_0^1\frac{y}{1+y^2}\ln\left(\frac{1-y^2}{4}\right)\text{Li}_2\left(\frac{1-y}{2}\right)dy=\int_0^1\frac{\ln(x)}{1+x}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx-2\int_0^1\frac{\ln(1+x)}{1+x}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx-\int_0^1\frac{x\ln(x)}{1+x^2}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx+2\int_0^1\frac{x\ln(1+x)}{1+x^2}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx$$
be continued
$$\int_0^1\frac{\ln(1+x)}{1+x}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx=3\operatorname{Li}_4\left(\frac12\right)-\frac{\pi^4}{30}+\frac{21}8\ln2\zeta(3)-\frac{\pi^2}{12}\ln^22$$
$$\int_0^1\frac{x\ln(x)}{1+x^2}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx=\frac{C^2}{2}+\frac{15 \text{Li}_4\left(\frac{1}{2}\right)}{16}-\frac{701 \pi ^4}{46080}+\frac{7}8\ln2\zeta(3)+\frac{5 \log ^4(2)}{128}-\frac{3}{64} \pi ^2 \log ^2(2)$$
Comment: Combine the two integrals using the relation (3.4.5) of MHZ page 22
Answer: $$\int_0^1\frac{\ln(1+x)}{1+x}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx=3\operatorname{Li}_4\left(\frac12\right)-\frac{\pi^4}{30}+\frac{21}8\ln2\zeta(3)-\frac{\pi^2}{12}\ln^22$$
$$\int_0^1\frac{x\ln(x)}{1+x^2}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx=\frac{C^2}{2}+\frac{15 \text{Li}_4\left(\frac{1}{2}\right)}{16}-\frac{701 \pi ^4}{46080}+\frac{7}8\ln2\zeta(3)+\frac{5 \log ^4(2)}{128}-\frac{3}{64} \pi ^2 \log ^2(2)$$
Answer: $$\int_0^1\frac{\ln(x)}{1+x}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx=3\text{Li}_4(2)+\text{Li}_2(2)\log^22-3\text{Li}_3(2)\log2+6\operatorname{Li}_4\left(\frac12\right)+\frac{21}4\ln2\zeta(3)-\frac{\pi^2}{8}\log^22+\frac{1}{4}\log^42-\frac{29\pi^4}{288}$$
I being known,I deduce
 $$\int_0^1\frac{x\ln(1+x)}{1+x^2}\text{Li}_2\left(\frac{x}{1+x}\right)\ dx=-\frac{1}{16}\operatorname{Li}_4\left(\frac12\right)+\frac{21}{64}\ln2\zeta(3)-\frac{41}{768} \pi ^2 \log ^2(2)-\frac{1}{96}\log^42+\frac{1609\pi^4}{92160}-\frac{3}{2}\text{Li}_4(2)-\frac{1}{2}\text{Li}_2(2)\log^22+\frac{3}{2}\text{Li}_3(2)\log2$$
Sorry,i couldn't deduct this integral.
$$3\text{Li}_4(2)+\text{Li}_2(2)\log^22-3\text{Li}_3(2)\log2=-3\operatorname{Li}_4\left(\frac12\right)-\frac{21}8\ln2\zeta(3)-\frac{1}{8}\log^42+\frac{\pi^4}{15}$$
Answer: $$=\int_0^1\frac{y}{1+y^2}\ln\left(\frac{1-y}{2}\right)\text{Li}_2\left(\frac{1-y}{2}\right)dy=2\operatorname{Li}_4\left(\frac12\right)+\frac{133}{64}\ln2\zeta(3)-\frac{37}{768} \pi ^2 \log ^2(2)+\frac{77}{384}\log^42-\frac{3197\pi^4}{92160}-\frac{C^2}{2}-\frac{1}{8} \pi  C \log (2)+\frac{3}{2}\text{Li}_4(2)+\frac{1}{2}\text{Li}_2(2)\log^22-\frac{3}{2}\text{Li}_3(2)\log2$$
$$\int_0^1\frac{y}{1+y^2}\ln\left(\frac{1+y}{2}\right)\text{Li}_2\left(\frac{1+y}{2}\right)dy=\frac{47}{16}\operatorname{Li}_4\left(\frac12\right)+\frac{133}{64}\ln2\zeta(3)-\frac{61}{768} \pi ^2 \log ^2(2)+\frac{23}{96}\log^42-\frac{4367\pi^4}{92160}+\frac{1}{8} \pi  C \log (2)+\frac{3}{2}\text{Li}_4(2)+\frac{1}{2}\text{Li}_2(2)\log^22-\frac{3}{2}\text{Li}_3(2)\log2$$
Comment: I'm not sure how does this answer the question. OP clearly wants an idea how to approach the integral, not some results that should be on the comments section. Given the length I can understand why you posted an answer, but why 4 answers and not just 1 for all 4 that could be comments?
Comment: Very impressive! I'm also working on similar integrals.
Comment: @
I did the best I could, but in fact I made a mistake that I could not correct


Why below function returning me null instead of 1?

Question: I have written below function to process an array but It is not returning me 1 thought It's output $input[0] returning me 1. don't understand why It is return NULL. Anything I return in that condition is return me NULL. Please explain me if anyone know. Thanks.
function endWithNumber($input)
{
    if (count(array_unique($input)) === 1) {
        return $input[0];
    }
    $maxVal = max($input);
    $maxKey = array_search($maxVal,$input);

    foreach ($input as $k => $v) {
        if ($maxKey != $k && $maxVal != $v) {
            $newVal  = ($maxVal - $v);
            $input[$maxKey] = $newVal;
            break;
        }
    }

    endWithNumber($input);
}

$input = array(6,10,15);
var_dump(endWithNumber($input));
exit;

Comment: change `endWithNumber($input);` to `return endWithNumber($input);`
Comment: @Jimit The code says *"if [condition], `return` something, else never return anything"*. It doesn't matter that the function calls itself recursively, that logic is the same for all code.
Comment: Why are you using count with === ?
Comment: What is this code supposed to accomplish exactly? I'm sure there are much more elegant solutions to this.
Comment: @Yoshi, Thanks Yoshi!! You're right.. but can you tell me why it is working like that?
Comment: @Yoshi, I have already return values in condition if satisfied...
Answer: Your function returns nothing until your array count is 1. Because your return statement is in if block.
<?php
function endWithNumber($input)
{
    if (count(array_unique($input)) == 1)
        return $input[0];

    $maxVal = max($input);
    $maxKey = array_search($maxVal,$input);

    foreach ($input as $k => $v)
    {
        if ($maxKey != $k && $maxVal != $v)
        {
            $newVal  = ($maxVal - $v);
            $input[$maxKey] = $newVal;
            break;
        }
    }

    return endWithNumber($input);
}

$input = array(6,10,15);
var_dump(endWithNumber($input));

exit;
?>


Deleting abandoned questions

Question: Ref. Voucher generated code giving store credit/userpoints
User has not even visited the site (while logged in) > 6 months (I can see this with moderator interface). The one comment was never even responded to. Should these be deleted or just put on hold? I tend to skew away from removing content nodes, but wanted to check with others.
Comment: Isn't a question considered answered if it has one upvote? I would be more inclined to leave it open in case a future answer comes in.
Comment: *"Isn't a question considered answered if it has one upvote?"* Do you mean "if it has an answer with one upvote?" If so, yes.
Comment: Is there a possibility for moderators to accept answers for other users? In that referenced question, which is not completely useless as it asks whether a feature is implemented or possible, I feel that your answer could be marked as the answer. I prefer detailed and specific questions, but I understand that's not the case with most questions lately.
Comment: @musicliftsme - no, and that is by design. The OP gets to "accept" the answer which works for him/her, but literally everyone else gets to upvote the answers which work for them.
Comment: @benmarks, OK. I was just thinking of an alternative to abandon questions, to which the OPs will supposedly never come back.
Comment: Yeah, I wish this were an option, but I get Stack's perspective on it. They don't want to be the next expertsexchange ;-)
Answer: If there is a comment under which means "please add info, we can't help you" delete it.
Comment: Delete the question or the comment?
Comment: What I mean is: The question is only answerable with the answer of the comment. So if the comment is abandoned, and therefore the question not answerable, delete both
Comment: Okay, that's what I understood. I've been going through old unanswered questions and doing this so that we can cull them later
Answer: Is it a problem or bug, and is it reproducable? Keep it.
Is it a feature wish, or a wish for an howto? Keep it.
Generally I woult set the quality of the question regarding understandability as measurement here.
For the specific example, its understandable and a clearly defined featurewish, so it doesnt matter if abondoned.
Answer: In my opinion 'can I have feature X' questions should be deleted unless an answer is given that gives a good answer that is easily to implement for future Googlers.
If no answer is given it should probably deleted right away because it's unlikely it will ever be answered

Deleting abandoned questions


Java Swing: Action Event to submit multiple variables

Question: I'm creating an simple application that let's me search for an employee's information so far I can search for the first name but I want to add more variables to the search like Date of Birth, Address, Profession etc which is submitted by a single action event on a JButton.
How would I go about doing this? I've looked into using IF Else and Switch statement but I don't have a clue how to go forwards.
 private void searchActionPerformed(java.awt.event.ActionEvent evt) {
     String val1 = textFirstName.getText();

     try {
          String sql = "select * from employees where first_name = '"+val1+"'";
          stmt = con.createStatement();
          rs = stmt.executeQuery(sql);
          dataTable.setModel(DbUtils.resultSetToTableModel(rs));
        }

     catch ( SQLException err ) {
            JOptionPane.showMessageDialog(Appointments.this, err.getMessage());

   }

}

Comment: Please include a small amount of code to show your problem and ideally what have you tried.
Comment: ok have done, within the method i just want to be able to search multiple variables and be able to submit it with a single JButton.
Answer: What you could do would be to create a dynamic panel which would grow as users add more search options. Essentially, you would have an Add Search Term button which would add a new combo box and text field each time it is pressed (provided that, for instance, the last combo box in the list is not empty).
You would need to create a class of the sort:
public class SearchTerm {
    private int id;
    private String column;
    private String value;

    //Getters and setters and the rest.
    ...
}

Once that you create the combo box (which will contain all the fields which the users can search through) and text box, which will contain the text, you could add a new SearchTerm object to your list of search terms. The Id field would come in handy should you wish to allow users to remove and/or change existing search terms.
The next step would be to create a separate layer which essentially does the searching. This would make your UI layer contain UI functionality. The Single Responsibility pattern dictates that a class do only one thing. Currently, your class is responsible for UI and DB operations.
This new layer will have a method which takes in a List of SearchTerm items. From there you would construct your search query by iterating over the SearchTerm objects provided and their corresponding values. Once done, you could return a list of User objects which resemble the data in your database. All this would need to execute on a separate thread. You will need to look into background workers for this.
Some additional points:

Please make sure you use prepared statements instead of SQL concatenation. As is, your application is prone to SQL injection.
At the moment, you are performing your search operation on the Event Dispatcher Thread (EDT). This is not recommended since this thread is responsible for maintaining the UI. Thus, if you do any intensive operations on this thread, the UI will suffer (by becoming less responsive or plain freezing). Launching your search operation on a separate thread will ensure that the EDT will not be bogged down by non UI related operations. You could then update the UI from the background thread through the SwingUtilities.invokeLater mechanism.


Finding the Residue of a Holomorphic Function

Question: I'm trying to find the residue at $0$ of the function
$$f(z)=\frac{1+iz-e^{iz}}{z^3}$$
on $\mathbb{C} - \{0\}$.
I think it's a double pole at the origin, but I'm not entirely sure. I'm wondering if it's best to try and find the Laurent expansion of the function on a suitable annulus, or whether there's a neater trick to find the residue.
Thanks in advance.
Comment: $e^{i z} = 1+i z-\tfrac{z^2}{2} + O(z^3)$.
Answer: Wim's hint is huge: you can use MacClaurin's series for the exponential function and write $$\frac{1+iz-e^{iz}}{z^3}=\frac{1}{z^3}+\frac{i}{z^2}-\frac{1}{z^3}\left(1+iz+\frac{(iz)^2}{2!}+...\right)=\frac{1}{2z}+...$$


iOS: Access UIImageView placed in Interface Builder from code

Question: I've placed some images in my interface with Interface Builder and set them to be hidden on startup... Now I want to change the hidden attribute to FALSE, when I press a button, but I haven't tried accessing interface built images in my code before (not even sure if it is possible)...
Any help?
Comment: I'm sorry if i have completely misunderstood, but why not just use an IBOutlet to the UIImageView, or set its tag to like 10 and then call [(UIImageView *)[self.view viewWithTag:10] setHidden:NO];
Answer: Just create some IBOutlets in your code, connect them in Interface Builder and then use them in your code.
e.g.
<code>//in your header:

IBOutlet UIImageView *image;

// in your code (e.g. in the IBAction for the button):
- (IBAction)showImageNowFoo:(id)sender {
    [image setHidden:NO];
}
</code>
btw: FALSE is false. NO is Objective-C (although FALSE works..)
Comment: PS: if this really was your question you should consider reading a good cocoa / cocoa-touch book or tutorial.


How do I Insert Custom Cell into TableView Programmatically

Question: I am trying to insert my custom cells into my table view with data that is loaded from a web request, but the table insert script is running before the data is loaded which has me ending up with a blank table.
Currently my code is this and I have tested it to work with dummy data:
    public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        mainTableView.estimatedRowHeight = 50.0
        mainTableView.rowHeight = UITableViewAutomaticDimension
        var cell : postWithTitleAndImageTableViewCell = mainTableView.dequeueReusableCellWithIdentifier("postWithTitleAndImage") as postWithTitleAndImageTableViewCell
        let image = UIImage(named: "chainz on deck.jpg")
        var id = json[indexPath.row]["id"] as String
        var title = json[indexPath.row]["name"] as String
        var text = json[indexPath.row]["post"] as String
        var time = json[indexPath.row]["time"] as String
        var popularity = json[indexPath.row]["popularity"] as String
        //add clientid
        cell.setCell(id, title: title, image: image!, text: text, time: time, popularity: popularity)
        return cell as postWithTitleAndImageTableViewCell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)! Which the ID is: \(readIDs[indexPath.row])")
    }

    public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return json.count
    }

The code does exactly what it's supposed to, except the json variable is loaded from a web request and the table is trying to insert before the data is actually loaded. How should I fix this? Is there a way to call for a manual insertion of a custom cell, or is there a way to call the tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) function once the data is loaded? What should I do?
Comment: You need to show your JSON loading code, but basically you need to call `tableView.reloadData()` once the JSON is loaded
Comment: @Paulw11 `mainTable.reloadData()` works but the data only shows up once the table is moved. If you don't try and scroll in the table it stays blank. Is there and way to fix this?
Comment: You need to show the code where you are loading the data and calling reload, but chances are you aren't dispatching reloadData on the main queue
Answer: Using mainTable.reloadData() worked. Thanks @Paulw11


Exercício de implementação de lista sequencial

Question: Estou tentando resolver este exercício da faculdade no qual já implementei boa parte, porém falta ainda 3 coisas. É sobre estrutura de dados com Java OO - lista sequencial.
Segue o código da classe da lista:
public class ListaSequencial {
    private Contato [] contatos = new Contato[10];
    private int n = 0;

    boolean isVazia(){
        return n == 0;
    }

    boolean isCheia(){
        return n == contatos.length;
    }

    int tamanho(){
        return n;
    }

    private void deslocaDireita(int pos){
        for(int i = n; i > pos;i--){
            contatos[i] = contatos[i - 1];
        }
    }

    boolean inserir(Contato contato){
        if(isCheia()){
            return false;
        }

        contatos[n] = contato;
        n++;
        return true;

    }
    boolean inserir(Contato c, int pos){
        if(isCheia()){
            return false;
        }
        deslocaDireita(pos);
        contatos[pos] = c;
        n++;
        return true;
    }

    private void deslocaEsquerda(int pos){
        for(int i = pos; i < n - 1 ;i++){
            contatos[i] = contatos[i+1];
        }
    }

    boolean remover(int pos){

        if(pos < 0 || pos >=n){
            return false;
        }
        deslocaEsquerda(pos);
        n--;
        return true;
    }

    public String imprimir(){
        String str = "";
        if(isVazia()){
            return "lista vazia";
        }
        else{
            for(int i = 0; i < n; i++){
                str += contatos[i].nome + " - " + contatos[i].telefone + "\n";
            }
            return str;
        }
    }

    Contato buscar(int pos){
        if(pos < 0 || pos >= n){
            return null;
        }
        return contatos[pos];
    }

    int getPosicao(Contato contato){

        for(int i = 0; i < n; i++){
            if(contatos[i] == contato){
                return i;
            }
        }
        return -1;
    }
}

O que não sei fazer e preciso para o Exercício:

Preciso criar um método para concatenar 2 listas;
Preciso criar um método que assim que a lista encha, crie um container (vetor) maior fazendo com que ela nunca encha (tipo um laço);
Por fim, preciso de um método pra remover um elemento da lista passando ao invés do índice, o próprio elemento. No caso, que remova a primeira ocorrência encontrada.

Alguém me dê uma ajuda?
Comment: Olá. Seja bem-vindo ao SOPt. Está um pouco confuso. O que você não sabe? O algoritmo? Além disso, você tem muitas perguntas numa só. Faça o nosso [tour] e no guia de [como fazer uma boa pergunta](http://pt.stackoverflow.com/help/how-to-ask). Sinta-se à vontade para editar a pergunta acrescentando detalhes.
Comment: Bom reformulei a pergunta no fim para entenderem melhor, o algoritmo eu sei porém não sei fazer os 3 metodos que coloquei no final. ( O de concatenar, criar um metodo para que a lista assim que encher criar um vetor maior e Remover um elemento da lista passando o proprio elemento. A linguagem já sei varias coisas mas ao meu ver ainda sou iniciante e estou ''Aprendendo a força" estrutura de Dados.
Answer: (3) Este é o mais fácil. Faça o seguinte:

Crie o novo método para excluir o elemento, o retorno é boolean.
Percorra o array usando um for. Os elementos a serem percorridos são de 0 até < n.
Verifique dentro do seu for se aposição do array correspondente tem o elemento que você está procurando. Se tiver, use o remover(int) para remover esta posição e retorne true logo em seguida.
Para decidir se o elemento encontrado é o que você procura ou não, recomendo que utilize o método java.util.Objects.equals(Object a, Object b).
Se você terminar de percorrer o array e não encontrar o elemento, retorne false.

(2) Fazer a lista crescer é o mais complicadinho dos três. Faça o seguinte:

Faça o método isCheia() ser privado. O motivo disso é que do ponto de vista externo da classe, a lista nunca fica cheia, vez que quando ela encher, ela vai aumentar e não mais continuar cheia, e portanto este método já não faria mais sentido para quem está olhando a classe de fora.
Crie um método privado crescer(), que é responsável por fazer o array interno crescer de tamanho. Para isso você cria um array maior que o antigo, copia todos os elementos e troca a referência (contatos = novoArray;).
Ao invés de if (isCheia()) { return false; }, faça if (isCheia()) { crescer(); }.
Os métodos inserir passam a ter retorno void.

(1) Para criar o método que concatena duas listas faça isso:

Esse item é muito mais fácil se você tiver feito a parte 2 primeiro. Antes de implementar o item 1, faça o item 2.
Crie um método estático que receba como parâmetro as duas listas e retorne uma lista.
Este método cria uma lista nova. Percorre os lista1.n elementos da primeira lista e os adiciona na lista nova. Depois ele percorre os lista2.n elementos da segunda lista e faz a mesma coisa.
Retorne a nova lista criada.
Comment: @RomárioJúnior Sim, teria. Mas como isso é um exercício de faculdade para você aprender, acredito que a ideia seja você conseguir escrever o código você mesmo para garantir o aprendizado.
Comment: Amigo, não teria como postar em código ?
Comment: A idéia é essa mesmo, porém como é um Academico Virtual só tenho mais alguns minutos para fazer a postagem do restante do Exercicio e a Atividade fechar, tentei fazer alguma coisa mas ainda tenho dificuldade . Ajudaria muito se postasse .


How do i find the distance between a point and 2 equations, if Y is not known?

Question: If e: 2x+y+1=0; f: x+2y-3=0, determine p such that the distances from A(1,p) to the
lines e and f are equal.
I`m kinda lost, I know this is probably a 10th grade problem but I really need help.
Thanks in advance.
Comment: Do you know the distance formula from a point to a straight line? And how to solve 3 equations with 3 variables?
Comment: |Ax+Bx+C|/Sqrt(A**2 + B**2)
Answer: Let $P = (1, y)$, we want to determine $y$ such that the distances from $P$ to the line $2x + y + 1 = 0$ and the line $ x + 2 y - 3 = 0 $ are equal.
Set up the distances equation:
$ \dfrac{ | 2(1) + y + 1 | }{\sqrt{5}} = \dfrac{ | 1 + 2 y - 3 | }{\sqrt{5}}$
So we have to solve:
$ | 3 + y | = | 2 y - 2 | $
Squaring,
$ (3 + y)^2 = (2 y - 2)^2 $
$ y^2 + 6 y + 9 = 4 y^2 - 8 y + 4 $
$ 3 y^2 - 14 y - 5 = 0 $
$ (3 y  +  1)(y  -  5) = 0$
Hence the two solutions for $y$ are $ y = -\dfrac{1}{3} $ and $ y = 5$
Comment: Thats it thanks brother.
Comment: may i ask just one question though? Why did u square it?
Comment: @CDXX Because of the absolute value.
Comment: i looked it up u were of great help thank you


Using absolute value vs. variance in GARCH

Question: I'm interested in model a GARCH for a series. The original series is $y_t$ (price index of a stock market), which has a unit root. So I created the returns:
$x_t = \ln(y_t) - \ln(y_{t-1})$.
Now, I'm confused about the fact of using $\lvert x_t\rvert$ for my GARCH. Why can I use absolute value, I'm thinking, that because I want to model volatility I'm just interested in how the series deviates from its mean in a period of time?
Comment: series in singular is still series.
Comment: I was going through my old answers and noticed this one was not accepted. Do you perhaps need further clarification?
Answer: If $x_t$ is a series of logarithmic returns, the standard GARCH(1,1) model for it takes the form
$$
\begin{aligned}
x_t &= \sigma_t \varepsilon_t, \\
\sigma_t^2 &= \omega + \alpha_1 x_{t-1}^2 + \beta_1 \sigma_{t-1}^2,
\end{aligned}
$$
where $\varepsilon_t$ is $i.i.d.(0,1)$ random variable. (It is straightforward to extend the model order to obtain GARCH($p$,$q$).) If you care about the volatility (measured by standard deviation or variance) of the returns, no absolute values get involved.
A GARCH model that involves absolute values is absolute value GARCH (AVGARCH or TS-GARCH) due to Taylor and Schwert (Bollerslev, 2009, p. 30)  and is formulated as follows:
$$
\begin{aligned}
x_t &= \sigma_t \varepsilon_t, \\
\sigma_t &= \omega + \alpha_1 |x_{t-1}| + \beta_1 \sigma_{t-1}.
\end{aligned}
$$
The model is less sensitive to large errors as compared to the regular GARCH model.
References

Bollerslev, Tim. "Glossary to ARCH (GARCH)." Volatility and Time Series Econometrics: Essays in Honour of Robert F. Engle. 2009.


Why doesn't my jQuery accordion menu stick?

Question: When a user clicks the Accordion Menu button it usually works. But, about 1 out of 10 times the animation doesn't stick and goes back to either expanded or collapsed, depending on what state it started at. I've copied the scripts from other places, but they seem simple enough.
HTML:

Umbrella

Admin

Dashboard

Daylight

Like I've said, I've tried several different versions of the same thing. These were just taken from random places and I've only edited them slightly. All of them do the same thing.
$("#system-nav > li > div").click(function(){
if(false == $(this).next().is(':visible')) {
    $('#system-nav ul').slideUp(300);
}

$(this).next().slideToggle(300).delay(250);
});

$('#system-nav ul:eq(0)').hide();

$(document).ready(function() {
$('#system-nav li div').click(function() {
    $('#system-nav ul').slideUp('slow');
    $(this).next().slideDown('slow');
});

$("#system-nav ul").hide();

 });

$(document).ready(function(){
$('#system-nav li div').click(function() {
    $(this).next().slideDown('slow');
    return false;
}).next().hide();
});

Comment: The only thing I can think of is to be more specific with your selectors in the next() functions.  Perhaps there is an overlap somewhere?
Answer: In the first JS sample using :visible is not the right proprety. Use :hidden instead
In the second one you're cliping it ?
In the last one you're canceling it ?

Here's a working code: http://jsfiddle.net/Q9qNw/
$("#system-nav").on("click","div",function(){
    if ($(this).next().is(":hidden")) {
        $(this).next().slideDown("500");
    } else {
        $(this).next().slideUp("500");
    }
});


Bypassing drupal cache in template file

Question: is there a way i can bypass the drupal cache for a specific element on my website?
in my case i've got 3 header graphics which should be displayed at a random order on every page load.
Answer: The entire page is being cached, so you'll want to disable caching on those pages that have dynamic elements. I think you'd want to:
a) turn OFF page caching for the needed paths (http://drupal.org/project/cacheexclude)
b) turn ON caching for any Views, blocks, or whatever else you can cache on those pages to save bandwidth
Then you'll have more granular caching control.
Answer: Using ESI, JavaScript or setting the image to a php file is how to get around the caching issue.
http://drupal.org/project/esi_api
http://drupal.org/project/esi
http://drupal.org/project/ajaxify_regions
http://drupal.org/project/ajaxblocks
http://drupal.org/project/views_javascript_random
http://www.alistapart.com/articles/randomizer

Bypassing drupal cache in template file


How to create a conda environment shortcut on Windows

Question: With Anaconda installed I got a anaconda base shortcut on Windows startmanu. To open the virtualenv I created (e.g., myenv), I have to click the anaconda base and type in activate myenv in the opened cmd window.
How can I create a shortcut to get to myenv with one-click, without open-and-typing like the above?
I've tried to create a copy of the base shortcut and change its command property i.e., %windir%\System32\cmd.exe "/K" C:\Programs\anaconda3\Scripts\activate.bat C:\Programs\anaconda3\envs\myenv. It does open the myenv cmdline, but seemed lost some buildin command,like conda.
I guess I need a little bit help on Windows bat skills.
Comment: I think you may have your quoting wrong, `%WinDir%\System32\cmd.exe /K "C:\Programs\anaconda3\Scripts\activate.bat C:\Programs\anaconda3\envs\myenv"`. Type `cmd /?` at the prompt for the usage help on that particular command.
Comment: @Compo, using your version I got the same results, i.e., myenv opened,but some commands(e.g., `conda`) are not in the environment. ;-(
Comment: I only provided a fix to your incorrect quoting, not an answer to your question, _which would have been provided in the answer area, not the comment area_. It was only so because you have not provided sufficient information in your question area for me to confidently provide an answer.
Comment: Well the answer would be in the batch file itself.
Comment: Since I also use `git-bash`, I found I can put `source /c/.../activate /c/.../myenv` into my `.bashrc` file. After that when I launch `git-bash`, it goes into myenv and works fine!  I'll go with  `git-bash` now.
Comment: It's funny that you can create a shortcut to the base environment with `%windir%\system32\cmd.exe "/K" C:\appl\Anaconda3\Scripts\activate.bat base` and that will have conda.exe in the path and if you `conda activate myenv` from there conda.exe will remain in the PATH. But if you try to directly activate the `myenv` it won't have access to conda.exe
Answer: putting the comments above together in a simple batch script works flawlessly:
@echo off
set PATH=%PATH%;C:\ProgramData\Anaconda3\Scripts
%windir%\system32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat <env-name>

Comment: Beautiful! Adding a `cd /d e:\my-working-dir` before the last line make it totally perfect. Thanks man.
Comment: This isn't a "shortcut"
Comment: Create a shortcut to cmd, set Target to %windir%\system32\cmd.exe "/K" %USERPROFILE%\Miniconda3\Scripts\activate.bat base (I use Miniconda3).  Double click to open a cmd prompt w/the env already activated.
Answer: The following works for me.  The only change is that the parameter to activate.bat is simply the env name (not the full path) as you would normally type it after an activate command.  Your quotes were fine, BTW.  For instance:
%windir%\system32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat myenv

Comment: This activates the environment, yes, but the conda.exe will not not be there (unless you already added C:\ProgramData\Anaconda3\Scripts to you global PATH which is not the recommended option when installing Anaconda
Comment: `conda.bat` which is called by `activate.bat` already takes care of the PATH.
Answer: For miniconda it's:
@echo off
set PATH=%PATH%;C:\ProgramData\miniconda3\Scripts
%windir%\system32\cmd.exe "/K" C:\ProgramData\miniconda3\Scripts\activate.bat video

Was gonna leave it as a comment on Jonathan's, but I'm new ><.
Answer: Mine automatically created a shortcut for Spyder with this format:
C:\Anaconda3\pythonw.exe C:\Anaconda3\cwp.py C:\Anaconda3\envs\py36 C:\Anaconda3\envs\py36\pythonw.exe C:\Anaconda3\envs\py36\Scripts\spyder-script.py

Comment: this requires short paths, as the full string must fit within 259 characters.
Comment: This is a great option for non command line apps. I just used is as `C:\Miniconda3\pythonw.exe C:\Miniconda3\cwp.py C:\Miniconda3\envs\env0 app.exe` . Replace env0 and app.exe with your respective values and no cmd.exe will be shown
Answer: Before creating new environment you can specify:
conda config --set shortcuts true

After that, you can see shortcuts for your new environment.
Answer: I use ConEmu terminal, with traditional cmd.exe shell. Here's what my shortcut to MiniConda3 looks like:
C:\Users\nmz787\Downloads\conemu_22_08_07\ConEmu64.exe -run  {Shells::cmd} & C:\Users\nmz787\Miniconda3\condabin\conda.bat activate
Answer: You can get around this by installing  the conda package into the environment that you want to activate.
From an Anaconda Prompt (from where conda is already accessible):
conda install -n myenv conda

Then you can create a windows shortcut with target %windir%\system32\cmd.exe "/K" C:\appl\Anaconda3\Scripts\activate.bat myenv
This is suboptimal as it pollutes your environment with the conda dependencies, and I wouldn't recommend it.
The other alternative is to add the C:\Anaconda3\Scripts directory to the PATH environment variable.


Como criar um parâmetro opcional em ADVPL?

Question: Em diversas funções documentadas pela Totvs há parâmetros opcionais. Gostaria de criar um parâmetro opcional em minha função, como fazer?
Estou querendo fazer com que a função updEnvio receba um vetor (de recnos) como parâmetro opcional.
User Function updEnvio(cTabela)
    Local cSQL := ""
    Local cCampo := IIF(SUBS(cTabela,1,1)=='S', SUBS(cTabela,2,2), cTabela)
    Local nStatus := 0

    cSQL := ""
    cSQL += " UPDATE " + RetSqlName(cTabela)
    cSQL += " SET " + cCampo + "_YGSENV = 'S' "
    cSQL += " WHERE 1=1 "
    cSQL += " AND " + cCampo + "_FILIAL = '" + xFilial(cTabela) + "' "
    cSQL += " AND " + cCampo + "_YGSENV <> 'S' "

    nStatus := TcSqlExec(cSQL)

    If (nStatus < 0)
        conout("Oops, TCSQLError: " + TCSQLError())
    Endif
Return

A grosso modo, queria transformá-la de modo que, se o vetor estivesse vazio, ela atualizasse toda a tabela; porém, se tivesse conteúdo, apenas os elementos cujos recnos estejam descritos nesse vetor. Usando a lógica C++ de ser, eu escreveria o valor padrão do parâmetro em sua declaração. Então, meu pseudocódigo ADVPL fica assim:
User Function updEnvio(cTabela, aRecnos := {})
    Local cSQL := ""
    Local cCampo := IIF(SUBS(cTabela,1,1)=='S', SUBS(cTabela,2,2), cTabela)
    Local nStatus := 0
    Local i

    cSQL := ""
    cSQL += " UPDATE " + RetSqlName(cTabela)
    cSQL += " SET " + cCampo + "_YGSENV = 'S' "
    cSQL += " WHERE 1=1 "
    cSQL += " AND " + cCampo + "_FILIAL = '" + xFilial(cTabela) + "' "
    cSQL += " AND " + cCampo + "_YGSENV <> 'S' "

    If LEN(aRecnos) > 0
      cSql += " AND R_E_C_N_O_ IN ("
      cSql += STR(aRecnos[1])
      For i := 2 to len(aRecnos)
        cSql += "," + STR(aRecnos[i])
      Next i
      cSql += ")"
    Endif

    nStatus := TcSqlExec(cSQL)

    If (nStatus < 0)
        conout("Oops, TCSQLError: " + TCSQLError())
    Endif
Return

Answer: Antes vamos adotar uma nomenclatura correta: Qual a diferença entre parâmetro e argumento?. Parâmetro nunca são opcionais, ou eles existem ou não existem, não é como em JavaScript. Argumentos podem ser opcionais. E o que quer saber é se os parâmetros podem ter seus valores inicializados se o argumento referente a ele não for a passado.
Não é possível com esta sintaxe, a linguagem não dá suporte ao que deseja na pergunta. Ela tem um truque para facilitar o que deseja (por sinal foi eu que criei isso nela em 1994 e até hoje é da mesma forma, um recursos de include) usando default.
User Function updEnvio(cTabela, aRecnos)
    Local cSQL := ""
    Local cCampo := IIF(SUBS(cTabela,1,1)=='S', SUBS(cTabela,2,2), cTabela)
    Local nStatus := 0
    Local i
    Default aRecnos := {}

    cSQL := ""
    cSQL += " UPDATE " + RetSqlName(cTabela)
    cSQL += " SET " + cCampo + "_YGSENV = 'S' "
    cSQL += " WHERE 1=1 "
    cSQL += " AND " + cCampo + "_FILIAL = '" + xFilial(cTabela) + "' "
    cSQL += " AND " + cCampo + "_YGSENV <> 'S' "

    If LEN(aRecnos) > 0
      cSql += " AND R_E_C_N_O_ IN ("
      cSql += STR(aRecnos[1])
      For i := 2 to len(aRecnos)
        cSql += "," + STR(aRecnos[i])
      Next i
      cSql += ")"
    Endif

    nStatus := TcSqlExec(cSQL)

    If (nStatus < 0)
        conout("Oops, TCSQLError: " + TCSQLError())
    Endif
Return

Coloquei no GitHub para referência futura.
Com o default o valor só será atribuído se não vier nada como parâmetro. Ou seja, pegaram o que eu criei e transformaram em sintaxe oficial, quando na verdade tinha uma sintaxe óbvia melhor quando resolveram colocar na linguagem.
Como curiosidade abra o arquivo protheus.ch que você tem acesso para fazer personalização e procure o trecho (pra não falar que é idêntico ao que eu fiz, eu usava Iif() sempre para não confundir visualmente com um comando If com parênteses):
#xcommand DEFAULT <uVar1> := <uVal1> ;
      [, <uVarN> := <uValN> ] => ;
    <uVar1> := If( <uVar1> == nil, <uVal1>, <uVar1> ) ;;
   [ <uVarN> := If( <uVarN> == nil, <uValN>, <uVarN> ); ]

Uma curiosidade que poucos sabem é que dá pra usar o pré-processador, que é bem mais poderoso que o de C, e criar argumentos nomeados, que acabam sendo até mais úteis porque em essência a linguagem não trabalha com objetos (tem uma implementação muito ruim e ineficiente, então evita-se o uso).
Comment: @JeffersonQuesado editei, de fato ainda é o que eu tinha criado :D
Comment: Quando o workaround vira sintaxe oficial
Answer: Em ADVPL os parâmetros de uma função são opcionais. Parâmetros não fornecidos vêm com valor nil.
Exemplo:
#include "protheus.ch"

user function test(xParm)
  if xParm != nil
    conout("xParm=" + xParm)
  else
    conout("nao recebeu parametros!")
  end if

  return

That's it.


how to connect database using mysqli keyword

Question: I'm new in PHP  and follow this tutorial connect php webservices to android below is my code  i change MySQL to MySQLi  everywhere  but still its show error:

    <?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="emp_info"; //replace with database name

$con=mysqli_connect("$host", "$username", "$password")or die("cannot
  connect");
mysqli_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info";
$result = mysqli_query($sql);
$json = array();

if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysqli_close($con);
echo json_encode($json);
 ?>

Comment: the tutorial's pretty crappy. you'll find that probably 95%+ of php tutorials on the web are outdated, badly written, full of security vulnerabilities, or just plain wrong. there's a LOT of crap out there.
Comment: Oh, and this `$result = mysqli_query($sql);` is also failing you. RTFM http://php.net/manual/en/mysqli.query.php as a wise man once said ;-)
Comment: `mysqli_select_db` that takes 2 parameters. Please read the manual. Now, using http://php.net/manual/en/mysqli.error.php  would have told you about it.
Comment: There is literally no point to write `"$username"` in your code when `$username` will do. It would be in your best interest to shed these awful habits.
Comment: i just simple copy paste the tutorial code     http://codeoncloud.blogspot.com/2013/07/android-mysql-php-json-tutorial.html
Comment: Couldn't agree with you more there Marc - @MarcB
Answer: There are two solution, first use the 4th argument in mysqli_connect().
Like this:
$con=mysqli_connect($host, $username, $password, $db_name)

Second, you need pass the connection in mysqli_select_db()
$con=mysqli_connect($host, $username, $password);
mysqli_select_db($con, $db_name);

Almost all function in MySQLi needed the conection at first argument, so mysqli_query() need the connection too.
$con=mysqli_connect($host, $username, $password, $db_name)or die("cannot connect");

$sql = "select * from emp_info";
$result = mysqli_query($con, $sql); //<--- here query need the connection

Comment: You missed something there Ray.
Comment: @Fred-ii- what i missed?
Comment: Look at the OP's code again very carefully. Comments up there should give you a clue ;-)
Comment: rray i did what u say but its still show error
Comment: ( ! ) Catchable fatal error: Object of class mysqli could not be converted to string in C:\wamp\www\samplejson.php on line 8
Comment: @Fred-ii- thx for the notice, i think is fixed now.
Comment: @syedahmed i think you are print something wrong not an array.
Comment: its work  thnx you rray


Failure of free()

Question: If I'm allocating memory in a loop like so
for(file = 0; file < nfile; file++){
...
...
...
   for(yy = 0; yy < ngridy; yy++){
      for(xx = 0; xx < ngridx; xx++) {
         tmparr1[xx+(ngridx*yy)] = (double *)calloc(nptperf[file], sizeof(double));
         tmparr2[xx+(ngridx*yy)] = (double *)calloc(nptperf[file], sizeof(double));
      }
   }

Sometime later in the code I'm freeing memory like so :
for(yy = 0; yy < ngridy; yy++){
    for(xx = 0; xx < ngridx; xx++) {
       free(tmparr1[xx+(ngridx*yy)]);
       free(tmparr2[xx+(ngridx*yy)]);
    }
}

Would there be a possibility of free() not freeing the memory and hence causing a whole lot more memory to be allocated?
I'm allocating and freeing the memory once every file loop. Also, nptperf[file] is usually around 1-3 million points, and ngridx = ngridy = 100.
This program works for ngridx = ngridy = 80 and less, but fails at 100.
Comment: First compile your program in debug mode using --ggdb option of gcc then  use `valgrind --leak-check=full --show-reachable=yes ./programname`  to find the critical points where you are leaking memory
Comment: free takes a void *ptr as argument and you are passing an array?
Comment: @BhavikShah - Yeah... tmparr1 is defined as `double **tmparr1` so I'm passing an array to free.
Answer: You are using wrong variables inside the bodies of your loops (gg and ggy instead of xx and yy). Among other problems, this causes (almost) all of the allocated memory to be leaked since you're losing the calloc()ed pointers.
Comment: To be honest, I don't see how 50x50x4,000,000 doubles can fit in 16+32GB. If you'd like to figure it out, I'd suggest producing a small self-contained runnable example, and posting it as a separate question along with your observations.
Comment: I've changed it, still get the same problem! Thanks for pointing that out. Can't believe I missed it.
Comment: @Kitchi: 3 million points on a 100x100 grid will require almost half a terabyte of memory for the two arrays. Does your box have enough RAM/swap?
Comment: That's what I figured... but I wanted to make sure that it wasn't a memory leak either. I've only got 50 GB combined memory+swap. So every time I run it, my process is `killed` by linux.
Comment: I just noticed something - even when my program works (with `ngridx = ngridy = 50`, I need some `74 GB` of space to allocate ~4 million double precision numbers on my `50x50` grid. But my physical ram is only `16GB` and if I monitor the memory usage, it peaks only at about `60%` or so. I'm very confused about why my program is running.
Comment: How much swap space do you have?
Comment: `32 GB`. But I thought that swap was only accessed when the RAM was full?
Answer: There are two possibilities:

free() can fail meaning you don't free the memory you used (your question)
your program has a bug and you don't free the memory you used, you are leaking memory.

The first is unlikely to happen, I don't know of any circumstances where free() fails if used properly. If it is passed the proper pointer, that memory will be freed, if it is passed NULL, it will do nothing.
The second is more likely to happen, but in the above snippet it looks ok. As mentioned above you can use Valgrind (/ˈvælɡrɪnd/) to check if something is going wrong. Compile with -O0 -ggdb and have Valgrind check the allocation and deallocation.
Answer: Run a tool like Valgrind with your program and see if you are leaking any memory. From the code you have posted, it does not look like you are leaking memory. But using Valgrind will confirm that and also it can point out other problems which may exist.
Answer: It is possible that the program may be running out of memory, calloc returning a null, ensued by memory corruption and finally getting killed.
I would suggest checking for the return value from calloc instead of assuming that it succeeded.
If the program needs a lot memory, make sure there is enough swap space to handle the requirements.  Remember that there are possibly other apps running on the system as well.
The other option is to divide and conquer.  One possibility is to turn it into a distributed application running on multiple machines. Without knowing what the rest of the application does, this may or may not be feasible.

Failure of free()


Bokeh plots distorting nbviewer slides view

Question: When using the web based iPython Notebook/Jupyter capability, i created a notebook with markdown cells of text and code cells to display the code and plots for matplotlib and bokeh. I then download that as .ipynb open with sublime, copy and paste to git, then access it on nbviewer through my git account. When looking at it here:
http://nbviewer.ipython.org/github/angisgrate/test/blob/master/pyohio3.ipynb
in notebook view, it works fine. the markdown, code, and plot steps are all there.
When switching to slides view, the intent of the creation needed for the presentation, this code blocks occurs first, blocking out the first 10 markdown steps and all the matplotlib steps, rendering this weird code without the plots:
http://nbviewer.ipython.org/format/slides/github/angisgrate/test/blob/master/pyohio3.ipynb
How can i fix this asap?? I've looked through and there was a similar problem in 2014 with slides, but it yielded an actual "Error" that i'm not seeing, just this contorted view
Answer: I can't say for certain. It's possible in the nbviewer slides view, the execution of JavaScript is suppressed (this happens on GitHub notebook previews, for instance). All of the rendering in Bokeh actually happens from the JavaScript library BokehJS, so if this is the case, then Bokeh will not function, and there is nothing really that can be done. This is probably a question bset directed towards the nbviewer team/community to find out the specifics of how the slides view behaves (and is intended to behave) with respect to executing embedded JavaScript.
Edit: Looks like this is a known/discussed issue. More information here:  Issue #484: Jupyter>>nbviewer slides Fail, notebook view fine by angisgrate in jupyter/nbviewer on GitHub
Comment: https://github.com/jupyter/nbviewer/issues/484 Yup I created that issue and it is still open. They are working on it. Thank you


Projective surface has an ample divisor

Question: Let $S$ be a projective surface. In https://mathoverflow.net/questions/63999/nef-divisor-on-surface, there is an argument proving that any nef divisor $D$ on $S$ has $D^2\geq 0$. But the argument implicitly assumes that $S$ has an ample divisor. Is it true that any projective surface has an ample divisor?
Answer: Yes: saying $S$ is projective means it admits a closed embedding in to $\Bbb P^n$. Then $S$ has a very ample divisor (pull back $\mathcal{O}_{\Bbb P^n}(1)$ along the closed embedding) and thus an ample divisor. See for instance 01VT, Hartshorne theorem II.7.6, or Vakil 17.3.9 on the interaction between very ample and ample.

Projective surface has an ample divisor


Os valores de output estão saindo sem espaço

Question: Tenho o seguinte problema para resolver:

Criptografia (em grego: kryptós, "escondido", e gráphein, "escrita") é o estudo dos princípios e técnicas pelas quais a informação pode ser transformada da sua forma original para outra ilegível, de forma que possa ser conhecida apenas por seu destinatário (detentor da "chave secreta"), o que a torna difícil de ser lida por alguém não autorizado (Wikipédia).
Uma das técnicas simples de criptografia é o da cifra de substituição, que é composto de:
Alfabeto normal;
Alfabeto para a cifragem;
A mensagem cifrada
Como resultado do processo de descriptografia temos a mensagem original.
  Implemente, então, um programa que dados estes 3 componentes retorne a mensagem original. Cada um destes componentes está numa linha distinta.

Para resolver o problema, codifiquei o seguinte algoritmo:
def descriptografar_texto(alfabeto_normal,alfabeto_cifrado,mensagem):
    dic = {}
    alfa_norm = list(alfabeto_normal)
    alfa_cifr = list(alfabeto_cifrado)
    frase = ''
    for letra1,letra2 in zip(alfa_cifr,alfa_norm):
        dic[letra1] = letra2
    for letra in mensagem:
        if letra in dic:
            frase += dic.get(letra)
    return frase

a = input()
b = input()
c = input()

print(descriptografar_texto(a,b,c))

A saída desejada é uma frase, entretanto, a minha saída está saindo sem espaços entre as palavras.
Como posso corrigir isso?
Comment: A postagem foi arrumada.
Answer: Adicionei um else para quando a letra não estiver no dicionário ele colocar um espaço.
if letra in dic:
                frase += dic.get(letra)
            else:
                frase += " "

Segue o código completo:
def descriptografar_texto(alfabeto_normal,alfabeto_cifrado,mensagem):

    dic = {}
    alfa_norm = list(alfabeto_normal)
    alfa_cifr = list(alfabeto_cifrado)
    frase = ''
    for letra1,letra2 in zip(alfa_cifr,alfa_norm):
        dic[letra1] = letra2
    for letra in mensagem:
        if letra in dic:
            frase += dic.get(letra)
        else:
            frase += " "

    return frase

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

b = ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']

c = "mlhhz jfv olfxfiz"

print(descriptografar_texto(a,b,c))

Saída:
nossa que loucura
Comment: Note que eu coloquei o alfabeto minúsculo então se você digitar uma letra maiúscula será exibido um espaço. O mesmo acontece para números e caracteres especiais. Para corrigir isto as listas `a` e `b` precisam ser atualizadas.
Comment: Obrigada! Funcionou perfeitamente.
Comment: Que ótimo, fico muito feliz em te ajudar. Abraço e até a próxima!


Nginx subversion commit failure

Question: Hi I have trouble in committing php scripts to subverison. I am using Nginx web server to send request to apache server using mod_proxy setting of nginx for commiting files, svn checkout and updates works fine.

server {
        listen  80;
        server_name svn.server;
        location / {
        access_log off;
        proxy_pass http://localhost:8081;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

       location  ~ ^/repos/.*.php$  {

                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
        }

}
Comment: Please provide more information.  What error are you getting?
Answer: The problem is that location block with the fastcgi setup for PHP.  When SVN goes to commit it does a PUT to a URI that ends in the filename for the file e.g.
PUT /svn-test-work/repositories/authz_tests-7/!svn/txr/1-1/A/D/G/rho
Where the path inside the repo is /A/D/G/rho.
The reason you're not seeing a problem with update and checkout is you're probably using a client or server that is still using bulk updates.  Bulk updates mean rather than making a HTTP GET request for the file all the contents are included in a REPORT request.  Newer clients will make a GET request and will see problems with checkout and update as well.
I'd guess the php fastcgi setup is for some sort of web based UI for your SVN server.  You need to place that on a unique URL rather than under the same URL as your repositories.

Nginx subversion commit failure


In survival analysis, can the last follow up date be with a different specialty

Question: I'm interested in collecting the date follow up for patients with cancer of the uterus. it's retrospective chart review. Can the date of last follow up include visits to different specialties or it has to do with the same specialty (to answer the question whether disease recurrence occurred or not)?
Comment: Welcome to the site! This is way to specific to your field for us simple statisticians to be able to comment as is. Could you help us understand what different specialties are, and why they would influence the follow ups, and why the last one more than others in general terms?
Answer: The answer depends on what you are using for the events of interest.
In survival analysis, death is often taken to be an event (overall survival). In that case, being alive at any follow up indicates that the event hadn't occurred by that date. You can use the date of last follow up to get a lower limit to overall survival duration (a right-censored survival time), regardless of the observing clinician. So you should be transcribing dates of all follow up visits, for overall survival at least.
If cancer recurrence is the event, then you have to apply your understanding of the subject matter, as John Madden indicated in a comment.
Evaluating time to cancer recurrence is tricky enough in the best of studies. The cancer was presumably present in clinically undetectable form since the original therapy, so "recurrence" is just when the remaining cancer grew large enough to become detectable. That depends on the methods used to detect recurrence. A gynecologic oncologist would presumably look harder and use more sophisticated methods to evaluate recurrence in a patient who had previous uterine cancer. A dermatologist treating the same patient would assume that the oncologist was evaluating the patient for cancer recurrence, and not pursue the cancer issue beyond making sure there weren't any overt signs of trouble.
To resolve those issues, discuss with your colleagues on the project and decide among yourselves how you should proceed. In the process, think about how you would justify your decision to a skeptical audience.
The timing of cancer recurrence has an additional, statistical, problem arising from the intervals between follow-up visits. If a patient returns for follow up every 6 months, has no recurrence at one visit, but has recurrence at the next visit, what do you choose for the time of recurrence? It happened sometime during that 6-month window, but you don't know when. That is best handled as an "interval-censored" time to recurrence. In practice, the recurrence date is nevertheless often taken to be the date of the follow-up visit where the recurrence was first seen. That imposes a bias toward longer times to recurrence.
Answer: Nobody except an oncologist or a radiologist can say if the cancer has progressed, so no it would not make sense to consider a visit to primary care physician as a scan timepoint to calculate the last known non-progressive disease date for progression free survival in subjects who are censored. You can say that they didn't die, for sure, but PFS is a composite endpoint. The OS follow-up time is usually quite a bit longer than PFS follow-up time for that reason.


Visual Studio won't run .NET 4 application

Question: I changed the target framework of a WPF application to use .NET 4 and now Visual Studio refuses to run it when I press F5. There are no errors, nothing in the build window, it just does nothing.
If I run it manually outside Visual Studio, it runs. If I change it back to .NET 3.5, it runs.
I tried running with logging enabled, but the log didn't have anything debugging-related. But here it is anyway. Anything else I should try?
Comment: Did you change the target framework to ".NET Framework 4" or ".NET Framework 4 Client Profile"?
Comment: Do you see anything in the Output window?
Answer: A system restart fixed it. Weird.


Alter add to cart message

Question: How to alter the message shown - "xyz" added to your cart, when we add an item to cart in Drupal 8 Commerce 2x.
I saw Drupal\commerce_cart\EventSubscriber where the function displayAddToCartMessage(CartEntityAddEvent $event) is written which is responsible for showing the message, is there any method to override it.
Answer: Install the Commerce Extended Quantity module and then implement a HOOK_xquantity_add_to_cart_qty_prices_msg_alter():
https://github.com/drugan/commerce_xquantity#an-item-added-to-your-cart-message-alter

Alter add to cart message


How to set up local ntp server without internet access on ubuntu?

Question: I have tried several guides on how to set up a local ntp server on ubuntu but none seem to work correctly. My servers are drifting heavily in time for some reason and I have to keep their time close together because I run databases that require this.

I have 8 ubuntu 14.04 LTS servers, none of them has internet access
I want to run a ntp server on one (or more if that is better) of the servers and have all other servers connect to the ntp server(s) to set the time

Currently, my server (ip .24) runs this /etc/ntp.conf:
server 127.127.1.0 prefer
fudge  127.127.1.0 stratum 10
driftfile /var/lib/ntp/drift
broadcastdelay 0.008

# Give localhost full access rights
restrict 127.0.0.1

# Give machines on our network access to query us
restrict 192.168.178.0 mask 255.255.255.0 nomodify notrap

broadcast 192.168.178.0

And on the "clients":
# Point to our network's master time server
server 192.168.178.24 iburst
fudge 192.168.178.24  stratum 10

restrict default ignore
restrict ::1
restrict 127.0.0.1
restrict 192.168.178.24 mask 255.255.255.255 nomodify notrap noquery

driftfile /var/lib/ntp/drift

minpoll 4
maxpoll 5

Note: I have used Multi-Tabbed Putty to send the following commands to all ntp clients at the same time.
I have stopped the ntp services for all except the server, used sudo ntpdate 192.168.178.24 to let them fetch the date and restarted the ntp services afterwards. This succeeded. All servers showed the same date straight after the command finished. After about 10 minutes however, my servers show the following time:
Fr 30. Sep 11:16:53 CEST 2016
Fr 30. Sep 11:15:33 CEST 2016 (server .24)
Fr 30. Sep 11:16:50 CEST 2016
Fr 30. Sep 11:15:33 CEST 2016
Fr 30. Sep 11:17:05 CEST 2016
Fr 30. Sep 11:15:33 CEST 2016
Fr 30. Sep 11:15:33 CEST 2016
Fr 30. Sep 11:15:33 CEST 2016

How to have them properly sync to the ntp server? And how can I lower the polling time? It looks like my servers are running out of sync fast so I need them to retrieve the "correct" time again...
With "correct" time I mean a time that is the same for all servers. It does not necessarily need to be the exact correct world time (if you call it like that).

Edit:
I have tried the suggested configuration setting. As far as I understood, this is how my server/client configs should look like. In the meantime, I have seen that my .24 server is actually drifting to a worse time. The .20 server is the most accurate one and I am using the .20 server now to host the ntp server. Sorry for the confusion.
Server config:
# Use the local clock
server 127.127.1.0 prefer
fudge  127.127.1.0
driftfile /var/lib/ntp/drift
broadcastdelay 0.008

# Give localhost full access rights
restrict default

# Give machines on our network access to query us
restrict 192.168.178.0 mask 255.255.255.0 nomodify notrap

broadcast 192.168.178.0

For the clients:
# Point to our network's master time server
server 192.168.178.20 iburst

restrict default

driftfile /var/lib/ntp/drift

minpoll 4
maxpoll 5

ntpq -as and ntpq -pe on the server:
ntpq -c as
ind assid status  conf reach auth condition  last_event cnt
===========================================================
  1 41906  963a   yes   yes  none  sys.peer    sys_peer  3
  2 41907  8811   yes  none  none    reject    mobilize  1

ntpq -c pe
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*LOCAL(0)        .LOCL.           5 l   60   64  377    0.000    0.000   0.000
 192.168.178.0   .BCST.          16 u    -   64    0    0.000    0.000   0.000

Five times similar output like this (these servers drift in time):
ntpq -c as
ind assid status  conf reach auth condition  last_event cnt
===========================================================
  1 62104  9024   yes   yes  none    reject   reachable  2

ntpq -c pe
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 hadoop20.xx LOCAL(0)         6 u   27   64  377    0.151  63591.8 33407.0

For two (most likely?) working clients:
ntpq -c as
ind assid status  conf reach auth condition  last_event cnt
===========================================================
  1  7757  963a   yes   yes  none  sys.peer    sys_peer  3

ntpq -c pe
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*hadoop20.xx LOCAL(0)         6 u   18   64  377    0.183    7.883   3.015

edit 2:
I have used sudo service ntp stop, sudo ntpdate 192.168.178.20, wait for ntpdate to finish, sudo service ntp start on all clients. There are still only 2 succeeding clients and 5 rejecting clients.
The rejecting clients show this output. The delay + offset values look high because the failing clients drift in time. Maybe they are not trusting the server to update the time because the delay/offset is so high?
ntpq -c as
ind assid status  conf reach auth condition  last_event cnt
===========================================================
  1 20981  905a   yes   yes  none    reject    sys_peer  5

ntpq -c pe
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 hadoop20.xx LOCAL(0)         6 u   34   64    3    0.166  18665.9 16201.3

I have also tried using this https://askubuntu.com/a/256004 answer, it works for about 30 seconds then the state changes to "reject" again! Same for ntpdate -s 192.168.178.20. It is most likely related to the ntp clients rejecting the time of the server. Is there a way to FORCE them to change the time?
Answer: Don't do this.  Seriously.  Just don't.  People keep coming up with the idea that NTP is designed to allow a bunch of machines all to have the same time.  It isn't.  It's designed, quite carefully, to allow many machines to all have the closest thing they can to the correct time, which is not the same thing.
If you have access to a window, you can build a half-decent stratum-1 server for about £50, or a good one for £100.  You would do much better to build something like that, then point the other clients at it.  Correct timestamps are much better than merely self-consistent ones, not least for forensics.
But if you absolutely must do what you're doing, then you need to realise that you're perverting ntpd, and this will mean understanding what you're doing.
On the server
server 127.127.1.0 prefer
fudge  127.127.1.0 stratum 10

means "use the local undisciplined clock as if it were authoritative", which is what you want.  I'm not sure why you're forcing it to stratum 10, though; consider dropping the stratum 10, and let the driver supply its default stratum of 0.  On the clients
server 192.168.178.24 iburst
fudge 192.168.178.24  stratum 10

makes no sense at all.  fudge 127.127.x.y is reserved for forcing the use of various kinds of local clock drivers.  It makes no sense to give it any other address.  Drop the fudge line from the clients, and just point them at the server.  You're also using a closed network, so drop all the security stuff until you get this working:
restrict default

If that still doesn't seem to work, we'll need to see the output of ntpq -c as and ntpq -c pe on both the server, and on a badly-behaving client, after at least ten minutes of uninterrupted running.
Edit: you write in a comment below that "I think the offset/jitter is really high because the failing clients
drift in time".
I think you may be right.  This chap's blog suggests he had the same experience: that the client clock was so bad that it fooled the local ntpd into thinking that the server was unreliable.  He wrote

the reason for the huge jitter finally seems clear! Our clock drifts
  so fast that the offset will go up by several seconds through our few
  measurements

Given that it's your clients whose time goes most quickly off which are failing to sync (marking the server as "reject"), I think you're seeing the same effect.  His solution was to use adjtimex to manually tune the kernel clock (adjusting the tick value) until the system clock was less wayward, at which point ntpd had a chance to recognise the server as being OK, and sync to it.  You should probably give that a try on the worst client first, and see if it helps.
Comment: Following up on your edit: Installing package `adjtimex` solved the problem on its own! The installation printed stuff like: `Comparing clocks (this will take 70 sec)...done.
Adjusting system time by -14.5741 sec/day to agree with CMOS clock...done.`. After it finished, `sudo service ntp stop`, `sudo ntpdate 192.168.178.20`, `sudo service ntp start` has solved it!
Comment: I've edited my original question. It looks like two clients were able to connect to the server now, but 5 could not. At least that's what I can tell from the output of `ntpq -c as` and `ntpq -c pe`
Comment: Looks like it's not a firewall problem, as even the refusing clients can see that the server's at stratum 6.  Does `ntpd` syslog anything useful on a refusing client, so we can get some idea of why they're `reject`ing the server?  Also, id you do the `ntpdate` first?  Plus, the `cnt=2` on the refusing output above is worrying; you did wait ten minutes as asked, yes?
Comment: I have just used the commands again - I think it was 10 minutes already the last time but now it is for sure. For the failing servers, the `cnt=2` remains, it has not changed. I have not restarted meanwhile. I will stop all client ntp services now, use `ntpdate 192.168.178.20` on the clients and then restart the ntp service on the clients. `cat /var/log/syslog | grep ntp` has not given any output for the last hour on the failing clients. Any idea? what about the `minpoll`and `maxpoll` in the client config?
Comment: I have added more output to the original question. I think the offset/jitter is really high because the failing clients drift in time. Maybe they do not trust the time of the server?
Comment: My feeling is that you really need to get `ntpd` on the client to tell you what's going on.  You'll need to check your (r)syslog config, find out where ntpd is logging and why (on my system (CentOS6) it uses facility `daemon` and severities 5, 6, and 7).  Also, see my edit above.
Comment: Yours is the best answer and I've certainly read it every time i've needed to do this.  Your comment not to do this is not always practical.  What do you propose for complicated systems that are GPS/network denied?  I find myself in underwater applications for distributed systems and your answer has helped me multiple times.
Answer: I was able to get acceptable time diff following the below-listed steps:
Steps

Install chrony in both your devices
sudo apt install chrony

Let's assume the server IP address 192.168.1.87 then client configuration (/etc/chrony/chrony.conf) as follows:
server 192.168.1.87 iburst
keyfile /etc/chrony/chrony.keys
driftfile /var/lib/chrony/chrony.drift
log tracking measurements statistics
logdir /var/log/chrony

Server configuration (/etc/chrony/chrony.conf), assume your client IP is 192.168.1.14
keyfile /etc/chrony/chrony.keys
driftfile /var/lib/chrony/chrony.drift
log tracking measurements statistics
logdir /var/log/chrony
local stratum 8
manual
allow 192.0.0.0/24
allow 192.168.1.14

Restart chrony in both computers
sudo systemctl stop chrony
sudo systemctl start chrony

5.1 Checking on the client-side,
sudo systemctl status chrony
 `**output**:

            июн 24 13:26:42 op-desktop systemd[1]: Starting chrony, an NTP client/server...

            июн 24 13:26:42 op-desktop chronyd[9420]: chronyd version 3.2 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCFILTER +SECHASH +SIGND +ASYNCDNS +IPV6 -DEBUG)

            июн 24 13:26:42 op-desktop chronyd[9420]: Frequency -6.446 +/- 1.678 ppm read from /var/lib/chrony/chrony.drift

            июн 24 13:26:43 op-desktop systemd[1]: Started chrony, an NTP client/server.

            июн 24 13:26:49 op-desktop chronyd[9420]: Selected source 192.168.1.87`

5.1 chronyc tracking output:
        Reference ID    : C0A80157 (192.168.1.87)
        Stratum         : 9
        Ref time (UTC)  : Thu Jun 24 10:50:34 2021
        System time     : 0.000002018 seconds slow of NTP time
        Last offset     : -0.000000115 seconds
        RMS offset      : 0.017948076 seconds
        Frequency       : 5.491 ppm slow
        Residual freq   : +0.000 ppm
        Skew            : 0.726 ppm
        Root delay      : 0.002031475 seconds
        Root dispersion : 0.000664742 seconds
        Update interval : 65.2 seconds
        Leap status     : Normal

Answer: You may ditch NTP completely, set time manually on the "server" and issue this command:
ssh firstname.lastname@example.com "date -s \"$(date "+%F %T")\""

Loop it through all you "client" IP's and you are done!
Explanation: local time will be "copied" to remote machine via SSH.


Drupal Commerce: Set Order as Paid in Full

Question: I am trying to import records from a CSV file (from another non-drupal database) for a membership site I am porting to Drupal 7. I have Drupal Commerce, Commerce Recurring Framework set up. Everything works as it should when you go through the proper work flow. However, I have 2000+ records that need to be added to the site and going through that process doesn't make sense. In other words, I am writing a script to set up the order and then recurring entity for each user.
I have code that creates my order, the issue is that Commerce is looking for a payment to be made before it creates the recurring entity for the order. Again, that doesn't make sense from a time perspective, not to mention all of these members have already paid as these are being ported. So my question is how to I trigger the order paid in full event that will trigger the creation of the recurring entity being created? Or is there a way to just create the recurring entity?
Here is my code:
<?php
foreach ($records as $record) {
$product_sku = $record['sku'];

$order = commerce_order_new($user->uid, 'completed');

commerce_order_save($order);

$product = commerce_product_load_by_sku($product_sku);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

commerce_line_item_save($line_item);

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

commerce_order_save($order);
}
?>

Thanks,
Aaron
Comment: Why are you trying to trigger that event? If you're importing these orders, why can't you just load and execute the rule directly as part of the import process?
Comment: I don't see how. I couldn't find a rule that actually created the recurring entity. As far as I could get I could see that once the order was paid for (0 balance) then the entity would create. Thoughts?
Comment: I assumed there was a rule from your description of your problem. If there isn't, then just invoke the same code the module is using to do the processing.
Answer: If you want to trigger the paid in full event you just need to make the order balance 0. You can do that by adding a payment transaction for the full amount to the order. The event is then triggered when that new successful transaction is saved.
The relevant Commerce function is
commerce_payment_commerce_payment_transaction_insert
/**
 * Implements hook_commerce_payment_transaction_insert().
 *
 * When a new payment transaction is inserted that is already completed, check
 * the order balance and invoke a Rules event if the order is paid in full.
 */
function commerce_payment_commerce_payment_transaction_insert($transaction) {
  // If the inserted transaction was marked as a success and placed against a
  // valid order...
  if ($transaction->status == COMMERCE_PAYMENT_STATUS_SUCCESS &&
    $order = commerce_order_load($transaction->order_id)) {
    // Then check to make sure the event hasn't been invoked for this order.
    if (empty($order->data['commerce_payment_order_paid_in_full_invoked'])) {
      // Check the order balance and invoke the event.
      $balance = commerce_payment_order_balance($order);

      if ($balance['amount'] <= 0) {
        // Invoke the event including a hook of the same name.
        rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);

        // Update the order's data array to indicate this just happened.
        $order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

        // Save the updated order.
        commerce_order_save($order);
      }
    }
  }
}

The key part is here:
// Invoke the event including a hook of the same name.
rules_invoke_all('commerce_payment_order_paid_in_full', $order, $transaction);
// Update the order's data array to indicate this just happened.
$order->data['commerce_payment_order_paid_in_full_invoked'] = TRUE;

// Save the updated order.
commerce_order_save($order);

In any case, you'll need to create a valid transaction for the order to trigger the commerce_payment_order_paid_in_full event. Rules reacting to that event will expect the transaction object as an assumed parameter.
Answer: You can use the example from commerce_payment_example module e.g.
<?php

  commerce_checkout_complete($order);

  if ($is_cli) {
    drush_print('Marking order as fully paid...');
  }

  $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

  if (!$payment_method) {
    if ($is_cli) {
      drush_print("  No example payment method found, we can't mark order as fully paid. Please enable commerce_payment_example module to use this feature.");
    }
  }
  else {
    if ($is_cli) {
      drush_print("  Creating example transaction...");
    }

    // Creating new transaction via commerce_payment_example module.
    $charge      = $order->commerce_order_total['und'][0];

    $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
    $transaction->instance_id = $payment_method['instance_id'];
    $transaction->amount = $charge['amount'];
    $transaction->currency_code = $charge['currency_code'];
    $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    $transaction->message = 'Name: @name';
    $transaction->message_variables = array('@name' => 'Example payment');

    if ($is_cli) {
      drush_print("  Notifying Commerce about new transaction...");
    }

    commerce_payment_transaction_save($transaction);

    commerce_payment_commerce_payment_transaction_insert($transaction);

For full working example, please see:
Programmatically creating an order in Drupal Commerce for anonymous users redirecting to payment page


When to deviate from scale?

Question:
Although above composition is in B minor, there is a single A# in the piece that is not in the scale.

What is the purpose of this out of scale note?
When does it make sense to use notes out of the scale?
Comment: By the way, there are mistakes in the notation. For example, the barline after bar 1 should be moved to the left: following the first G. And it would be easier to read with a time signature of 5/8. Though maybe there's an accompaniment in 10. Nice tune. Is it Turkish?
Comment: @OldBrixtonian It confused me too, first part makes more sense as 5/8 but vocal parts are more like 10/8 I guess. And yes, it is a Turkish song, you can listen here: https://www.youtube.com/watch?v=0L7i5Ta53Cg
Comment: I was imagining it as a fast dance! Yes - there's *something* 10-ish about it it. Maybe just the drum playing that 3+2 2+3 pattern. A Turkish musician told me that the first year of music college there is spent studying the 2nd degree of the scale. I hope Turkish music isn't losing those tunings.
Comment: Deviate when it sounds "right" to do it wrong.
Answer: But A♯ IS in the scale! There are three minor scales- natural, melodic and harmonic. And that note is in both the melodic and harmonic scales!
It's there to produce a bit of tension - without it, the closest note under the root B would be a whole tone below. So that note (A) is raised to make a semitone under B. It's like the leading note in the major scale - giving the feeling of pull towards the root.
When does it make sense to use 'out of scale' notes? Whenever they sound good, or better than 'in scale' notes! One of the things music can do is surprise, by going somewhere unexpected. Non-diatonic notes can do that. Except A♯ is diatonic in B minor. Don't go away with the concept that every piece must only have diatonic notes in it: it's a bit of theory which somehow, wrongly, works its way in.
Comment: @piiperiReinstateMonica - no! I'm saying the *natural* minor has B C# D E F# G A. The harmonic minor has B C# D E F# G A#. The melodic minor has B C# D E F# G# A#. Each has the normal 7 notes - one of each letter. But using them as a 'Bm pool', there's 9. But that's not in a scale!
Comment: @piiperiReinstateMonica - OP may well consider only the natural minor scale, which won't have A#. However, *key* and *scale* are not synonymous, and the majority of minor pieces have the leading note. Also seems under the impression, like a lot of questioners here, that notes in a piece must belong to a scale/key. Someone's teaching 'em wrong!
Comment: Are you saying that the B minor scale contains ... B, C#, D, E, F#, G, G#, A, A# .... 9 notes? :)
Comment: I was literally going to write "A♯ IS in the scale" and saw your answer, +1.  Not only is there a maj 7 in the "harmonic minor" but I think it's important to distinguish the minor scale(s) from the minor KEY signature.  You want/need that leading tone.
Comment: @ggcg The OP says it's not in the scale, so by "_the scale_" the OP is referring to a scale that does not have an A#.
Comment: I don't think anyone is teaching them... it's just the wrong conclusion that comes from how things look. Another incorrect conclusion is to think that a scale "exists" all the time even when nothing is being played, when actually it's just a reference grid for finding some basic positions and jumps. Even the tonic note is only a point of reference. It doesn't necessarily obey the key signature - which is another one of these incorrect assumptions.
Comment: I hate to break the news to you (some of you) but what the scale IS may depend on when you learned it.  In older classical guitar texts what we call melodic minor is NOT called melodic minor but plain old minor.  Not a major issue though, ;-)
Comment: @ggcg - would that be our melodic going up, and natural coming down - or what jazzers use, same both ways? There are still 3 recognised minor scales - and that's without Dorian and Phrygian!
Comment: The first, and the others don't usually warrant the designation of a key.
Answer: You want to re-orient your thinking. The concern isn't about the music being in a scale but what is the tonality?
In this case the question is about it being in a minor key.
All keys - both major and minor - have a leading tone one half step below the tonic. The A# here is the leading tone to the tonic B in the key B minor. The leading tone in minor is not in the key signature, but that is normal for minor key music. The seventh scale degree in minor is sometimes raised from the key signature to create a leading tone one half step below the tonic.
That give us the background to get into your question...

When does it make sense to use notes out of the [key signature]?

The answer lies in harmony: the leading tone is used to create dominant harmony. Let's avoid a long digression into harmony and just say the dominant chord in this music is the F#7. That chord is spelled F# A# C# E so when an A is played for that chord it takes a sharp. Notice that when A is not part of F#7 it is not sharped.
A natural used for passing tones and other non-chord-tones, no F#7 chord involved...

A natural used as a chord tone in an A major chord, and part of an elaboration of the descending line B A G F#, no F#7 chord involved...

A becomes A# when part of the F#7 chord, and its role as the leading tone can be seen where A# moves up to B...

When the seventh degree is the lowered form (not raised from the key signature) you can call the tone the sub-tonic.
When the seventh degree is raised from the key signature to be a half step below the tonic, it's called the leading tone.
Other tones within a key can be raised or lowered like this, but the raising of the seventh scale degree to create a leading tone is especially important in tonal music.

Some final food for thought regarding music being  in a scale or from a scale:
Scale and key are often used synonymously. Most of the time that isn't a problem and you can understand the meaning by context. But, when scale gets mixed up with the idea there are only seven unchanging pitch classes in a key, trouble follows.
The answers to this question all point out how scale degrees are flexible within a key. Understanding the flexible nature of such tones is a harmonic matter.
Look back at the notation for this song and the type of melodic motion used. Why are we talking about scales? Where are the scales in the music? The motion type employed is mostly arpeggiated chord tones, turn figures and some other embellishments on chord tones, and "filling in" the thirds of chords.
This melody isn't derived simply from a scale, it's derived harmonically from the tones of chords within the key. It may seem paradoxical, but understanding melody is often a matter of understanding harmony.
Answer: Great answer from Tim, but I would also add that the chord notated at those points in the piece are F#7 chords and A# is the 3rd of that chords. If you followed strictly from the key signature, those chords would be F#m7 chords which would not produce as strong of a cadence from the V to the I.
Sometimes, in a jazz context, a minor third against a 7 chord is an interesting colour, but the chord is often written as a 7#9 chord, which implies the major 3rd is still played anyway.
It is also very common to play an F#7b9 chord when playing V to I in a minor key so as not to create dissonance by implying a C, natural 9, against the B, the b9. Hope that also helps!
Comment: In a strict sense, yes that is true. I should have written in a Jazz context. For example, if you see a chord chart and the chord is written F#7 to Bm, a harmony player may play a F#9 to Bm7, or they might play F#7 to Bm11, adding upper extensions to the chord. Further, a soloist seeing those same chords might play any of the minor scales, using purely notes from the key signature, or as you point out, using the A# as a leading note. I guess i was trying to give a wider context to why someone might use non-diatonic notes in a melody.
Comment: But there's no B or C in either F# chord!
Answer: TL;DR: If you cannot do the intervals you want to do with a certain scale you happen to be thinking, then you have to deviate from it. If you want to do, say, a melody line F# - A# - B, or an F# major chord, you cannot do that with the notes in the B natural minor scale.
To try to explain what is being done with accidentals i.e. modifications to a scale, I'll transform the question to "when to deviate from a scale". Or, "when to deviate from the particular scale I happen to be thinking about at a given moment." There is any number of different scales, each with different uses. Why do you use any scale at all in the first place? As opposed to, playing unique pitches where no pitch is ever played twice? Why are scales used?
Scales are used as reference grids for reproducing certain sets of intervals. Intervals are relationships between pitches, and intervals are what harmony is built of. If you use, say, the major scale or other "diatonic" scales - around which the Western music culture and notation system is developed - there is a certain set of intervals that can be obtained using the notes in that scale. In tonal music like the one you have in the example, there is an implied home note all the time, to which your ear compares all pitches it hears.
In the example song the home note is B. If you are happy with only contrasting the home note B with A and C# notes and other notes you get with the B natural minor scale, then you don't have to deviate from the scale. However, if you want to contrast something with an A# note, or if you want to play, say, an F# major chord before going back home to B minor, the B natural minor scale does not have the ingredients for that chord. You have to deviate from the B natural minor scale.
Scales are not a law of nature, they are a cultural helper construct and a convention to help produce certain interval structures.
Accidentals are used to do temporary modifications to the prevailing scale, in order to achieve different harmonic effects.
Comment: Is this supposed to be an answer or a new question?
Comment: @ggcg If you are not happy with the intervals that are possible with the scale you have, then you have to deviate from the scale. That's the answer. Did you not read the text.

When to deviate from scale?