text:
Q: Proof of theorem 3.4 in Stein's real analysis
(Corollary 3.6.) Suppose $G$ is a real-valued and continuous on a closed interval $[a,b]$. If $E$ denotes the set of points $x$ in $(a,b)$ so that $G(x+h)>G(x)$ for some $h>0$, then $E$ is either empty or open. In the latter case, it is a disjoint union of countably many intervals $(a_k,b_k)$, and $G(a_k) = G(b_k)$, except possibly when $a =a_k$, in which case we only have $G(a_k)\leq G(b_k)$.

Let $O\subset\Bbb R$ be an open set. Then $O$ can be written as $\bigcup I_n$, with $I_n$ disjoint open intervals. Fix $n$ and apply Corollary 3.6 to the function $G(x) = -F(-x)+rx$ on the interval $-I_n$. Reflecting through the origin again yields an open set $\bigcup_k(a_k,b_k)$ contained in $I_n$, where the intervals $(a_k,b_k)$ are disjoint, with
$$F(b_k)-F(a_k)\leq r(b_k-a_k).$$

I don't understand the meaning of Reflecting through the origin here. Using the notation of Corollary 3.6, $E$ of $-I_n$ can be written as $E =\bigcup_k(\alpha_k,\beta_k)$. Then $G(\alpha_k)\leq G(\beta_k)\iff -F(-\alpha_k)+r\alpha_k\leq -F(-\beta_k)+r\beta_k$. What should I do next from here?

A: "Reflecting through origin" just means negating the interval: $(u, v) \mapsto (-v, -u)$. But there is a problem.
Letting $G(x) = F(x) - rx$ and applying Corollary 3.6 results in finding intervals satisfying $F(a_k) - ra_k \le F(b_k) - rb_k$, that is, $r(b_k - a_k) \le F(b_k) - F(a_k)$, exactly the opposite inequality than is needed.
This could have been solved by negating the function, $G(x) = -(F(x) - rx)$, so the intervals found are those where $F(x) - rx$ is lower at the right endpoint instead of higher. Or it could have been solved by reflecting the domain of the function: $G(x) = F(-x) -r(-x)$, so the intervals found are those where $F(x) - rx$ is higher at the left endpoint instead of at the right. Either would have worked to get the desired inequality.
Instead, the book went with $G(x) = -F(-x) + rx = -(F(-x) + r(-x))$. The intervals found by Corollary 3.6 then satisfy $$G(a_k) \le G(b_k)\\-F(-a_k) + ra_k \le -F(-b_k) + rb_k\\F(-b_k) - F(-a_k) \le r(b_k - a_k)$$
Now since $a_k < b_k$ for the intervals found, we have $-b_k < -a_k$, so by a relabelling $\alpha_k = -b_k, \beta_k = -a_k$, we have intervals $(\alpha_k, \beta_k)$ for which $$F(\alpha_k) - F(\beta_k) \le r(-\alpha_k -(-\beta_k))$$
or $F(\beta_k) - F(\alpha_k) \ge r(\beta_k - \alpha_k)$. This isn't the inequality they claimed.
Because they talk about reflecting through the origin and $-I_n$, I think they intended $G(x) = F(-x) +rx$, and the negative sign in front of $F$ was just a typo.


text:
Q: Excel: Determining which argument to MAX() was the maximum is there a way to check which argument in =MAX(1,3,2) was the maximum? The example should return 2 (or 1 if the index starts at 0).
I have different sources of data and would like to display which one was selected.
thanks!
Bernhard

A: You could use:
=MATCH(MAX(C37*2,B23*4,D4),CHOOSE({1,2,3},C37*2,B23*4,D4),0)
If one or more of the three expressions being passed to MAX is in reality quite lengthy and/or resource-heavy, it may be worth avoiding its repetition, e.g.:
=MATCH(1,0/FREQUENCY(0,1/(1+CHOOSE({1,2,3},C37*2,B23*4,D4))))
though you should note that the latter is only valid if the results of the three expressions being passed to MAX are non-negative.
Regards

redpajama_set_name: RedPajamaStackExchange


text:
Q: Amazon S3 Bucket Index? Hello i want to use my bucket to display a index or a redirect is that possible?
For example when i go to my bucket bucket1example.s3.amazonaws.com,
i get AccessDenied error
<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>42RP9K65G8T9EA7A</RequestId>
<HostId>
byYoD3naIjOi3aqwONTrAkOL2Basfdj29faPMz29sgofukHo15K987GIRClOuscJmzKX0S24EzM=
</HostId>
</Error>

But if i go to my file doc.html bucket1example.s3.amazonaws.com/doc.html i can see my file.
Is there a way to display the Doc.html file with the url "bucket1example.s3.amazonaws.com"?
Is possible when i visit bucket1example.s3.amazonaws.com automatically redirect to "doc.html"?

A: You have to enable static website hosting for the bucket and configure an index document
This AWS document can help you with the configuration.
https://docs.aws.amazon.com/AmazonS3/latest/userguide/IndexDocumentSupport.html


text:
Q: Java program that teaches kid simple addition and subtraction I feel like I'm almost there with the code but the problem is the while loop I am not allowed to use break and continue statements for this program. The first output test its suppose to have 14 questions where you get 12 right and 2 wrong giving you 86%. As for the second test you get a perfect score while the last test takes you to 20 questions that being the max number of questions, 4 of the first 8 questions correctly and 4 of the first 8 incorrectly, and then the next 12 correctly giving you 80% Code below:
package proj3;

    import java.util.Scanner;

    public class Project4App {

        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            int correctNum = 0;
            int wrongNum = 0;
            double percent = 0;
            int subNumCorrect = 0;
            int subNumWrong = 0;
            int addNumCorrect = 0;
            int addNumWrong = 0;
            int totalQuestions = 0;

            while(!(correctNum == 10 && totalQuestions == 10) && !(percent >= 85.0 && totalQuestions >= 10) && (totalQuestions != 20)) {
                Question Quest = new Question();

                System.out.println("What is the result?" + "\n" + Quest.toString());
                int userInt = scnr.nextInt();

                if((Quest.getOperator() == '+') && (userInt == Quest.determineAnswer())) {
                    addNumCorrect += 1;
                }
                else if(Quest.getOperator() == '+' && (userInt != Quest.determineAnswer())) {
                     addNumWrong += 1;
                }

                if((Quest.getOperator() == '-') && (userInt == Quest.determineAnswer())) {
                    subNumCorrect += 1;
                }
                else if((Quest.getOperator() == '-') && (userInt != Quest.determineAnswer())) {
                     subNumWrong += 1;
                }

                if(userInt == Quest.determineAnswer()){
                    correctNum += 1;
                    System.out.println("Congratulations, you got it correct!");
                }
                else if (userInt != Quest.determineAnswer()){
                    wrongNum += 1;
                    System.out.println("The correct answer for " + Quest.toString() + " is " + Quest.determineAnswer());
                }

                totalQuestions++;

                percent = Math.round((double)(correctNum * 100) / (totalQuestions));
                }

                System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
                System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
                System.out.println("The percent correct: " + percent + "%");

                scnr.close();
            }
        }

A: I think this largely does what you want. A number of the counters weren't being modified as was intended. This is partly due to the amount going on in your main method making it hard to see what's going on (too much information). I've extracted functionality to smaller, more well defined methods.
You had a whole lot of logic effectively saying you want the user to have achieved 85% with at least 10 questions answered - and stop when 20 questions are asked. You could factor this condition out to a method returning a boolean isGameComplete(totalQuestions) and put this in the while condition-expression.
I've taken the liberty of implementing a question class based on the functionality that I think achieves the intention.
The correctPercent was rounded to an int which made it impossible to be == to 85.5%, say. I've converted this to a double so if you get more than 85%, say 85.25%, the game completes successfully.
Probably some other stuff I've added, which I've tried to comment in-line, if significant. Hopefully this is what you were after.
If it ever gets too difficult to understand, extracting small chunks of code to well named methods (even long ones) helps enormously, since it reduces your mental load.
class Project4App {

    static final Scanner scanner = new Scanner(System.in);
    static int correctNum = 0;
    static int wrongNum = 0;
    static int subNumCorrect = 0;
    static int subNumWrong = 0;
    static int addNumCorrect = 0;
    static int addNumWrong = 0;
    static int totalQuestions = 0;
    static double percentCorrect = 0;

    public static void main(String[] args) {
        /**
         * answer at least 9/10 questions correctly (to get 85%)
         */
        while (percentCorrect < 85.0 && totalQuestions >= 10 && totalQuestions <= 20) {
            Question question = new Question();

            int userInt = getUsersAnswer(question);
            boolean isCorrect = question.determineAnswer(userInt);
            updateStatistics(question, isCorrect);
            printResults(); // can remove this/comment this out - added to help with debugging
        }

        System.out.println();
        System.out.println("------------ Game Complete! ------------");
        printResults();
    }

    private static void printResults() {
        System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
        System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
        System.out.println("The percent correct: (" + (addNumCorrect+subNumCorrect) + "/" + totalQuestions +") " + percentCorrect + "%");
        System.out.println("The percent wrong: (" + (addNumWrong+subNumWrong) + "/" + totalQuestions +") " + (100 - percentCorrect) + "%");
    }

    private static int getUsersAnswer(Question question) {
        System.out.println("What is the result?" + "\n" + question.toString());
        int userInt = scanner.nextInt();
        return userInt;
    }

    public static void updateStatistics(Question question, boolean isCorrect){
        if (question.getOperator() == '+') {
            if (isCorrect) {
                addNumCorrect++;
                correctNum++; // newly added (wasn't updated)
            } else {
                addNumWrong++;
                wrongNum++; // newly added - unused variable originall
            }
        } else { // operator is '-'
            if (isCorrect) {
                subNumCorrect++;
                correctNum++; // newly added (wasn't updated)
            } else {
                subNumWrong++;
                wrongNum++; // newly added - unused variable originall
            }
        }
        totalQuestions++; // newly added
        percentCorrect = (correctNum * 100) / totalQuestions;
    }
}

class Question {

    private static final int UPPER_LIMIT_ON_RANDOM_NUMBERS = 20;
    private static final Random random = new Random();
    private final int number1;
    private final int number2;
    private final char operator;

    public Question() {
        operator = Math.random()>0.5 ? '+' : '-';
        number1 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // NOTE THE SUBTRACTION NUMBER COULD BE NEGATIVE IF number2
        number2 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // IS GREATER THAN number1.
    }

    public char getOperator() {
        return operator;
    }

    public boolean determineAnswer(int userAnswer) {
        switch (operator) {
            case '+':
                return userAnswer == (number1 + number2);
            case '-':
                return userAnswer == (number1 - number2);
        }
        return false; // shouldn't end up here - would be better to throw an unchecked exception and crash the program - new RuntimeException()
    }

    @Override
    public String toString() {
        return number1 + " " + operator + " " + number2;
    }
}

Output:
------------ Game Complete! ------------

Progress Report:
Addition:
You got 7 correct and 0 incorrect.
Progress Report:
Subtraction:
You got 2 correct and 1 incorrect.
The percent correct: (9/10) 90.0%
The percent wrong: (1/10) 10.0%


text:
Q: How to extract data from an html form using django? I have html form with some text input for a users registration, the form is like this:
<form id="signup-form" action="#" method="post">
                 Full Name
                 <input autocomplete="off" type="text" name="username" id="name" class="name">

                 Email Adderss
                 <input autocomplete="off" type="email" name="emailAdress" id="email" class="email">

                 Phone Number - Optional
                 <input autocomplete="off" type="text" name="phone" id="phone">

                 Password
                 <input autocomplete="off" type="password" name="password" id="password" class="pass">

                 Confirm Password
                 <input type="password" name="passwordCon" id="passwordCon" class="passConfirm">
                 <input type="submit" form="signup-form" value="Signup Now" id="submit">
           </form>

I want to know, how can i store the values of each input, when the button is submitted and save them in the database, is there a way to call the input field by its ID and store it in Django?

A: Your code template is missing a lot of things like urls , views and models .
What views you are working with , url of the form submission , and what database. But here is a simple structure of the form submission if you are using django user model and not using custom model .
You have your form template. It works fine , but add a new field after  tag for csrf_verification of the template.
<form>
{% csrf_token %}
...

...
</form>

Your urls.py for the signup
from django.urls import path
from . import views

urlpatterns = [
    path("signup/" , views.signUpView , name = "user-signup") ,
]

Your views.py
I am using a function-based view here and django User model.
from django.contrib.auth.models import User
from django.contrib.auth import login

def signUpView(request , *args , **kwargs):
    if request.method == "POST":
        username = request.POST.get("username")
        emailAddress = request.POST.get("emailAddress")
        password = request.POST.get("password")

        # get all your fields which you gave in the form.

        user = User(userrname = username , email = emailAddress )
        user.set_password(password)
        user.save()
        login(request , user)
        return redirect("homepage")
    else :
        return render(request , "signupPage.html")

This is your basic template and working of django signup page. And this will do your work which you are asking for. For detailed and specific answer. Elaborate the question.


text:
Q: Issue with ng-if and grid-tile I am trying to hide a grid-tile when the screen size is small or less, at the same time I want show a hidden grid-tile. Both of these grid-tiles contain a d3 graph.
My issue is with loading the graph when the screen size changes; the tile appears but the graph does not load. However, if I refresh the page the graph will load. The issue is illustrated on this codepen (Resize to small window. Refresh).
http://codepen.io/sweatherly/pen/Wxdpwx
     <md-grid-tile ng-if="$mdMedia('gt-sm')" md-rowspan="2" md-colspan="9" md-colspan-md="6" md-colspan-sm="4" md-colspan-xs="1">
      <md-card class="graph-card dark-cards" layout-fill>
        <graph></graph>
      </md-card>

  </md-grid-tile>

To get the initial load to work I had to use $document.ready({});. I'm not sure how I could apply this to the page resizing/ng-if.

A: The problem is that your graph directive has no link function. Because, $document.ready returns undefined:
link: $document.ready(function loadGraph() {
    //Code here
});

You need to change that to:
link: function() {
    $document.ready(function() {
        //Your Code here
    });
}

Please check out this demo: http://codepen.io/anon/pen/akEwok


text:
Q: Rotate x-axis labels, D3js multi bar chart I would like to rotate my labels on the x-axis. The labels are currently overlapping. However, I can't figure out how to alter them in the template I based the bar chart off of. My assumption is that it is somewhere in the lines below, but it is a template with a structure I am unfamiliar with as a d3 beginner. My plunker is http://plnkr.co/edit/jtGz8vtYGSHscKhrIob3?p=preview
d3.csv("data.csv", function(d, i, columns) {
    for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
    return d;
}, function(error, data) {
    if (error) throw error;

    var keys = data.columns.slice(1);

    x0.domain(data.map(function(d) { return d.n; }));
    x1.domain(keys).rangeRound([0, x0.bandwidth()]);
    y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

    var rectG = g.append("g")
    .selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d) { return "translate(" + x0(d.n) + ",0)"; })
    .selectAll("rect")
    .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
    .enter();

A: When appending the x-axis, you can do the following to rotate the labels:
g.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x0))
    //select all text labels in the axis, then position + rotate
    .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-1em")
      .attr("dy", "-0.5em")
      .attr("transform", "rotate(-90)");

PS: this will overlap with all the text/labels you have in the bottom and you have to position them accordingly as well so things fit properly. You probably have to stretch out your svg a little bit vertically to make everything fit. I have given it a try in the plunkr; you can adjust it further if you want the graph to be larger, etc.
Forked Plunkr here - http://plnkr.co/edit/JyFdeX0wy9g0lUKi9ASC?p=preview


text:
Q: Updating $PATH on mac to use new version of a file I originally installed the Elm v0.16 version of elm-format https://github.com/avh4/elm-format. I don't remember how I set it up but a new Elm v0.17 has been released and elm-format was updated. I downloaded the new elm-format file but when I type elm-format into the terminal it still shows the old version:
elm-format 0.2.0-alpha.
I thought I added it to my path but I'm not sure because I don't see anything but this on my path when I run echo $PATH:
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

How do I make it so that when I run elm-format it uses the latest version that I just downloaded? I had configured the previous version of elm-format to work with sublime text as well but now I can't update sublime to use the new elm-format either and it defaults to using the old version of elm-format, resulting in improper syntax.
Additionally, since the latest version of Elm has new syntax and idioms, when writing code in sublime it is still trying to use the old syntax and highlights my Elm 0.17 syntax with the hot pink incorrect syntax highlight.
I can't even find where or how the old version of elm-format exists but for some reason it's the default version.
I don't know if it's relevant but this is my current .bash_profile that I apparently never altered to make work with the old version of elm-format:
# STYLING & COLORS
# ################

## LSCOLORS
#> http://osxdaily.com/2012/02/21/add-color-to-the-terminal-in-mac-os-x/
#> http://apple.stackexchange.com/questions/100297/changing-terminal-color

export CLICOLOR=1
export GREP_OPTIONS='--color=auto'
export LSCOLORS=exBxhxDxfxhxhxhxhxcxcx

## Prompt Style/Colors
#> http://blog.taylormcgann.com/2012/06/13/customize-your-shell-command-prompt/
#> http://www.kirsle.net/wizards/ps1.html

export PS1_OLD=$PS1
export PS1="\[\033[1;35m\]\W \[\033[1;91m\]♥\[\033[0;36m\] "

In Sublime, under Preferences > Package Settings > Elm Language Support > User Settings I have:
{
    "elm_format_on_save": true,
    "elm_paths": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/elm-format"
}

All in all I'm totally confused and frustrated as I can't even write code without hot pink highlights all over it.

A: First run which elm_format to show the location of the old 0.16 version. You can then replace that binary with the new one you got from github. From the sublime path it looks like you've placed a binary of elm_format on the root of the hard drive. You may want to put it inside /usr/local/bin


text:
Q: Magento 2 - How to get additional options product from quote item I have some Vitrual product with options, I need to get his options but I can just get the info_buyRequest instead of additional_options
Here is my code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');

//This doesn't work
$itemsCollection = $cart->getQuote()->getItemsCollection();

//This doesn't work too
$itemsVisible = $cart->getQuote()->getAllVisibleItems();

//This return something
$items = $cart->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'
';
    echo 'Name: '.$item->getName().'
';
    echo 'Sku: '.$item->getSku().'
';
    echo 'Quantity: '.$item->getQty().'
';
    echo 'Price: '.$item->getPrice().'
';
    echo "
";
}

//Here I try to get the product options but no way

$items = $cart->getQuote()->getAllItems();

foreach ($items as $item) {
    $options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
    $customOptions = $options['options']; // error here, line 44
    if (!empty($customOptions)) {
        foreach ($customOptions as $option) {
            $optionTitle = $option['label'];
            $optionId = $option['option_id'];
            $optionType = $option['type'];
            $optionValue = $option['value'];
        }
    }
}

Error:

Exception #0 (Exception): Notice: Undefined index: options in
  /app/code/Vendor/Module/view/frontend/templates/file.phtml
  on line 44

quote_item_option table > additional_options code

A: Please use below to get additional_options
$options = $item->getOptionByCode('additional_options');

A: You can use

$options = $item->getBuyRequest();

Instead of

$options =
  $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());

A: You can use it is work for me,
$additionalOptions = $item->getOptionByCode('additional_options')
echo $additionalOptions->getValue();

A: Because this wasn't answered the above solutions are missing the call to get the options.
$item->getBuyRequest()->getAdditionalOptions()


text:
Q: Probability Brownian motion hitting ball in dimension 2 and 3. Can someone help me in solving this exercise ? I was thinking it is something dealing with the recurrent/transient property of the Brownian motion, but I am not sure.
Let $(B_t)_t \in [0,1)$ be a standard Brownian motion on $R^2$  and for $R ∈ (0,∞)$ let $B_R$ denote the
ball of radius R centered at the origin. For every $t ∈ (0,∞)$, compute
$P[B_t ∈ B_R]$, and thereby prove that (1) $P(B_t \notin B_{\sqrt{2\lambda t}}) = e^{-\lambda}$,
(2) and that, for the Lebesgue measure $|B_R|$ of $B_R$,
$\lim_{R \rightarrow 0} \frac{P[B_t ∈ B_R]}{|B_R|} = \frac{1}{2\pi t}$
What happens in dimension three?

A: First, note that $\|B_t/\sqrt{t}\|_2$ has the $\chi$ distribution with $2$ degrees of freedom. Therefore,
$$
\mathsf{P}(B_t\in \mathsf{B}_R)=\mathsf{P}(\|B_t/\sqrt{t}\|_2\le R/\sqrt{t})=\int_0^{R^2/(2t)}e^{-x}\, dx=1-e^{-R^2/(2t)},
$$
and, consequently, $\mathsf{P}(B_t\notin \mathsf{B}_{\sqrt{2\lambda t}})=e^{-\lambda}$, and
$$
\lim_{R\to 0}\frac{\mathsf{P}(B_t\in \mathsf{B}_R)}{|\mathsf{B}_R|}=\lim_{R\to 0}\frac{1-e^{-R^2/(2t)}}{\pi R^2}=\lim_{R\to 0}\frac{e^{-R^2/(2t)}}{2t\pi}=\frac{1}{2\pi t}.
$$


text:
Q: Python: How to pass tornado read_message()'s result to QT5 UI element I have a python QT5 application, which starts tornado socket client in another thread. What I want to know is, whenever I get the result in tornado's websocket.read_message(), how to pass that value to QT5 GUI label.
Here is Main.py which starts QT5 GUI application and tornado websocket client in a new thread.
import sys
import threading

from PyQt5.QtWidgets import QApplication
from app.ui.components import MainWindow

from app.client import Client
from config import SERVER_URL

def main():
    app = QApplication(sys.argv)
    form = MainWindow()
    form.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    client = Client("ws://{0}/socket".format(SERVER_URL), 5)
    thread = threading.Thread(target=lambda : client.ioloop.start())
    thread.setDaemon(True)
    thread.start()
    main()

Here is Client.py
from tornado import gen
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.websocket import websocket_connect

class Client(object):
    def __init__(self, url, timeout):
        self.url = url
        self.timeout = timeout
        self.ioloop = IOLoop.instance()
        self.ws = None
        self.connect()
        self.periodic_callback = PeriodicCallback(self.keep_alive, 20000, io_loop=self.ioloop)

    @gen.coroutine
    def connect(self):
        try:
            self.ws = yield websocket_connect(self.url)
            self.periodic_callback.start()
        except Exception as e:
            pass
        else:
            self.run()

    @gen.coroutine
    def run(self):
        while True:
            msg = yield self.ws.read_message()
            if msg is None:
                self.ws = None
                break
            print("Received: {0}".format(msg)) # HOW TO PASS msg to GUI LABEL WHENEVER IT RECEIVES A NEW VALUE

    def keep_alive(self):
        if self.ws is None:
            self.connect()
        else:
            self.ws.write_message("Hello from client")

A: The tornado thread has access to objects in memory from the original thread. So a very simple solution would be to pass QApplication or some other object from the QT app into your Client object. Then when you receive a message, you can call whatever method on the QT object.
However, it's far from clear that this will work safely. QT objects might not be designed to be accessed from two different threads. Without knowing how a class is meant to be used, you shouldn't assume it's thread-safe. So the simple solution might mean that at the same time that some QT code is running on your main thread, the Tornado thread calls some piece of QT code which changes the state of the QT objects. The other piece of code wasn't expecting that thing to change, and so you get a crash or other failure.
It's possible you find out that the QT library is designed to cope with this. But's there's a better way in any case - a producer-consumer queue.
This means that you have a Queue object, which is shared between threads. This could be threading.Queue from the threading module you're already using. Every time a Websocket message is received, you put something on the queue. This could be any Python object - just the message string if it's all you need, or some custom object if you want.
Then on another thread, you have a loop which just reads from the queue, and calls QT each time it gets a message.
Edit - QT can probably handle this
I don't know much about QT. However, most windowing systems actually have their own event queue, where they manage clicks, key presses, etc. If calls to QT to update something are handled on this event queue, it probably means they are thread safe. This is because the function you would call from the Tornado thread doesn't directly make changes to the GUI, rather it simply adds something to the queue to be processed when QT gets round to it.
I had a quick look to some stuff about QT, and it seems that this probably is how QT works, and you should be find update it from the Tornado thread without implementing your own queue. See https://stackoverflow.com/a/11793684/1737957 and http://code.activestate.com/recipes/415311-qt-event-processing-python-threads/


text:
Q: mplayer freezes while attempting to play a file via the python subprocess module Here's a simple script just to illustrate the problem. The script is supposed to play any video and audio file that can be played with mplayer.
import sys
import time
import subprocess

def get_sound_duration(file_to_play):
    ffprobe = ["ffprobe", "-v", "error",
               "-show_entries", "format=duration", "-of",
               "default=noprint_wrappers=1:nokey=1", file_to_play]
    duration = subprocess.Popen(ffprobe,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
    return duration.stdout.readlines()[0].strip()

def play(player=sys.argv[1], file_to_play=sys.argv[2]):
    proc = subprocess.Popen([player, file_to_play],
                            stdout=subprocess.PIPE)
        time.sleep(float(get_sound_duration(file_to_play)))
        proc.terminate()
        proc.wait()

if __name__ == "__main__":
    play()

The problem with it is that when I run it with mplayer as follows:
$ python play.py mplayer PATH_TO_FILE

it hangs in less than a minute. Out of all players that I tested this script with, this issue only occurred with mplayer and mpv (which is based on mplayer, so, roughly speaking, it's the same).
I've found a way to fix it, but I'm not really satisfied with the fix. To fix it I just have to take the stderr parameter out of the Popen constructor in the play function. But however I don't understand how it solves the problem.
Do you have any ideas?


text:
Q: GCD and multiple delegates in iOs I would like to do the following:
In a class (shared instance) I will have a method that takes as parameters a data object (nsstring) and a delegate. This will create a new background thread and dispatch some calculations on that thread. The thing is that the method may be called hundreds of times with different data and possibly different delegates passed in . I would like the results to go to the correct delegate (I will need to keep the  delegates in an array right? or can I just pass them to the background thread as they come and when that thread finishes it will send the result only to that delegate?).
One more thing... all this methods will use a very large data structure (an array with 10000 nsstring objects,they only need to read from it). How do I make sure this is not duplicated on each thread? And is only allocated when needed and deallocated when no thread uses it?
Here is the code I decided to use:
   if (!self.dictPasswords) {
        // read everything from text
        NSString* fileContents = [NSString stringWithContentsOfFile:fileRoot
                                                           encoding:NSUTF8StringEncoding error:nil];

        //  separate by new line
        self.dictPasswords = [fileContents componentsSeparatedByCharactersInSet:
                                   [NSCharacterSet newlineCharacterSet]];

    }

    __weak id<PSPasswordDictionaryVerificationDelegate> wdelegate = delegate;

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [wdelegate willBeginPasswordVerificationForPassword:password];
        for (NSString *posiblePass in self.dictPasswords) {
            if ([password isEqualToString:posiblePass]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [wdelegate password:password isInDictionary:YES];
                });

                 return;
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [wdelegate password:password isInDictionary:NO];
        });

    });

However... after this runs I get a permanent 24MB added to the used memory. I would like to detect when no threads are using the self.DIctPasswords array and deallocate it. It will be read from the file again later if somebody calls this method again...
Thanks for the help guys.

A: Just let the block capture the delegate.
No need to hold it otherwise
Class
#import <Foundation/Foundation.h>

@protocol ProcessorDelegate;

@interface Processor
- (void)process:(id)data forDelegate:(id<ProcessorDelegate>)delegate;
+ (Processor*)sharedInstance;
@end

@protocol ProcessorDelegate
- (void)processor:(Processor*)processor didProcess:(id)data withResult:(id)result;
@end

@implementation  Processor

- (void)process:(id)data forDelegate:(id<ProcessorDelegate>)delegate {
    __weak id<ProcessorDelegate> wdelegate = delegate; //capture weak to counter potential cycles
    __weak id wself = self;
    dispatch_async(dispatch_get_global_queue(0,0), ^{
        NSLog(@"WORK");
        id result = data; //TODO
        [wdelegate processor:wself didProcess:data withResult:result];
    });
}

+ (Processor*)sharedInstance {
    static Processor *p = nil;
    if(!p) {
        p = [[Processor alloc] init];
    }

    return p;
}

@end

DEMO
@interface Demo : NSObject <ProcessorDelegate>
- (void)doIt;
@end

@implementation Demo
- (void)doIt {
    [Processor sharedInstance] process:@"TEST" forDelegate:self];
}
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        Demo *d1 = [[Demo alloc] init];
        Demo *d2 = [[Demo alloc] init];
        Demo *d3 = [[Demo alloc] init];
        Demo *d4 = [[Demo alloc] init];

        [d1 doIt];
        [d2 doIt];
        [d3 doIt];
        [d4 doIt];

        [[NSRunLoop currentRunLoop] run];
    }
}

A: It seems more appropriate to encapsulate the calculations plus data and delegate in a class of its own.  Then you can have an array of those objects in your singleton.  You may want to consider using NSOperation here.
OMT: Simply pass this large array as a pointer (to each calculation object) and use regular strong properties (not copy) if you're using any properties at all, saving a reference to it using an ivar is fine too.  One concern is that this data-structure must be read-only; otherwise (when you'd modify it in each thread), you'd need some data locking.

A: I have done it with blocks : a singleton that have all the functions you needs (like an API) and a delegate class
// singleton.h
typedef void (^request_handler_t)(NSData* data);
- (void) foo:(NSString *)str withBlock:(request_handler_t)callback;

// singleton.m
- (void) foo:(NSString *)str withBlock:(request_handler_t)callback;{
    MyDelegate *delegate = [MyDelegate delegateWithBlock:callback];
    [yourMethodThatNeedDelegate:delegate];
}

// MyDelegate.h
+ (MyDelegate*) delegateWithBlock:(api_request_handler_t)block;
- (void)delegateMethod1;

//Delegate.m
+ (MyDelegate*) requestWithBlock:(api_request_handler_t)block;{
    //... alloc init
    _callback = block;
}
- (void)delegateMethod1;{
    // delegate finished the job
    block(myResultingData);
}

// Usage :
[MySingleton singleton] foo:(NSString *)str withBlock:^(NSData *data){
    //do something with the async data
}];


text:
Q: TypeError: reservationService.getPendingReservations is not a function
angular.js:13708 TypeError: reservationService.getPendingReservations
  is not a function

When I load  page the first time I get this error, but giving F5 the page, load smoothly.
Below I show my code. Which I can not find the error. I've been checking some forums which indicate that it may be related to dependency injection but still can not find the error. I did a test and I realized that when the page loads the first time, the factory is uninitialized, if this is not related to this.
homeController.js
'use strict';
app.controller('homeController', ['$scope', '$route', '$location', 'authService', 'reservationService', 'localStorageService',
    function ($scope, $route, $location, authService, reservationService, localStorageService) {

    $scope.showNotifications = function () {
        updateNotifications();
        $("#notificationContainer").fadeToggle(600);
        //hideCountNotifications();
    }

function updateNotifications() {

        reservationService.getPendingReservations(authData.id_place).then(function (results) {
            if (results.status != 200) {
                $scope.message = "Upps! Lo siento, creo que tenemos un problema al cargar las notificaciones.";
                console.log(results);
            }
            else {
                $scope.notifications = results.data;
                $scope.cantPendingReservations = results.data.length;

                //// La primera vez que carga la pagina se llamada el metodo para que recargue la grilla
                //reloadGrid();
            }
            //$scope.$emit('UNLOAD')
            //$("#tableScheduler").show();

        }, function (error) {
            if (error.status == 401) { authService.logOut(); $location.path('/login'); }
        });
    }

}]);

reservationService.js
'use strict';
app.factory('reservationService', ['$http', '$q', 'localStorageService', 'servicesConnect', function ($http, $q, localStorageService, servicesConnect) {

    var serviceBase = servicesConnect.apiFutbolPlay;
    var reservationService = {};

    var authData = localStorageService.get('authorizationData');
    if (authData) {
        var _ListPitch = function (id_place) {
            var deferred = $q.defer();
            $http.get(serviceBase + 'api/pitches/single/' + id_place).then(function (results) {
                deferred.resolve(results);
            }, function errorCallback(err, status) {
                deferred.reject(err);
            });
            return deferred.promise;
        }

        var _ListPendingReservations = function (id_place) {
            var deferred = $q.defer();
            $http.get(serviceBase + 'api/reservations/customer/myreservations/' + id_place, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function (results) {
                deferred.resolve(results);
            }, function errorCallback(err, status) {
                deferred.reject(err);
            });
            return deferred.promise;
        }

        reservationService.getPendingReservations = _ListPendingReservations;
    }

    return reservationService;

}]);

index.html
<!DOCTYPE html>

    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="images/favicon/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

A: The reason for your error is that reservationService.getPendingReservations is initialised only if 'authorizationData' exists in local storage. If it doesn't then getPendingReservations is never set to anything.
My guess is that elsewhere in your code, authorizationData is stored in local storage, so that when you refresh the page the function becomes available.
To solve this problem, you will need to restructure your reservation service to deal with situations where authorisation has not happened, or perform checks before you attempt to use getPendingReservations.


text:
Q: primary key with additional data I've read somewhere that there is an option to store additional data on the leaves of the tree created by the primary key.
For example,
If I have a table with columns: row_id, customer_id
and I need to display customer_name, I can do join between my table and customers table. But I can also store the customer_name with the primary key of customers table (with customer_id) and the sql engine wouldn't have to load the entire row of customer in order to fins customer name.
Can someone describe it better?
How can I implement that?

A: For SQL Server 2005+, it sounds like you're talking about included columns, but that only works when all of the columns are in one table.
CREATE INDEX IX_Customers_RowCust
ON Customers (customer_id)
INCLUDE (customer_name);

But, I think you're describing a situation where (row_id, customer_id) are in one table, and customer_name is in a second table. For that situation, you'd want to create an indexed view.
CREATE VIEW vwCust WITH SCHEMABINDING AS
    SELECT t.row_id, t.customer_id, c.customer_name
        FROM SomeTable t
            INNER JOIN Customers c
                ON t.customer_id = c.customer_id
GO
CREATE UNIQUE CLUSTERED INDEX vwCustRow ON vwCust (row_id)
GO

A: The MSDN article explains it very well
http://msdn.microsoft.com/en-us/library/ms190806.aspx
Basically as it fetches the data from the index (based on your where clause) instead of having to hit the table again to get the additional data the index bring back the data which has been included as part of the index.
It is important to note that the included columns do not make up the index used for search purposes but they will affect the size of the index and so will therefore take up more memory space.
Joe has got the syntax that you need to implement it.

A: FYI: Note that you cannot add included columns on a clustered index, since a clustered index isn't really an index in the first place - it's just the b-tree of the data.  In some cases, you may be better off with a heap and several efficient covering indexes (which may have included columns).
So if your primary key is also the clustered index, no included columns...

A: Only a non-clustered index can be made covering by INCLUDEs. Here, the included columns are in the lowest level of the index. This avoids what is known as a key (bookmark in SQL Server 2000) lookup into the clustered index
A clustered index is covering automatically: the lowest leaf level of the index is the data. By default, a PK is clustered in SQL Server.
This applies to the same table.
To do this across tables you need an indexed view (and see Joe's answer)


text:
Q: Terraform GPG key mismatch I'm trying to install Terraform on Ubuntu with:
https://developer.hashicorp.com/terraform/tutorials/docker-get-started/install-cli
When trying to verify Hashicorp's GPG signing key I see this command
gpg --no-default-keyring \
    --keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
    --fingerprint

should have the expected output of
/usr/share/keyrings/hashicorp-archive-keyring.gpg
-------------------------------------------------
pub   rsa4096 2020-05-07 [SC]
      E8A0 32E0 94D8 EB4E A189  D270 DA41 8C88 A321 9F7B
uid           [ unknown] HashiCorp Security (HashiCorp Package Signing) <security+packaging@hashicorp.com>
sub   rsa4096 2020-05-07 [E]

as of the posting of this question. This also matches Hashicorp's Security page under the heading Linux Package Checksum Verification.
However, I see a new key created 2023-01-10 instead:
/usr/share/keyrings/hashicorp-archive-keyring.gpg
-------------------------------------------------
pub   rsa4096 2023-01-10 [SC] [expires: 2028-01-09]
      798A EC65 4E5C 1542 8C8E  42EE AA16 FCBC A621 E701
uid           [ unknown] HashiCorp Security (HashiCorp Package Signing) <security+packaging@hashicorp.com>
sub   rsa4096 2023-01-10 [S] [expires: 2028-01-09]

Am I correct in not trusting this key, as until Hashicorp fixes their documentation, this could be a compromised key?

A: HashiCorp has rotated its main signing keys this week.
The updated key, along with a note confirming the change of key, is now in the Official Packaging Guide document.


text:
Q: Htaccess SEF url rewrites Probably a simple solution for you guys but we are creating some landing pages for a customer's adwords account. We have the pages created and are inserting the area and keyword using get requests in PHP.
The url's currently look like this:
http://www.customersdomain.co.uk/index.php?keyword=locksmith&area=london
Essentially I am looking for a htaccess rewrite rule that would allow this url to be entered:
http://www.customersdomain.co.uk/areas/locksmith-london.html
With a view that the dynamic content of locksmith & london would be entered in to the page and could be replaced with other keywords such as locksmith & birmingham. We are aware this is bad practice for seo purposes but this customer has other reasons "wanting to appear local to his customer" for doing it.
Any help would be great as it is not really my forte.

A: Since you are the admin and you don't need htaccess at all, you can use something like this in virtualhost context:
RewriteEngine on
RewriteRule ^/areas/(.+)-(.+)\.html$ /index.php?keyword=$1&area=$2 [L]

or
RewriteRule ^/areas/([^-]+)-(.+)\.html$ /index.php?keyword=$1&area=$2 [L]

This is a very rudimentary way, but both work, if you have a limited set of values you could enclose them in the parenthesis like (london|paris|gotham). There are more complex examples, specially if you have hundres of possibilities and you want to be very specific matching them you could even use RewriteMap. But for starters try these ones, to make sure they are working use [R,L] to actually rewrite them and see how they really change in browser and then once you are sure they work, you can then remove the R flag so they get rewritten internally.
In between tests, make sure yo clear your cache, or simply try "curl  http://www.customersdomain.co.uk/areas/locksmith-london.html" to make sure cache from your browser is not interfering with your tests.
Be sure to check the mod_rewrite documentation
Oh, and about htaccess. I understand that you read somewhere to use .htaccess, and everyone in this world seems to think it is a magic file to add rewrites, but truth is it is only meant for users without access to main configuration file of HTTPD, it adds complexity as it happens in per-dir context, and it adds much overhead to the server. Your client will be thankful if you give their server maximum performance possible just by not using it. Good luck!


text:
Q: What is the best way to count the number of times a value occurs in an array? I have been given an assignment to write a program that reads in a number of assignment marks from a text file into an array, and then counts how many marks there are within particular brackets, i.e. 40-49, 50-59 etc. A value of -1 in the text file means that the assignment was not handed in, and a value of 0 means that the assignment was so bad that it was ungraded.
I could do this easily using a couple of for loops, and then using if statements to check the values whilst incrementing appropriate integers to count the number of occurences, but in order to get higher marks I need to implement the program in a "better" way. What would be a better, more efficient way to do this? I'm not looking for code right now, just simply "This is what you should do". I've tried to think of different ways to do it, but none of them seem to be better, and I feel as if I'm just trying to make it complicated for the sake of it.
I tried using the 2D array that the values are stored in as a parameter of a function, and then using the function to print out the number of occurences of the particular values, but I couldn't get this to compile as my syntax was wrong for using a 2D array as a parameter, and I'm not too sure about how to do this.
Any help would be appreciated, thanks.

A: Why do you need a couple for loops? one is enough.
Create an array of size 10 where array[0] is marks between 0-9, array[1] is marks between 10-19, etc. When you see a number, put it in the appropriate array bucket using integer division, e.g. array[(int)mark/10]++. when you finish the array will contain the count of the number of marks in each bucket.

A: As food for thought, if this is a school assignment, you might want to apply other things you have learned in the course.
Did you learn sorting yet? Maybe you could sort the list first so that you are not iterating over the array several times. You can just go over it once, grab all the -1's, and spit out how many you have, then grab all the ones in the next bracket and so on.
edit: that is of course, assuming that you are using a 1d array.


text:
Q: CNN model is not learn well I started to learn CNN implementation in PyTorch, and I tried to build CNNs to process the grayscale images with 4 classes from 0 to 3. I got in the beginning accuracy around 0.55. The maximum accuracy I got is ~ 0.683%.
I tried SGD and Adam optimizer with different values for lr and batch_size, but the accuracy is still low.
I used data Augmentation to create more samples, around 4k.
I cannot improve accuracy further and wondered if I could get some advices about what I need to change in CNN structure to increase accuracy.
Loss starts around: Loss: [1.497] then decreases near: Loss: [0.001] then fluctuated up and down around this value.
I spent time reading about similar problems but without luck.
I am using nn.CrossEntropyLoss() for my loss_fn. I don't use softmax for dense layer.
This is the Summary of the CNN model:
-------------------------------------------------------------
        Layer (type)               Output Shape         Param #
=============================================================
            Conv2d-1         [-1, 32, 128, 128]             320
              ReLU-2         [-1, 32, 128, 128]               0
       BatchNorm2d-3         [-1, 32, 128, 128]              64
         MaxPool2d-4           [-1, 32, 64, 64]               0
            Conv2d-5           [-1, 64, 64, 64]          18,496
              ReLU-6           [-1, 64, 64, 64]               0
       BatchNorm2d-7           [-1, 64, 64, 64]             128
         MaxPool2d-8           [-1, 64, 32, 32]               0
            Conv2d-9          [-1, 128, 32, 32]          73,856
             ReLU-10          [-1, 128, 32, 32]               0
      BatchNorm2d-11          [-1, 128, 32, 32]             256
        MaxPool2d-12          [-1, 128, 16, 16]               0
          Flatten-13                [-1, 32768]               0
           Linear-14                  [-1, 512]      16,777,728
             ReLU-15                  [-1, 512]               0
          Dropout-16                  [-1, 512]               0
           Linear-17                    [-1, 4]           2,052
============================================================

I would appreciate the help.

A: How many images are in the train set ? the test set ? What are the size of the images ? How would you consider the difficulty of classification of the images ? Do you think it should be simple or difficult ?
According to the numbers you have, you're overfitting as your loss is near 0 (meaning nothing much will retropropagate to the weights, i.e your model won't change anymore) and your 68.3% (it's a typo right ?) is from the test set (I suppose). So you don't have any problem to train the network which is a good point.
Then you can search ways of countering overfitting online and here is some "classical" possibilities :
- you may raise the dropout parameter
- putting some regularizer (L1 or L2) to constraint the learning
- early stopping using a validation set
- using a classical and/or lighter convolutional network (resnet,inception) with/without pretrained weights. This latter also depends on your images type (natural, biomedical ...)
- ... a lot more or less difficult to implement
Also technically you are using a softmax layer as it's included in the crossentropyloss of pytorch.


text:
Q: Como fazer o PHPMailer e o envio dos valores a um banco de dados MySQL Estou tentando enviar os dados do formulário para um e-mail usando o PHPMailer (isso já está funcionando) e aproveitar para incluir esses dados em uma tabela de banco de dados MySQL.
Não funcionou, imagino que o erro esteja no código.
<?php
// Adiciona o arquivo class.phpmailer.php - você deve especificar corretamente o caminho da pasta com o este arquivo.
require_once("phpmailer/PHPMailerAutoload.php");
// Inicia a classe PHPMailer
$mail = new PHPMailer();

// DEFINIÇÃO DOS DADOS DE AUTENTICAÇÃO - Você deve auterar conforme o seu domínio!
$mail->IsSMTP(); // Define que a mensagem será SMTP
$mail->Host = "smtp.xxx.com.br"; // Seu endereço de host SMTP
$mail->SMTPAuth = true; // Define que será utilizada a autenticação -  Mantenha o valor "true"
$mail->Port = 587; // Porta de comunicação SMTP - Mantenha o valor "587"
$mail->SMTPSecure = false; // Define se é utilizado SSL/TLS - Mantenha o valor "false"
$mail->SMTPAutoTLS = false; // Define se, por padrão, será utilizado TLS - Mantenha o valor "false"
$mail->Username = 'cursos@xxx.com.br'; // Conta de email existente e ativa em seu domínio
$mail->Password = 'juliana2017'; // Senha da sua conta de email

// DADOS DO REMETENTE
$mail->Sender = "cursos@xxx.com.br"; // Conta de email existente e ativa em seu domínio
$mail->From = "cursos@xxx.com.br"; // Sua conta de email que será remetente da mensagem
$mail->FromName = "Form do site"; // Nome da conta de email

// DADOS DO DESTINATÁRIO
$mail->AddAddress('xxx@gmail.com', 'Bruno'); // Define qual conta de email receberá a mensagem
//$mail->AddAddress('recebe2@dominio.com.br'); // Define qual conta de email receberá a mensagem
//$mail->AddCC('copia@dominio.net'); // Define qual conta de email receberá uma cópia
//$mail->AddBCC('copiaoculta@dominio.info'); // Define qual conta de email receberá uma cópia oculta

// Definição de HTML/codificação
$mail->IsHTML(true); // Define que o e-mail será enviado como HTML
$mail->CharSet = 'utf-8'; // Charset da mensagem (opcional)

// DEFINIÇÃO DA MENSAGEM
$mail->Subject  = "Formulário de Contato"; // Assunto da mensagem
$mail->Body .= " Atendimento: ".$_POST['atendimento']."
"; // Texto da mensagem
$mail->Body .= " Curso:        ".$_POST['curso']."
"; // Texto da mensagem
$mail->Body .= " Nome:             ".$_POST['nome']."
"; // Texto da mensagem
$mail->Body .= " Certificado:  ".$_POST['certificado']."
"; // Texto da mensagem
$mail->Body .= " CPF:          ".$_POST['cpf']."
"; // Texto da mensagem
$mail->Body .= " E-mail:       ".$_POST['email']."
"; // Texto da mensagem
$mail->Body .= " Celular:      ".$_POST['celular']."
"; // Texto da mensagem
$mail->Body .= " Outro telefone:" .$_POST['telefone']."
"; // Texto da mensagem
$mail->Body .= " Rua:          ".$_POST['rua']."
"; // Texto da mensagem
$mail->Body .= " Número:       ".$_POST['numero']."
"; // Texto da mensagem
$mail->Body .= " Complemento:  ".$_POST['complemento']."
"; // Texto da mensagem
$mail->Body .= " Bairro:       ".$_POST['bairro']."
"; // Texto da mensagem
$mail->Body .= " Cidade:       ".$_POST['cidade']."
"; // Texto da mensagem
$mail->Body .= " Estado:       ".$_POST['uf']."
"; // Texto da mensagem
$mail->Body .= " CEP:          ".$_POST['cep']."
"; // Texto da mensagem
$mail->Body .= " Como nos conheceu?: ".$_POST['facebook'].", ".$_POST['instagram'].", ".$_POST['google'].", ".$_POST['outrasformas'].", ".$_POST['indicacao']."
"; // Texto da mensagem
$mail->Body .= " Termo: ".$_POST['termo']."
"; // Texto da mensagem
$mail->Body .= "

DADOS PARA O CONTRATO

".$_POST['nome'].", portadora do CPF: ".$_POST['cpf'].", reside no endereço; ".$_POST['rua'].", Nº: ".$_POST['numero'].", ".$_POST['complemento'].", ".$_POST['bairro'].", ".$_POST['cidade'].", ".$_POST['uf'].", CEP: ".$_POST['cep']."";

// ENVIO DO EMAIL
$enviado = $mail->Send();
// Limpa os destinatários e os anexos
$mail->ClearAllRecipients();

// Exibe uma mensagem de resultado do envio (sucesso/erro)
if ($enviado) {
  echo "E-mail enviado com sucesso!";
} else {
  echo "Não foi possível enviar o e-mail.";
  echo "Detalhes do erro: " . $mail->ErrorInfo;
}

////////////// INSERT TO MYSQL ////////
$nome = $_POST['nome'];
$cpf = $_POST['cpf'];
$email = $_POST['email'];
$celular = $_POST['celular'];
$telefone = $_POST['telefone'];
$rua = $_POST['rua'];
$numero = $_POST['numero'];
$complemento = $_POST['complemento'];
$bairro = $_POST['bairro'];
$cidade =  $_POST['cidade'];
$uf = $_POST['uf'];
$cep = $_POST['cep'];
$strcon = mysqli_connect('mysql.xxx.com.br','xxx','juliana2017','xxx') or die('Erro ao conectar ao banco de dados');
$sql = "INSERT INTO clientes (nome, cpf, email, celular, telefone, rua, numero, complemento, bairro, cidade, uf, cep)VALUES ($nome, $cpf, $email',$celular, $telefone, $rua,$numero, $complemento, $bairro,$cidade, $uf, $cep)";
mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro");
mysqli_close($strcon);
echo "Cliente cadastrado com sucesso!";

A: os values devem estar todos entre aspas simples
  .....VALUES ('$nome', '$cpf', '$email', '$celular', '$telefone','$rua', '$numero', '$complemento', '$bairro', '$cidade', '$uf', '$cep')";


text:
Q: How to set @Scheduled for each 30 min and calling sa method with parameters? I have a case where I need to use Scheduled.
This schedule will execute this method every 30 min, so the method is
    @Transactional
    public void processEnable()
            throws Exception
    {
        try
        {

        }
        catch (Exception e)
        {
            logger.warn("[Enable] [STATUS] - ERROR  ");
            logger.warn("[Enable] [EXCEPTION] " + e.getMessage(), e);
            throw e;
        }
    }

and I want to get this method to execute for 30 min
and i am doing this with that.
@Scheduled(cron = "0 0 1-2 * * *")
public void Enable()
{
    try
    {
        Service.Enable();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

but the problem is how to get the parameter here, is my first time, in fact, using @Scheduled and I don't know how it works or how can I get the parameter from the user so I can get this method works each 30 min.
I am having no idea to get the parameter I want.

A: If you want the external objects to be used within your @Scheduled methods, you should inject them into the DemoService class using autowiring rather than passing them as parameters to the @Scheduled methods.

A: In your Scheduled method:

*

*you need to set the user executing the code to get spring security annotations satisfied. So using a system user do:

SecurityContext securityContext= SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);

*get all the authenticated users at the moment the job starts running. See this answer
List<Object> principals = sessionRegistry.getAllPrincipals();

*iterate the list of Authentication objects from the previous step and call processEnableApp (passing the parameters to the method)

A: Your cron expression is wrong. You need this */30 * * * *


text:
Q: Write xml file with elements depending on the type of action to be performed I need to express in xml a list of actions that my program can do. The problem is that some actions need of additional elements and others do not. For example if my program has to perform actions on files: if I delete the only thing that interests me is the path, if the program does the copy... again I need the path, but also a path of destination .. How to write an xml file so structured?

A: Something like this?
<actions>
  <action name="FileCopy">
    <params>
      <param name="SourcePath" value="c:\source.txt"/>
      <param name="DestPath" value="c:\dest.txt"/>
    </params>
  </action>
  <action name="FileDelete">
    <params>
      <param name="DeletePath" value="c:\source.txt"/>
    </params>
  </action>
  <action name="ReloadCache"/>
  <action name="Alert">
   <params>
     <param name="Message" value="Done!"/>
   </params>
  </action>
</actions>

You could of course remove the params level and put param tags directly under the action tag, however the proposed structure will allow to add other types of nodes under the action tag (for example, validation callbacks) without breaking too much things.


text:
Q: Gradle generate Asynce(RPC) and i18n for GWT-projects like as maven-gwt-plugin do Our team wants to migrate a gwt maven project to Gradle.
We use gwt-maven-project as plugin to generate RPC source and i18n messages.
It seems almost none dependable Gradle plug-in like gwt-maven-plugin for gradle project.
Except exec task that call maven command, have another resolution?


text:
Q: How to properly use in_stock in Amazon Forecast related time series I'm trying to understand the data required for Amazon Forecast to create a demand forecast using my historical sales data. I've read through the documentation many times. I am still confused as to how the "in_stock" field in a related time series is supposed to function. Here is a link to the description of the "in_stock" field I am referring to:
https://docs.aws.amazon.com/forecast/latest/dg/retail-domain.html#related-time-series-type-retail-domain
It says:

The following fields are optional and might be useful in improving
  forecast results:

*

*in_stock (integer; 1=true, 0=false) – A flag that specifies whether the item is in stock.

What exactly is this field meant to indicate? Is it only meant to be set to 0 when the number of sales is 0? In other words, if the number of sales for a given day is 0, and in_stock is set to 0, then the system knows the sales were 0 because the product was not available, not because there was no demand.
What if a product goes out of stock halfway through the day. Would that be a case where you might have in_stock = 0 but also have sales on that day?
I am also confused how this in_stock field comes into play when in another piece of their documentation:
https://d1.awsstatic.com/whitepapers/time-series-forecasting-principles-amazon-forecast.pdf?did=wp_card&trk=wp_card
On page 10, they say:

In the retail case study, the information that a retailer sold zero
  units of an available item differs from the information that zero
  units of an unavailable item are sold either in the periods outside
  its existence, e.g. before its launch or after its deprecation, or in
  periods within its existence, e.g. partially out of stock, or when
  there was no sales data recorded for this time range. The default zero
  filling is applicable in this former case. In the latter, even though
  the corresponding target value is typically zero, there is additional
  information conveyed in the value being marked as missing. You must
  preserve the information that there was missing data and not discard
  this information (see the following example for an illustration why
  keeping the information is important). To encode a value that does not
  represent zero sales of an available product as truly missing, Amazon
  Forecast allows the user to specify the filling type for middle fill
  and back fill in the FeaturizationMethodParameters key of the
  FeaturizationConfig parameter of the create_predictor API. To mark a
  value as truly missing, the fill type for these parameters should be
  set to NaN. Unlike for zero filling, the values encoded with NaN are
  treated as truly missing, and not used in the metrics evaluation
  component.

This seems to indicate that when a product is out of stock and there are no sales, those rows should be marked as NaN, which effectively removes those rows from the dataset.
I suppose my questions boils down to:

*

*What is the difference between a day with 0 sales and in_stock = 0 vs a day with sales = NaN, which effectively removes that day from the dataset?

*What do you do when a product goes out of stock partway through the day? Can in_stock = 0 and still have sales data for a given day?

A: *

*The difference is that with in_stock your model includes more information allowing you to do projections based on in_stock into the future. It's better to use in_stock as opposed to sales = NaN as long as you have the historical data.

*If you require in_stock to be represented as a partial day, your time series will need to be more granular. If you can't achieve more granularity you should be able to specify sales > 0 and in_stock = 0, all this will do is train the model, for that Id, that when an item is out of stock a certain amount of sales are made hence it is better to have a more granular time series.

A: For this use case the recommendation would be to specify sales = 'NaN' in the TARGET_TIME_SERIES when a particular product is unavailable / out-of-stock. This is as per the approach outlined in: https://d1.awsstatic.com/whitepapers/time-series-forecasting-principles-amazon-forecast.pdf. The example in Figure 6 (on page 11) elaborates on this further. For cases where a product goes out of stock part way through the day, the sales value should be specified.
It is also worth noting that at the time of this writing, RELATED_TIME_SERIES in Amazon Forecast requires the last timestamp for every item in the related time series dataset must be on or after the last timestamp in the target time series plus the user-designated forecast window (called the forecast horizon). See: https://docs.aws.amazon.com/forecast/latest/dg/related-time-series-datasets.html for additional details.
Hope this helps.


text:
Q: how to convert api respons ekey value in camelcase I am getting some api response , where I have to change all key value is camelcase ..
like below I am getting response  . i have to convert all key is small .
like CBSServiceResponseDtls = cBSServiceResponseDtls same for all keys .
Dont want to change any of value  And few of keys has _ .
Like "API_OUTPUT" I have to change in apiOutput.
Please help. Thanks
{
   "CBSServiceResponseDtls":{
      "Response":{
         "ResultStatus":{
            "ResultCode":0,
            "ResultMessage":"SUCCESS"
         },
         "Data":{
            "EVENT":{
               "API_OUTPUT":{
                  "SUCCESS_FLAG":0,
                  "REQUEST_STATUS":0,
                  "ABILLITY_REF_NUM":32038,
                  "RESPONSE_ERROR_CODE":"",
                  "SUCCESS_MESG_LANG_1":"Request has been Processed Successfully",
                  "SUCCESS_MESG_LANG_2":"Request has been Processed Successfully",
                  "TRANSACTION_LOG_REFERNCE":2.0200507064507202e+27
               },
               "LOGIN_DETAILS":{
                  "LOGIN_DTLS":[
                     {
                        "LOGIN_NAME":"soban",
                        "LOCATION_CODE":"WAREHOUSE",
                        "LOCATION_CODE_NO":1,
                        "LOCATION_DESC":"WAREHOUSE",
                        "DEFAULT_FLAG":"Y"
                     },
                     {
                        "LOGIN_NAME":"soban",
                        "LOCATION_CODE":"BTP",
                        "LOCATION_CODE_NO":70,
                        "LOCATION_DESC":"BTP",
                        "DEFAULT_FLAG":"N"
                     }
                  ]
               }
            }
         }
      }
   }
}

A: Simple solution, You can use regex replace/transform function to change all keys.
More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
CamelCase Sample:

const toCamelCase = (str = "") => {
  const [first, ...rest] = str.split("_");
  return (
    first.toLowerCase() +
    rest
      .map((word) => {
        word = word.toLowerCase();
        return word.slice(0, 1).toUpperCase() + word.slice(1);
      })
      .join("")
  );
};
const tranform = (m) =>
  m.indexOf("_") === -1
    ? m.slice(0, 1).toLowerCase() + m.slice(1)
    : toCamelCase(m);
const formatJson = (obj) => {
  const jsonString = JSON.stringify(obj).replace(
    /\"(\w+)\":/g,
    (_, m) => `"${tranform(m)}":`
  );
  return JSON.parse(jsonString);
};
const data = {"CBSServiceResponseDtls":{"Response":{"ResultStatus":{"ResultCode":0,"ResultMessage":"SUCCESS"},"Data":{"EVENT":{"API_OUTPUT":{"SUCCESS_FLAG":0,"REQUEST_STATUS":0,"ABILLITY_REF_NUM":32038,"RESPONSE_ERROR_CODE":"","SUCCESS_MESG_LANG_1":"Request has been Processed Successfully","SUCCESS_MESG_LANG_2":"Request has been Processed Successfully","TRANSACTION_LOG_REFERNCE":2.0200507064507202e+27},"LOGIN_DETAILS":{"LOGIN_DTLS":[{"LOGIN_NAME":"soban","LOCATION_CODE":"WAREHOUSE","LOCATION_CODE_NO":1,"LOCATION_DESC":"WAREHOUSE","DEFAULT_FLAG":"Y"},{"LOGIN_NAME":"soban","LOCATION_CODE":"BTP","LOCATION_CODE_NO":70,"LOCATION_DESC":"BTP","DEFAULT_FLAG":"N"}]}}}}}}
const json = formatJson(data);
console.log("%j", json);

A: You can use this helper function to do it recursively:
function objToLowerCase(obj) {
     if (Array.isArray(obj)) {
        return obj.map((entry) => typeof entry !== "object" ? entry : objToLowerCase(entry));
     }
     const newObj = Object.entries(obj).reduce((obj, [key, value]) => {
    const newKey = key.toLowerCase().split("_").join("");
    const newValue = typeof value !== "object" ? value : objToLowerCase(value);
    obj[newKey] = newValue;
    return obj;
  }, {});
  return newObj;
}

Here is a sandbox.
To make it camelCase, you could use this function:
function toCamelCase(str) {
  if (str === str.toUpperCase()) {
    return str
      .toLowerCase()
      .split("_")
      .map((s, i) =>
        i === 0 ? s : s.slice(0, 1).toUpperCase() + s.slice(1, s.length)
      )
      .join("");
  } else {
    return str.slice(0, 1).toLowerCase() + str.slice(1);
  }
}

and call it like this:
function objToLowerCase(obj) {
     if (Array.isArray(obj)) {
        return obj.map((entry) => typeof entry !== "object" ? entry : objToLowerCase(entry));
     }
     const newObj = Object.entries(obj).reduce((obj, [key, value]) => {
    const newKey = toCamelCase(key)
    const newValue = typeof value !== "object" ? value : objToLowerCase(value);
    obj[newKey] = newValue;
    return obj;
  }, {});
  return newObj;
}


text:
Q: Hylafax+Ubuntu unreliable under KVM We have an Hylafax 5.2.5 CentOS 5 installation hosted inside a Xen
virtual machine. It works quite well, but now I'm in the process of
upgrading/migrating it to a KVM virtual machine running Ubuntu 10.04 and
Hylafax 5.5.1 (compiled from source using
http://sourceforge.net/projects/hylafax/files/hylafax%20debian%20build%20files/
)
The problem I'm having is that - while receiving works fine - sending
faxes is extremely unreliable, I get lots of "No response to MPS
repeated 3 tries", or "Failure to transmit clean ECM image data."
The line, modem and configuration files I'm using are the same as
before, so I thought that it could be a KVM scheduling issue, but even
setting cpu_shares to 10240 instead of 1024 doesn't change a thing...
What else could I try?
Here's an example log file http://pastebin.com/cN01cpEs

A: I would suggest you first verify your rs232 subsystem is up to spec, eg by sending data through the virtualised serial port out the physical connection to another machine and looking for stalls and/or data errors. Also, try fiddling with the baud rate.
I hate to suggest twice in a week on SE that someone find an oscilloscope, but it can be very revealing with RS232 problems...


text:
Q: Power Bi Custom Column funtion In MQuery, I'm trying to create a custom column.  If another column has a value of 1 through 5 then the value in new column will be some text.  It's given me a Token Else expected error.
=if[#"Chair Independence Level"] = "1" then "Same Product Line"
else if[#"Chair Independence Level"]= "2" then "Different Product Line"
else if[#"Chair Independence Level"]= "3" then "Different Business Area"
else if[#"Chair Independence Level"]= "4" then "Different Sector"
else if [#"Chair Independence Level"]= "5" then "Not an Employee"

Does anyone know how to fix the problem or what I should change my code to?

A: The IF condition in Power query needs to be capped off with an ELSE statement. Just add the ELSE and you should be good to go:
=if[#"Chair Independence Level"] = "1" then "Same Product Line"
else if[#"Chair Independence Level"]= "2" then "Different Product Line"
else if[#"Chair Independence Level"]= "3" then "Different Business Area"
else if[#"Chair Independence Level"]= "4" then "Different Sector"
else if [#"Chair Independence Level"]= "5" then "Not an Employee"
else "NA"

If the #"Chair Independence Level" field is numeric, then:
=if[#"Chair Independence Level"] = 1 then "Same Product Line"
else if[#"Chair Independence Level"]= 2 then "Different Product Line"
else if[#"Chair Independence Level"]= 3 then "Different Business Area"
else if[#"Chair Independence Level"]= 4 then "Different Sector"
else if [#"Chair Independence Level"]= 5 then "Not an Employee"
else "NA"

A: You are working on the mQuery side of powerby so no DAX.
You are missing your last else statement:
else if [#"Chair Independence Level"]= "5" then "Not an Employee" ELSE "the other"


text:
Q: Is a conditional expectation with two conditioning variables equal to zero? Question: Let $X$, $Y$ and $Z$ be three random variables on the same probability space. If $E(X|Y) = 0$ and $E(X|Z) = 0$, does it necessarily follow that $E(X|Y,Z) = 0$?
Discussion: I thought this would be easy to demonstrate with the law of total expectation, but that only seems to imply that $E(E(X|Y,Z)) = 0$.

A: No, try $(Y,Z)$ independent and centered and $X=YZ$. Then $\mathbb E(X\mid Y)=Y\mathbb E(Z)=0$ and $\mathbb E(X\mid Z)=Z\mathbb E(Y)=0$ but $\mathbb E(X\mid Y,Z)=YZ$ which is not zero in general.
Indeed, $\mathbb E(\mathbb E(X\mid Y,Z))=0$, always, since $\mathbb E(\mathbb E(X\mid Y,Z))=\mathbb E(X)$ and, by hypothesis, $\mathbb E(X\mid Y)=0$ hence $\mathbb E(X)=\mathbb E(\mathbb E(X\mid Y))=0$.


text:
Q: Get user banner in discord.js Is there any way to obtain user banner on discord using discord.js? User banner is new feature, so I am not sure if there is any way so far. I didn't find anything in docs. Eg. server banner is available on:
https://cdn.discordapp.com/banners/GUILD_ID/GUILD_BANNER.png.
Something similar for user banner would be great.

A: I managed to recover a discord banner after several hours of development, the code below :
( you need to install "node-fetch" => npm i node-fetch )
const fetch = require('node-fetch')

let uid = "user_id"

let response = fetch(`https://discord.com/api/v8/users/${uid}`, {
    method: 'GET',
    headers: {
        Authorization: `Bot ${client.token}`
    }
})

let receive = ''
let banner = 'https://cdn.discordapp.com/attachments/829722741288337428/834016013678673950/banner_invisible.gif' // invisible image ( you can change the link if you want )

response.then(a => {
if(a.status !== 404) {
a.json().then(data => {
receive = data['banner']

if(receive !== null) {

let format = 'png'
if(receive.substring(0,2) === 'a_') {
format = 'gif'
}

banner = `https://cdn.discordapp.com/banners/${uid}/${receive}.${format}`

}})

.setTimeout(() => {

// To retrieve the value "banner" we put a timeout otherwise it will return us the first definition of "banner" that is to say the invisible image, I let you modify the code as you wish, good evening to you (and also I just wanted to make it clear I'm French)

// Put the rest of your code here :

}, 1000)

A: Simple solution
The simplest solution for discord.js v12 I came up with:
async function getUserBannerUrl(userId) {
    const user = await client.api.users(userId).get();
    return user.banner ? `https://cdn.discordapp.com/banners/${userId}/${user.banner}?size=512` : null;
}

However this doesn't handle mime types well. You don't know what the mime type is unless you read the content-type header. This may break some things that require you to have a file extension in your URL. That's why I came up with more complex solution.
Complex solution
The code below is dependent on axios.
const axios = require("axios");

async function getUserBannerUrl(userId, { dynamicFormat = true, defaultFormat = "webp", size = 512 } = {}) {

    // Supported image sizes, inspired by 'https://discord.js.org/#/docs/main/stable/typedef/ImageURLOptions'.
    if (![16, 32, 64, 128, 256, 512, 1024, 2048, 4096].includes(size)) {
        throw new Error(`The size '${size}' is not supported!`);
    }

    // We don't support gif as a default format,
    // because requesting .gif format when the original image is not a gif,
    // would result in an error 415 Unsupported Media Type.
    // If you want gif support, enable dynamicFormat, .gif will be used when is it available.
    if (!["webp", "png", "jpg", "jpeg"].includes(defaultFormat)) {
        throw new Error(`The format '${defaultFormat}' is not supported as a default format!`);
    }

    // We use raw API request to get the User object from Discord API,
    // since the discord.js v12's one doens't support .banner property.
    const user = await client.api.users(userId).get();
    if (!user.banner) return null;

    const query = `?size=${size}`;
    const baseUrl = `https://cdn.discordapp.com/banners/${userId}/${user.banner}`;

    // If dynamic format is enabled we perform a HTTP HEAD request,
    // so we can use the content-type header to determine,
    // if the image is a gif or not.
    if (dynamicFormat) {
        const { headers } = await axios.head(baseUrl);
        if (headers && headers.hasOwnProperty("content-type")) {
            return baseUrl + (headers["content-type"] == "image/gif" ? ".gif" : `.${defaultFormat}`) + query;
        }
    }

    return baseUrl + `.${defaultFormat}` + query;

}

Example usage
Implementing simple !banner command, that will show the message sender's banner.
client.on("message", async (message) => {

    if (message.author.bot) return;

    if (message.content == "!banner") {
        const bannerUrl = await getUserBannerUrl(message.author.id, { size: 4096 });
        if (bannerUrl) {
            const embed = new Discord.MessageEmbed()
                .setTitle(`${message.author.username}'s banner`)
                .setDescription("Look at my banner, how cool is that?")
                .setImage(bannerUrl);
            message.channel.send(embed);
        } else {
            message.channel.send("You don't have money to buy Discord Nitro... How sad...");
        }
    }

});

A: According to a response to this GitHub issue and the official documentation, there is no current way to read the user bio and banner.
As Tyler stated, the feature is still in beta. Once added, you should be able to serialize the banner image hash on the user object, thus allowing bots to receive the field passively.

A: You can get the discord user banner with discord-banner npm package
Its so easy to use it and allow you to get it for now without Discord.js v13


text:
Q: BouncyCastle Error I am developing an android application. In this application I create my own private key by passing pass phrase, user id and keys. When creating the private key, it says "Error: org.bouncycastle.openpgp.PGPException: cannot create cipher: CAST5/CFB/NoPadding"
I have checked the logcat as well as the warning section in the Eclipse but there is error there. SO why I am getting this error and how to solve it.
Any help is greatly appreciated!
I am using bcpg-jdk15on-150.jar and bcprov-jdk15on-150.jar,
which I have downloaded from http://www.bouncycastle.org/latest_releases.html
EDIT
the solution of renaming one or both the jar files does not work. When I run the application it says Unable to execute dex: Multiple dex files define Lorg/bouncycastle/apache/bzip2/BZip2Constants;
and Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lorg/bouncycastle/apache/bzip2/BZip2Constants;
I think there is a problem with the duplication of some files within the two jar files. Can anyone suggest me a solution regarding this?
Thanks

A: Use latest BouncyCastle and setup security in your code in the following way:
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    Security.insertProviderAt(new BouncyCastleProvider(), 1);

It sets Bouncy Castle library as preferred security provider; Android's default provider config has BC at position 3 so this code will remove it and insert BC again at position 1.
It solved the problem for me.


text:
Q: Trying to distribute images evenly with css Im trying to create a slide of small images and that on each slide the images are evenly distributed horizontally. Found an interesting technique on css-tricks.com and a very straighforward working example but i haven't been able to replicate it.
Here's the html of a slide

Here's the css following the mentioned technique
div.sites .carousel-inner .item div {
  font-size: 0.1px;
  text-align: justify;
}

div.sites .carousel-inner .item div:after {
  content: "";
  width: 100%;
  display: inline-block;
}

div.sites .carousel-inner .item div a {
  display: inline-block;
}

You can see the code working at the bottom of this site, under the title "OTROS SITIOS"
EDIT: My girlfriend tried my code in CodePen and it worked nicely. im guessing it must be some global style that's interfering with it.
Thanks for your help

A: I copied the html structure starting from the div sites and pasted it on CodePen alongside with your proposed css code.
I saw that you missed the escape character between the  and
When I added it, the code worked perfectly :)


text:
Q: How can I detemine the parameters needed by the_widget()? I'm working with an old (now unmaintained) widget, which only allows one instance.
Since I want to have a different sidebar on the homepage and I want this widget on both sidebars, I figure I need to do one of two things:

*

*Update the plugin to use the new widget API

*Use the_widget() to manually drop the widget into the custom sidebar

I've opted to do the latter as a quick fix, but can't figure out the parameters needed to get it to display.
Any suggestions would be greatly appreciated.

A: If you don't need to change any of the settings for the widget, you may be able to use the Duplicate Widget widget.

A: Take a look at the official documentation.
Furthermore: If you really want help in detail, you'll have to provide much more information (pastebin or similar link to code) in your Q.


text:
Q: Custom ProjectSchemaDefinitions in Project Property Sheet I finally managed to configure my Visual Studo C++ Project to show my Custom ProjectSchemaDefinition if I take a look at a Single Project->Property.

My Question:
Is there any way to show this in a Shared Project Property (eg external.props) ?
My current shared.targets configuration
<PropertyGroup Label="Import Settings">
    <UseDefaultProjectTools>true</UseDefaultProjectTools>
    <UseDefaultPropertyPageSchemas>true</UseDefaultPropertyPageSchemas>
    <UseDefaultGeneralPropertyPageSchema>true</UseDefaultGeneralPropertyPageSchema>
</PropertyGroup>
<ItemGroup>
    <PropertyPageSchema Include="$(SolutionDir)\props\PublishConfig.xml">
        <Context>Project</Context>
    </PropertyPageSchema>
    <ProjectTools Include="PublishConfig" />
</ItemGroup>

I think I miss just the right Context in this definition but cannot find any reliable source at msdn where different Context Targets are correctly described.
Thank you in advance


text:
Q: MongoDB Mongoose How to delete an object from an array var UserSchema = new mongoose.Schema({
   //Irrelevant code
   profile:
   {
    requests: [{ sender: String, id: String,  hasSelected: Boolean, value: Boolean}]
   }
});

That object is to keep track of friend request, I want it to get completely deleted from the requests array once it has been accepted or declined. I have tried a whole bunch of stuff but nothing is deleting it. Currently have this code:
User.updateOne({ id: user.id },
              { "$pull": { "profile": { "requests": { "id": targetId } } }  },
              { "multi": true },
              function(err,status) {
                if(err){console.log("Could not delete the friend request");}
                else{
                  console.log("Sucessfully deleted friend request from: " + user.name);}
               }
              );

It always says it was deleted on the log, but when I check on mongoDB the request is still there.

A: try $elemMatch to remove the specific object.
 User.updateOne(
 { id: user.id },
 { $pull: { "profile.requests": { $elemMatch: { id: targetId } } } },
 { multi: true },
 function (err, status) {
 if (err) {
  console.log("Could not delete the friend request");
  } else {
  console.log("Sucessfully deleted friend request from: " + user.name);
 }
 }
 );


text:
Q: The simplest way to get custom field id dynamically in Lightning I have a lightning component where I need to display link to related list of children relationship record for given custom object record.
Since I developed this application on sandbox, I can't hardcode this link since it will change after I deploy this application to production. So I was thinking of building the link dynamically by dynamically retrieving the custom field id.
This is short version of Lightning component
<aura:component controller="LEXCont">
    <aura:attribute name="relatedLinkPrefix" type="String" />
    <aura:attribute name="projectId" type="String" />
    Related months
</aura:component>

These are two methods from LEXCont class
static String restGet(String endPoint, String method, String sid) {
    Http h = new Http();
    HttpRequest hr = new HttpRequest();
    hr.setHeader('Authorization', 'Bearer ' + sid);
    hr.setTimeout(60000);
    hr.setEndpoint(endPoint);
    hr.setMethod(method);
    HttpResponse r = h.send(hr);
    return r.getBody();
}

@AuraEnabled
public static String getRelatedDebugLink() {
    try{
        String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
        String monthObjectId = restGet( baseURL + '/services/data/v38.0/tooling/query?q=select+Id+from+CustomObject+where+DeveloperName+=+\'Month\'', 'GET', UserInfo.getSessionId() );
        monthObjectId = monthObjectId.substringAfter('"Id":"').substringBefore('"');
        String projectLookupFieldId = restGet( baseURL + '/services/data/v38.0/tooling/query?q=select+Id+from+CustomField+where+TableEnumOrId=\'' + monthObjectId + '\'AND+DeveloperName=\'Project\'', 'GET', UserInfo.getSessionId() );
        projectLookupFieldId = projectLookupFieldId.substringAfter('"Id":"').substringBefore('"');
        return '/' + Month__c.sobjecttype.getDescribe().getKeyPrefix() + '?rlid=' + projectLookupFieldId + '&id=';
    } catch( Exception ex ){
        throw new AuraHandledException( ex.getMessage() );
    }
}

In this code I am trying to execute two Tooling API queries: the first one
Select Id from CustomObject where DeveloperName = 'Month'

to get custom Object Id and the next one
select Id from CustomField where TableEnumOrId=:monthObjectId AND DeveloperName='Project'

to get the actual custom field Id.
Since we can't run query on CustomField and CustomObject objects directly, I had to use REST API to make these queries.
I mean I can't just write inline queries like
SObject cs = [ select id from CustomObject ];

or
SObject cf = [ select id from CustomField ];

because if I try to do that I will receive error message
sObject type 'CustomObject' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names.

and
sObject type 'CustomField' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names.

correspondingly, because CustomObject and CustomField object are only exposed for Tooling API.
The code for getRelatedDebugLink method works fine if I use it from Anonymous Execution window or from Visualforce page but doesn't work for Lightning, since Lightning Session ID doesn't have to full access to Salesforce API.
When I run the same code from Anonymous execution window, I got the result custom field id but when I run this in Lightning, I receive error
This session is not valid for use with the REST API

I know that I could use some additional visualforce page proposed in this answer
<apex:page>
    Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>

which would give me full-access session id or I could hardcode my username and password and perform SOAP login to get full-access session id, however it would be too complex. I wonder if there is any concise or elegant solution to this

A: Today I have discovered that there are FieldDefinition and EntityDefinition objects in Salesforce which are not only available for using in Tooling API but also generally available for inline queries and for Lightning Controllers.
So by using this object and making query
select DurableId from FieldDefinition where EntityDefinition.label = 'Month' and label = 'Project'

I can avoid making callout to REST API, rewriting my method as follows:
@AuraEnabled
public static String getRelatedDebugLink() {
    try{
        String projectLookupFieldId = [ select DurableId from FieldDefinition where EntityDefinition.label = 'Month' and label = 'Project' ].DurableId.substringAfter('.');
        return '/' + Month__c.sobjecttype.getDescribe().getKeyPrefix() + '?rlid=' + projectLookupFieldId + '&id=';
    } catch( Exception ex ){
        throw new AuraHandledException( ex.getMessage() );
    }
}


text:
Q: Why do i get a NullPointerException when I have checked for the the String not being null? My app crashes on a NPE even though i'm checking whether the value of the String is non null:
  if (AppConstants.AppConstants_appName != null &&
            AppConstants.AppConstants_appName.equals("xxx")) {
            suffix = "version=1.0";
        }

AppConstants_appName is a public static String.
Not sure what's going wrong here.
Here's my Stacktrace. Anyone an idea?
Stacktrace
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at nl.onlineretailservice.library.APIManager.getURLSuffix(APIManager.java:637)
at nl.onlineretailservice.library.APIManager.requestFolderProducts(APIManager.java:334)
at nl.onlineretailservice.helper.FolderViewerActivityHelper.loadProducts(FolderViewerActivityHelper.java:160)
at nl.onlineretailservice.helper.FolderViewerActivityHelper$2.downloadReady(FolderViewerActivityHelper.java:267)
at nl.onlineretailservice.library.DownloadOperation.onPostExecute(DownloadOperation.java:221)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)


text:
Q: I'm having some issues to see some flags dynamically added on the highcharts I'm having an issue when I add flags dynamically to a Highcharts chart. The thing is that when I do so, the flags are not drawn on the chart until I do something that makes the chart refresh (for example, drag the mouse over some button with a tooltip).
I've noticed that this has something to do with the fact that I add the flags inside a point's click event.
point: {
   events: {
      'click': function() {}
   }
}

I assume this is the case since when I add flags to the chart in other parts of the code they appear instantly.
What could be the reason of this behavior?


text:
Q: Mysql query to select record having same artistID but different CDID I am trying to display the artist details once the album is selected. But at the same the other albums related to the artist should displayed too. Are there any way to achieve this.

The left column is the CDID and the right column is the artistID.
This is my current mysql code:
<?php

require "pdoDB.php";
$albumtitle = $_GET['title'];
$db = database::connect();
$artistsql = "SELECT a.artistName, p.pubName, cd.CDTitle FROM tiptop_artist a
             INNER JOIN tiptop_artistcd acd ON a.artistID = acd.artistID
             INNER JOIN tiptop_cd cd ON cd.CDID = acd.CDID
             INNER JOIN tiptop_publisher p ON p.pubID = cd.pubID
             WHERE cd.CDTitle = ?";
$stmt = $db->prepare($artistsql);
// $stmt->bindParam("catid", $categoryid);
$stmt->execute(array($albumtitle));

echo "

Artist Name
Publisher
Other Album

";

while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "
";
    // echo "" . $row1['artistName'] . "	";
    echo "" . $row['artistName'] . "	";
    echo "" . $row['pubName'] . "	";
    echo "" . $row['CDTitle'] . "	";
    echo "
";
}

?>

The final output should obtain something like this:
artist name | publisher | related albums by the artist
------------------------------------------------------
hardwell    | sony music| I am hardwell
                        | Spaceman

Thank you in advance.

A: There are a few ways you can accomplish this in a single query or in multiple queries. You may at one point need to compare different query strategies to see which is the most performant though.
(Note: In the example below, you'll probably want to add a check after the first query to ensure it returns results before running the second query.)
Here's an example using two queries:
$sql = "SELECT artist.name as 'artist.name',
               artist.id as 'artist.id',
               publisher.name as 'publisher.name',
               cd.title as 'cd.title',
               cd.id as 'cd.id'
        FROM tiptop_cd as cd
        INNER JOIN tiptop_artistcd as artistcd ON(artistcd.cd_id = cd.id)
        INNER JOIN tiptop_artist as artist ON(artist.id = artistcd.artist_id)
        INNER JOIN tiptop_publisher as publisher ON(publisher.id = cd.publisher_id)
        WHERE cd.title = :title";

$stmt = $db->prepare($artistsql);
$stmt->bindParam(":title", $_GET['title']);
$stmt->execute();
$details = $stmt->fetch(PDO::FETCH_ASSOC);

$sql = "SELECT cd.title as 'cd.title'
        FROM tiptop_artistcd as artistcd
        INNER JOIN tiptop_cd as cd ON(cd.id = artistcd.cd_id AND cd.id != :cd_id)
        WHERE artistcd.artist_id = :artist_id";

$stmt = $db->prepare($artistsql);
$stmt->bindParam(":artist_id", $details['artist.id']);
$stmt->bindParam(":cd_id", $details['cd.id']);
$stmt->execute();

echo "
".
     "
".
     "Artist Name	".
     "Publisher	".
     "Other Album	".
     "
".

     "
".
     "".$details['artist.name']."	".
     "".$details['publisher.name']."	".
     "".$details['cd.title']."	".
     "
";

while ($album = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "
";
    echo "	";
    echo "	";
    echo "" . $album['cd.title'] . "	";
    echo "
";
}

echo "</table";

Here's a single query version:
SELECT artist.name as 'artist.name',
       publisher.name as 'publisher.name',
       cd.title as 'cd.title',
       albums.title as 'albums.title'
FROM tiptop_cd as cd
INNER JOIN tiptop_artistcd as artistcd ON(artistcd.cd_id = cd.id)
INNER JOIN tiptop_artist as artist ON(artist.id = artistcd.artist_id)
INNER JOIN tiptop_publisher as publisher ON(publisher.id = cd.publisher_id)
INNER JOIN tiptop_artistcd as artistcd2 ON(artistcd2.artist_id = artist.id)
INNER JOIN tiptop_cd as albums ON(albums.id = artistcd2.cd_id)
WHERE cd.title = :title

Here's another clever (and possibly more performant) way to do it in a single query. The first row returned will contain your details and current selected cd, and the remaining rows the other albums:
SELECT artist.name as 'artist.name',
       publisher.name as 'publisher.name',
       cd.title as 'cd.title',
       IF(cd.title = :title, 1, 0) as selected
FROM tiptop_cd as cd
INNER JOIN tiptop_artistcd as artistcd ON(artistcd.cd_id = cd.id)
INNER JOIN tiptop_artist as artist ON(artist.id = artistcd.artist_id)
INNER JOIN tiptop_publisher as publisher ON(publisher.id = cd.publisher_id)
ORDER BY selected DESC


text:
Q: Error in table: all arguments must have the same length I am trying to use naiveBayes to fit and classify a data with binary (location=3 or not) outcome and assess its performance on test data by resampling.
I got an error code:
Error in table(train$prog, trainPred) :
all arguments must have the same length
Here is my reproducible code:
wifiDat <- read.table("wifi_localization.txt",sep="\t")
colnames(wifiDat)
dim(wifiDat)
summary(wifiDat)
head(wifiDat)
colnames(wifiDat) <- c("WF1", "WF2", "WF3", "WF4", "WF5", "WF6",  "WF7", "RM")
wifiDat$RM <- factor(wifiDat$RM)
library(e1071)
wifiDat$RM <- factor(wifiDat$RM)
set.seed(1)
row.number = sample(1:nrow(wifiDat), 0.25*nrow(wifiDat))
train = wifiDat[row.number,]
test = wifiDat[-row.number,]
NBclassfier=naiveBayes(RM~WF1+WF2+WF3+WF4+WF5+WF6+WF7, data=train)
print(NBclassfier)
printALL=function(model){
trainPred=predict(model, newdata = train, type = "class")
trainTable=table(train$prog, trainPred)
testPred=predict(NBclassfier, newdata=test, type="class")
testTable=table(test$prog, testPred)
trainAcc=(trainTable[1,1]+trainTable[2,2]+trainTable[3,3])/sum(trainTable)
testAcc=(testTable[1,1]+testTable[2,2]+testTable[3,3])/sum(testTable)
message("Contingency Table for Training Data")
print(trainTable)
message("Contingency Table for Test Data")
print(testTable)
message("Accuracy")
print(round(cbind(trainAccuracy=trainAcc, testAccuracy=testAcc),3))
}
printALL(NBclassfier)

Here is my sample data
V1. V2. V3. V4. V5. V6. V7. V8
-64 -56 -61 -66 -71 -82 -81 1
-68 -57 -61 -65 -71 -85 -85 2
-63 -60 -60 -67 -76 -85 -84 3
-61 -60 -68 -62 -77 -90 -80 4
-63 -65 -60 -63 -77 -81 -87 1
-64 -55 -63 -66 -76 -88 -83 1
-65 -61 -65 -67 -69 -87 -84 2
-61 -63 -58 -66 -74 -87 -82 3
-65 -60 -59 -63 -76 -86 -82 4
-62 -60 -66 -68 -80 -86 -91 1
-67 -61 -62 -67 -77 -83 -91 1
-65 -59 -61 -67 -72 -86 -81 1
-63 -57 -61 -65 -73 -84 -84 1

Please how can I fix the error?

A: If you look at the traceback of your error, you should see that the issue lies in the table(train$prog, trainPred) part of your function. The base::table() function requires you to provide objects of the same length for the ... argument, as
Stepping through your custom function, you'll see that the length of trainPred is 3, and train$prog doesn't exist (and all columns of train are of length 10 anyway). Hence the error.
Are you missing a step somewhere?