text:
Q: OpenCV mask unwanted peaks I have a problem with the contour, i.e. the mask I get after that. I am bothered by all the peaks, I marked them with a red circle, which remain after the graph. Is there any easy way to get rid of them?

h, w = img.shape[:2]
mask = np.zeros((h, w), np.uint8)

# Transform to gray colorspace and threshold the image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# Search for contours and select the biggest one and draw it on mask
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cntsSorted = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)

for n in range(0,2):
    cnt = cntsSorted[n]
    cv2.drawContours(mask, [cnt], 0, 255, -1)

    # Perform a bitwise operation
    color = cv2.bitwise_and(img, img, mask=mask)
    x, y, w, h = cv2.boundingRect(cnt)
    crop = color[y:(y + h)-3, x+3:x + w]


text:
Q: Applying Euler's formula for limit of $\frac{\sin(x)}x$ as x approaches $0$ in exponential form I'm currently studying Euler's formula and the representation of
$\frac{\sin(x)}x$ as $\frac{1}{2ix}(e^{ix}-e^{-ix})$
and my understanding would be taking the limit as $x$ approaches $0$ would be
$$\lim_{x\rightarrow0} \frac{1}{2ix}(e^0-e^{-0})$$
which I believe is not right
I think I'm asking two questions:

*

*Clarity of Euler's formula (I sort of understanding it from the
series derivation but in practice I don't understand this at all)

*Clarity on taking the limit for the real numbers using  this complex representation

Edit: Just wanted to say thank you to everyone who commented, all the answers were very helpful!

A: Euler's formula states that $e^{ix}=\cos(x)+ i\sin(x)$ for any real number $x$, where $ i=\sqrt{-1}$ is the imaginary unit (see 1 and 2). It can obtained from the Maclaurin series expansions of $\cos(x)$, $\sin(x)$ and $e^x$.  Then we have
$$\frac{e^{ix}-e^{-ix}}{2xi}=\frac{\cos(x)+ i\sin(x)-(\cos(-x)+i\sin(-x))}{2xi}=\frac{2i\sin(x)}{2xi}=\frac{\sin(x)}{x}$$
since $\cos(x)$ is an even function and $\sin(x)$ is an odd function.

It is well know that $\lim_{x\rightarrow 0}\frac{\sin(x)}{x}=$ $1$. If you want to start from the other definition we have
$$\lim_{x\rightarrow 0}\frac{e^{ix}-e^{-ix}}{2ix}=\lim_{x\rightarrow 0}\frac{\left(1+ix-\frac{x^2}{2}+...\right)-\left(1-ix-\frac{x^2}{2}+...\right)}{2ix}=\lim_{x\rightarrow 0}\frac{2ix+...}{2ix}=1$$
by power series expansion. You can also use L'Hopital's rule.

A: We have that by standard limit $\frac{e^x-1}x \to 0$ as $x \to 0$ we obtain
$$\frac{\sin x}x=\frac{e^{ix}-e^{-ix}}{2xi}=\frac1{e^{ix}}\frac{e^{2ix}-1}{2ix}\to 1\cdot 1=0$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve the failed connection reason from NEVPNManager? I'm trying to establish an IKEv2 connection on iOS using the NEVPNManager.
I update my profile successfully using NEVPNProtocolIKEv2 and start the connection process but after a few seconds the connection stops without any error.
Is there any way I can get more information about the connection to see why it failed? There does not appear to be anything helpful in the NEVPNManager object.
https://developer.apple.com/documentation/networkextension/nevpnconnection?language=objc


text:
Q: How to crop rectangle image to square? In this code, the items in the grid is displayed as square, but the image is squished. Some of these images are rectangular shape, I want to crop it into a square to fit into this grid.
struct GalleryView: View {
    @State private var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9].shuffled()

    let columns = [
        GridItem(.adaptive(minimum: 100, maximum: 1000)),
        GridItem(.adaptive(minimum: 100, maximum: 1000))
    ]

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(arr, id: \.self) { id in
                    Image("test\(id)")
                        .resizable()
                        .aspectRatio(1, contentMode: .fit)
                        .clipShape(Rectangle())   //this has 0 effect
                        .cornerRadius(20)
                        .listRowSeparator(.hidden)
                }
            }
            .padding(.horizontal)
        }
    }
}

Note that the challenge is to not set a custom size for the cell but let it take as much space as needed in the grid while maintaining the square aspect ration and crop.

A: The answer seems to be:
Color.blue
                        .aspectRatio(1, contentMode: .fill)
                        .overlay(
                            Image("test\(id)")
                                .resizable()
                                .scaledToFill()
                        )
                        .clipped()


text:
Q: How do I convert a uniform value in [0,1) to a standard normal (Gaussian) distribution value? I have uniform value in [0,1). I'd like to transform it into a standard normal distribution value, in a deterministic fashion.
What I'm confused about with the Box-Muller transform is that it takes two uniform values in [0, 1), and transform them into two normal random values.
However, I only have one uniform value. How do I apply Box-Muller over a single value?

A: Use the inverse transform method.

A: Given one uniform value in [0,1) you can use alternate digits to get two uniform values.  Or alternate bits.
Some other methods to generate standard gaussians are here:
http://en.wikipedia.org/wiki/Normal_distribution#Generating_values_from_normal_distribution

A: Although your setup is in the interval $[0,1)$, I will ignore the left endpoint and work with $(0,1)$. Recall the cumulative distribution function for the normal distribution:
$$
\Phi(t) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^t e^{-(1/2)x^2}dx.
$$
This function is an increasing map from ${\mathbb R}$ onto $(0,1)$ and its value at $t$ gives the probability that a normal random variable has value less than or equal to $t$.
Let $g \colon (0,1) \rightarrow {\mathbb R}$ be its inverse, i.e., $g(y)$ is the unique solution $t$ to $\Phi(t) = y$.  That is,
$$
\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{g(y)} e^{-(1/2)x^2}dx = y.
$$
Note the input to $g$ is a number in $(0,1)$ and the output is a real number.  That's the kind of setup you're looking for.
Claim: If $X$ is a uniform random variable on $(0,1)$ then $g(X)$ is a normally distributed random variable on the real line.
Proof: For $a < b$ in ${\mathbb R}$, we want to show the probability $a \leq g(X) \leq b$ is
$$
\frac{1}{\sqrt{2\pi}}\int_{a}^b e^{-(1/2)x^2}dx = \Phi(b) - \Phi(a).
$$
Since $g$ and $\Phi$ are inverses of each other, the condition $a \leq g(X) \leq b$ is the same as $\Phi(a) \leq X \leq \Phi(b)$, which is a condition in $(0,1)$ and your hypothesis about $X$ being uniform in $(0,1)$ is that the probability of that is $\Phi(b)- \Phi(a)$.  Since
$$
\Phi(b) - \Phi(a) = \frac{1}{\sqrt{2\pi}}\int_{a}^b e^{-(1/2)x^2}dx,
$$
we've got a Gaussian distribution.  (That you want $X$ to be uniform made this a lot easier to describe.)
Quite generally, if you want to model a probability distribution on the real line with  density function $f(x)$ by sampling a uniform random variable $X$ on $(0,1)$, you can use
the function $g(X)$, where $g$ is the inverse of the cumulative distribution function
$F(t) = \int_{-\infty}^t f(x)dx$.

A: The best way to obtain the inversion from U[0, 1] to Normal distribution is by using an algorithm presented in a famous short paper of Moro (1995). Moro presented a hybrid algorithm: he uses the Beasley & Springer algorithm for the central part of the Normal distribution and another algorithm for the tails of the distribution.
He modeled the distribution tails using truncated Chebyschev series.....
..................
http://marcoagd.usuarios.rdc.puc-rio.br/quasi_mc.html

A: The Box-Muller method is commonly used. It's simple to implement. And if you need several values, you can use it to produce normal samples two at a time. Otherwise, you could just discard one of the values and pretend you never created it.
George Marsaglia's Ziggurat method is more efficient than Box-Muller but more complicated.


text:
Q: How to make the JTextArea fill width and buttonsContainer fill height?
I've tried to use GridBagLayout. It makes the JTextArea parent container occupy a big width, but the text area itself didn't fill the width. Why?
And I hope the first button is close to the top and the second button is close to the bottom. How can I implement it?
Could you please advise how to correct my code?
The following code is all code for the demo.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

public class Demo extends JFrame {

    public Demo() throws HeadlessException {
        add(new MainPanel());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    class MainPanel extends JPanel {
        private final InputComponent inputComponent = new InputComponent();
        private final ButtonsContainer buttons = new ButtonsContainer();

        public MainPanel() {
            setPreferredSize(new Dimension(800, 100));
            setLayout(new GridBagLayout());
            setBorder(new EmptyBorder(5, 5, 5, 5));

            add(inputComponent,
                    buildConstraints(0, 0, 1, 1, GridConstraints.FILL_BOTH, 1.0, 1.0));
            add(buttons,
                    buildConstraints(1, 0, 1, 1, GridConstraints.FILL_BOTH, 0.0, 1.0));
        }
    }

    class InputComponent extends JComponent {

        private final JTextArea textArea = new JTextArea();

        public InputComponent() {
            setLayout(new BorderLayout());

            textArea.setLineWrap(true);
            add(textArea, BorderLayout.CENTER);
        }
    }

    class ButtonsContainer extends JComponent {
        private final JButton button1 = new JButton("Button 1");
        private final JButton button2 = new JButton("Button 2");

        public ButtonsContainer() {
            setLayout(new GridBagLayout());
            add(button1, buildConstraints(0, 0, 1, 1, GridBagConstraints.HORIZONTAL, 1.0, 0.0));
            add(button2, buildConstraints(0, 1, 1, 1, GridBagConstraints.HORIZONTAL, 1.0, 0.0));
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            final Demo demo = new Demo();
        });
    }

    private GridBagConstraints buildConstraints(
            int x,
            int y,
            int gWidth,
            int gHeight,
            int fill,
            double weightX,
            double weightY
    ) {
        final GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = x;
        constraints.gridy = y;
        constraints.gridwidth = gWidth;
        constraints.gridheight = gHeight;
        constraints.fill = fill;
        constraints.weightx = weightX;
        constraints.weighty = weightY;
        return constraints;
    }
}

A: Original Answer
Oracle has a helpful tutorial, Creating a GUI With Swing.  Skip the Netbeans section.
Don't use a GUI builder.  You wind up learning the idiosyncracies of the GUI builder, and not learning Java Swing.
I created the following GUI using a JFrame, a main JPanel, and a button JPanel.  If you maximize the GUI, you'll see that the JTextArea expands and the JButtons stay towards the top and bottom.

Don't extend Swing components, or any other Java class, unless you want to override one or more of the class methods.  Use composition over inheritance.
You can use multiple simple JPanels to create a complex GUI.  The GridBagLayout has its uses, like creating a form.  But all that was needed was multiple BorderLayouts.
Don't make Swing components class fields unless you need to access the field instance from more than one method.
Organize your code so it reads like an essay, with the most important code towards the top and the more detailed code towards the bottom.  Ideally, the reader of your code will never have to page up to find out something.  No, the compiler doesn't care about the order of the methods.  But human readers sure do.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ExampleBorerLayoutGUI {

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new ExampleBorerLayoutGUI();
        });
    }

    public ExampleBorerLayoutGUI() {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel(), BorderLayout.CENTER);
        frame.add(createButtonPanel(), BorderLayout.EAST);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JTextArea textArea = new JTextArea(5, 40);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JButton button1 = new JButton("Button 1");
        panel.add(button1, BorderLayout.NORTH);

        JButton button2 = new JButton("Button 2");
        panel.add(button2, BorderLayout.SOUTH);

        return panel;
    }

}

Edited to Add
Here's the GUI with three JButtons.  You didn't say whether you wanted the third button on the top or the bottom.  I chose the top.

I chose a GridLayout for the upper button JPanel.  It's easy to add more JButtons to a GridLayout.
Here's the modified complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ExampleBorderLayoutGUI {

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new ExampleBorderLayoutGUI();
        });
    }

    public ExampleBorderLayoutGUI() {
        JFrame frame = new JFrame("Example Border Layout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel(), BorderLayout.CENTER);
        frame.add(createButtonPanel(), BorderLayout.EAST);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JTextArea textArea = new JTextArea(5, 40);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        panel.add(createUpperButtonPanel(), BorderLayout.NORTH);
        panel.add(createLowerButtonPanel(), BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createUpperButtonPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JButton button1 = new JButton("Button 1");
        panel.add(button1);

        JButton button2 = new JButton("Button 2");
        panel.add(button2);

        return panel;
    }

    private JPanel createLowerButtonPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JButton button = new JButton("Button 3");
        panel.add(button, BorderLayout.SOUTH);

        return panel;
    }

}

A: You can auto-generate the right UI code if you use Eclipse IDE's Window Builder:
https://www.eclipse.org/windowbuilder/
It is far easier to design your application that way. Set this up on your IDE and let it do the heavy lifting for you. If you wish to incorporate dynamic resizing of your UI elements, design the code to be responsive.


text:
Q: Consistency of formatting available for VSCode and Atom? Some of our team uses Atom and some of our team uses VSCode. My issue is with code formatting via Atom Beautify vs VSCode formatting. They yield results that are inconsistent between each other, which is heck for version control and consistency within our team and style guides. Is there are way to attain consistency with formatting between these two IDEs?

A: You can install the Beautify extension, which gives you more control over the settings.
Alternatively, you could talk to your team about adopting Prettier via this extension, which is a more straightforward, but also more opinionated formatter.

A: EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs. When a project contains an .editorconfig file, the editor's preferences will be ignored, so they'll be intact for other projects. Plugins are available for Atom, Visual Studio Code and many other editors.


text:
Q: methodAccessException when passing variables from ViewModel to ViewModel on WP7 using anonymous object (MVVMCross) I've created an app using MVVMCross, the IOS and Android versions are working but when I tried to "port" to WP7 and I ran into the following problem:
throw methodAccessException.MvxWrap("Problem accessing object - most likely this is caused by an anonymous object being generated as Internal - please see http://stackoverflow.com/questions/8273399/anonymous-types-and-get-accessors-on-wp7-1");

As mentioned in the answer to my other question about this (on Android) you have to set an InternalsVisibleTo attribute in the AssemblyInfo.cs for WP7. So I did:
[assembly: InternalsVisibleTo("Cirrious.MvvmCross.WindowsPhone")]

But this doesn't make any difference. I use the following code to send two variables form my BeckhoffViewModel to my BeckhoffSensorViewModel.
BeckhoffViewModel:
public IMvxCommand BeckhoffSensor1
{
get
    {
        return new MvxRelayCommand(kvpSens1);
    }
}

private void kvpSens1()
{
    RequestNavigate<BeckhoffSensorViewModel>(new { VarType = "short", Variable = ".countertest" });
}

BeckhoffSensorViewModel:
public BeckhoffSensorViewModel(string VarType, string Variable)
{
    _vartype = VarType;
    _variable = Variable;
}

Anything I'm overlooking? I also looked at the other stackoverflow topic mentioned in the exception but couldn't really understand it.

A: The anonymous class will most definitely be created as internal by the compiler - which is why you need the line [assembly: InternalsVisibleTo("Cirrious.MvvmCross.WindowsPhone")]
Can you check that the AssemblyInfo.cs file definitely being linked into the project (and that this is the project containing the ViewModel/anonymous-class code)?
If that is the case, can you check the methodAccessException to see what the message is?
If that doesn't help, can you use a tool like Reflector to check the internalVisible attribute is actually present on the core/application assembly?


text:
Q: How to login to website using soap zeep in python. check the xml of post My wsdl Login method xml:
Host: 127.0.0.1
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/Login"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <EhelplineWebAPISecurityContext xmlns="http://tempuri.org/">
      <SessionId>string</SessionId>
      <EHLWebServiceAPIKey>string</EHLWebServiceAPIKey>
    </EhelplineWebAPISecurityContext>
  </soap:Header>
  <soap:Body>
    <Login xmlns="http://tempuri.org/">
      <LoginId>string</LoginId>
      <password>string</password>
    </Login>
  </soap:Body>
</soap:Envelope>

Login method is there in wsdl.
from zeep import Client
URL="wsdl url"
from zeep import Client
from zeep.transports import Transport
from requests import Session
client= Client(URL)
client = client.service.Login(LoginId="id",password="password")

but i am getting this error.
File "C:/Python27/zeeplogin.py", line 7, in <module>
    client = client.service.Login(LoginId="id",password="password")
  File "C:\Python27\lib\site-packages\zeep\client.py", line 41, in __call__
    self._op_name, args, kwargs)
  File "C:\Python27\lib\site-packages\zeep\wsdl\bindings\soap.py", line 121, in send
    return self.process_reply(client, operation_obj, response)
  File "C:\Python27\lib\site-packages\zeep\wsdl\bindings\soap.py", line 178, in process_reply
    return self.process_error(doc, operation)
  File "C:\Python27\lib\site-packages\zeep\wsdl\bindings\soap.py", line 280, in process_error
    detail=fault_node.find('detail'))
Fault: Object reference not set to an instance of an object.

My LoginId and password is right.

A: Have you tried this?
from zeep import Client
URL="wsdl url"
from zeep import Client
from zeep.transports import Transport
from requests import Session
client= Client(URL)
client = client.service.Login("id","password")


text:
Q: Len function : unicode character counted as 2 Please explain for me why is the below string's length is 9 instead of 8?
DECLARE @nstring NVARCHAR(100)

SET @nstring =N'Không có'

Print len(@nstring) -- 9

SET @nstring =N'Không co'

Print len(@nstring) -- 8

A: For some characters, there are several ways they can be encoded as Unicode.
In this case, an "ó" can be either U+00F3 (one 16-bit value) or U+006F U+0301 (two 16-bit values). These forms are canonically equivalent.
If you feel like reading a bit more, Using Unicode Normalization to Represent Strings by Microsoft.
Unfortunately, there is no way in T-SQL to convert a string from one form into another. See also questions like Normalize unicode string in SQL Server?
But the good news is since they're canonically equivalent, they compare the same in T-SQL (you can write N'Không có'=N'Không có' and the result is true) so it's not that big a problem as you may think at first.

A: Your last character count as two
DECLARE @nstring NVARCHAR(100)
SET @nstring =N'Không có'

print unicode(substring(@nstring,8,1))
print ascii(substring(@nstring,8,1))

print unicode(substring(@nstring,9,1))
print ascii(substring(@nstring,9,1))

The result is displayed in the image below.


text:
Q: Запись массивов в json на c# Возник вопрос, ответ на который я затрудняюсь найти.
Необходимо в Json записать таблицы с цифрами (массивы). Эти таблицы отсортированы по соответствующим характеристикам. На выходе хочу получить подобную иерархию в Json:
Параметр 1:(для выбора необходимой таблицы)
   Параметр 1.1:(для выбора необходимой таблицы)
      Параметр 1.1.1: (название i-ой строки из таблицы)
         ключ = значение (значение элемента из j-ой колонки данной строки)
         ключ = значение
         ...
      Параметр 1.1.2:
         ключ = значение
         ...
   Параметр 1.2:
      Параметр 1.2.1:
         ключ = значение
         ...
Параметр 2: и т.п.

Может объяснение корявое, заранее извините, но лучше не осилил...


text:
Q: Send data to Controller/Model and get result I want to do second filter on opencart 3, so I got default filter files from controller and model and modified them a bit.
Now I face the problem where I want on select change to send data and receive data from server
<script type="text/javascript">
    $(document).ready(function(e) {
    $("select").on('change', function() {
    var url = "controller/catalog/test.php";
    var id = $("#select-option").val();
    $.ajax({
      type: "GET",
      url: url,
      data: 'filter_group_id='+id,
      success: function(data) {
        $('.test').html(data)
      }
    });
  });
});
</script>

and i get this

Fatal error: Class 'Controller' not found in /home/public_html/admin/controller/catalog/test.php on line 2

A: I think it is better create a function without creating a page.
For example, if you are going to filter results from Catalog -> Products, you can create a
filter function on Product controller,
eg:
public function filterByGroupId(){
}

then you can access that function following way,

index.php?route=catalog/product/filterByGroupId


text:
Q: What does psexec -s do? I want to run some commands on the remote machine. I am using psexec.exe in my application, when I try to run some command using -h and -s arguments as mentioned in the below command.
C:\psexec.exe -accepteula \\IPAddress -h -u "Username" -p pwd -s netstat -bno

When we provide a valid username and password it works with provided credentials, but when we provide username and password which is not valid it picks up -s and works I have done some research on -s it says -s = Run the remote process in the System account.
What exactly -s command do, when running above mentioned command on a particular remote machine with the arguments like -h and -s together is user passed Username and Password will be preferred over -s?

A: With -s your command is executed with the System account. The System account is a special Windows account used to run core Windows services (more info here and here); this account also has special privileges, for example access to registry keys that is denied to all other accounts.
As you can read in the linked docs:

This account does not have a password

so you don't have to specify a password when using the System account.
This is how PsExec works:

*

*When you add the -s parameter the command is executed with the System account, so -u and -p parameters are ignored.

*If you specify -h (but not -s), then account and password (-u and -p) are used to connect and execute the process with the account's elevated token (if available), so they must be correct.

*If you specify -h together with -s then account and password (-u and -p) will NOT be used to connect, since the command will be executed with the System account anyway.

You can double check this behavior launching a program on a remote server and looking at the task manager of the remote machine: you will see that, using -s, the program will run under the System account, otherwise it will run under the user specified with -u.
For example if you run notepad with this command:
psexec \\remote_server -u domain\user -p correct_password -d -i -s cmd /c notepad.exe

or with this command:
psexec \\remote_server -u domain\user -p correct_password -d -i -s -h cmd /c notepad.exe

or with this command:
psexec \\remote_server -u domain\user -p wrong_password -d -i -s -h cmd /c notepad.exe

in all these three cases notepad is executed under the System account:


text:
Q: How to change widget background color? def change_frame_color(self, r, g, b):
    widget_list = [self.ui.widget,self.ui.widget_2,self.ui.widget_3,self.ui.widget_4,self.ui.widget_5]

    for widget in widget_list:
        widget.setAutoFillBackground(True)
        pt = widget.palette()
        pt.setColor(widget.backgroundRole(),QColor(r,g,b))
        widget.setPalette(pt)
        p = widget.palette().color(QPalette.Background)
        print(p.name(), widget.autoFillBackground())
        widget.update()

this is my code....
palette change but QWidget not change :(


text:
Q: Cargo path setup for rust-racer I just installed racer using cargo. After installing it say this:
Installing /home/karthik/.cargo/bin/racer
warning: be sure to add `/home/karthik/.cargo/bin` to your PATH to be able to run the installed binaries

How do I do this? Googling didn't help. Also, Should I be setting a PATH variable for cargo bin as well?
Edit: OS is Ubuntu 14.04 and I have super user access

A: You have to add the cargo bin path to your PATH variable and set the RUST_SRC_PATH in .profile or .bash_profile.
Related unix.stackechange question

A: There are two steps:
(1) Add the Cargo bin to your PATH variable.  You can run $ whereis cargo to find the bin path, and then do $ sudo -H gedit /etc/environment where you can add that new path section to your current PATH variable.  You will need to save and close the file (and you can ignore the error message in the terminal during the saving portion) in order for it to take effect.
(2) Run $ rustup component add rust-src to download the necessary Rust source files for you.
At this point Racer should work properly.
This is based on the answer here.


text:
Q: ASP.NET MVC Post Returns Wrong Model Values I have a simple post action that tries to return a new model back to the view from the post method. For some reason when I return new model I always see the model I have posted with why does that happen? I need to change the values of the model in the post action and return them back to the user but for some reason I am unable to do that?
public ActionResult Build()
{
    return View(new Person());
}

[HttpPost]
public ActionResult Build(Person model)
{
    return View(new Person() { FirstName = "THX", LastName = "1138" });
}

This is the view code;
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Person</legend>

            @Html.LabelFor(model => model.FirstName)

            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)

            @Html.LabelFor(model => model.LastName)

            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)

            <input type="submit" value="Create" />

    </fieldset>
}

If I open the form and type in "John" for first name and "Smith" for last name and post the form I get "John", "Smith" back from the post action and not "THX 1138" is there a way to override this behavior? I would also like to know why does it do that?

A: You can do this by instructing ASP.NET MVC to forget the posted values by adding this.ViewData = null; to your post action:
[HttpPost]
public ActionResult Build(Person model)
{
    this.ViewData = null;

    return View(new Person() { FirstName = "THX", LastName = "1138" });
}


text:
Q: Are there any other interesting topologies on $\mathrm{Spec} (A)$ other than Zariski's? This might be a somewhat stupid question, but I've been wondering if it is possible to define some other topology on $\mathrm{Spec} (A)$ other than Zariski topology in a way that it has some interesting properties as well.
First of all, I am new as this is my first encounter with anything close or related to algebraic geometry, so be easy on me =).
And second, what I'd like to know is if, for example, there is a topology on $\mathrm{Spec} (A)$ such that, say, $\mathrm{Spec} (A)$ is Hausdorff or has any other nice properties (connectedness, compactness, etc...), or why if such a topology exists, isn't as interesting as Zariski topology.
Note: I am aware of a "similar" question here. However, I'm not interested that much in why Zariski topology is important since I think I understand how it arises naturally.

A: There is a generalization of the notion of topology called a Grothendieck topology. Grothendieck has defined many examples of Grothendieck topolgies in the category of schemes for example the Etale topology which is one notion used in the proof of Weil conjectures.
https://en.wikipedia.org/wiki/Grothendieck_topology

A: As far as I'm aware there is no other interesting topology on  $\mathrm{Spec} (A)$. However:
1) There are the so called "Grothendieck topologies" on any $\mathrm{Spec} (A)$ or more generally on an arbitrary scheme.
They are generalizations of the usual notion of a topology and compensate for the coarseness of the Zariski topology, in that they allow results analogous to those in algebraic topology:  Gysin sequence, Künneth formula, Poincaré duality, Lefschetz fixed point formula,etc.
They were dreamed of by Weil and constructed by Grothendieck (with the help of  Mike Artin and others), spurred by an insight of Serre's.
Their most spectacular achievement was the complete solution of the Weil conjectures by Grothendieck and Deligne.
2) For schemes $X$ of finite type over $\mathbb C$, for example $\mathrm{Spec} (A)$ with $A$ a finitely generated $\mathbb C$-algebra, Serre showed how to give the set $X^{cl}$ of closed points  of $X$ a topology and a structure sheaf such that $X^{cl}$ becomes a complex analytic space.
There is then an exciting interplay (foreshadowed by Riemann, Chow and others) between the scheme $X$ and the analytic space $X^{cl}$, in which algebra, algebraic topology and analysis join forces, to our greatest delight.
Hodge theory is an egregious example of that  alliance.


text:
Q: Use C# to get an SMTP server certificate Using C# how do I connect to a SMTP server that supports STARTTLS and get its SSL certificate? I know it can be done using openssl with something like this
openssl s_client -starttls smtp -crlf -connect 192.168.0.1:25

I don't want to call openssl and parse its output though. An example of how to do it with C# would be very much appreciated.

A: One way would be to bind to the ServerCertificateValidationCallback callback and send a test message to the server. The mail message might fail but the certificate will still be valid.
    private void Form1_Load(System.Object sender, System.EventArgs e)
    {
        System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
        using (System.Net.Mail.SmtpClient S = new System.Net.Mail.SmtpClient("smtp.gmail.com"))
        {
            S.EnableSsl = true;
            using (System.Net.Mail.MailMessage M = new System.Net.Mail.MailMessage("test@example.com", "test@example.com", "Test", "Test"))
            {
                try
                {
                    S.Send(M);
                }
                catch (Exception)
                {
                    return;
                }
            }
        }
    }
    private bool RemoteServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        Console.WriteLine(certificate);

        return true;
    }


text:
Q: passing of two php variables from one php page to next php page with the help of SQL I want to pass the two variable from the below php script to the next php page that is pid and title. pid is working fine but I don't know how to take the title from SQL query and pass it to the next php script.
   $result= mysqli_query($bd, "select p.title, p.description from POI p where p.pid='$pid'");
   while($row=mysqli_fetch_array($result))
        {
        echo "
$row[0]
";

        echo $row[1];
        echo "
";
        echo "
";
        }

the below code is for getting the values from the above php script:
$pid=$_REQUEST['pid'];
$title=$_REQUEST['row[0]'];

A: When you build the url, you are passing parameters named pid and title.
Change

$title=$_REQUEST['row[0]'];

to be

$title=$_REQUEST['title'];

A: Instead of the ' you are using in title='$row[0]', use {}, title={$row[0]}:
echo "
{$row[0]}
";

And on the next page, $_REQUEST['title'];

A: Try this:
echo "
".$row[0]."
";

Then on the link_comment.php script:
$pid=$_GET['pid'];
$title=$_GET['title'];

A: Change this
echo "
$row[0]
";
to this
echo "
{$row[0]}
";


text:
Q: Is $3 \ge 1$ or is it just $3 > 1$? Well, probably this might seem a really simple question (and it might be so too!), but off late me and my friends have been debating quite hard over this question.

Is $3 \ge 1$ or is it just $3 > 1$?

Actually it all started here: if functions $f$ and $g$ satisfy $f>g$ then do they also satisfy $f \ge g$? All of us agreed. (are we wrong here itself?). After all, the $\ge$ symbol is basically 'greater than' OR 'equal too'. So if a function $f$ takes values greater than $g$, then definitely it satisfies the $\ge$ relation.
But then somehow the above mentioned question came up. My friends say that $3 \ge 1$ is absolutely wrong. Their reasoning: "under no circumstances can 3 be equal to 1", so $3 \ge 1$ is wrong.
My argument: $3 \ge 1$ is a mathematical statement which can either be true or false. It states that 3 is either greater than OR equal to 1. One of the conditions is satisfied and the two conditions are linked by an 'OR'. So $3\ge 1$ is true.
Who's right?
(please edit or add tags as i don't know what to tag the question as!)

A: The statement "two is even or pigs fly" is true, as is anything of the form "[true] or [false]".
So yes, given two numbers $a,b$, exactly one of the following is true:
$$a<b$$
$$a=b$$
$$a>b$$
But it doesn't hurt anything to combine the true one with a false one, using "or".

A: You are right.
Regarding your friend's concern: The statement 'I am a person or I am a horse' is true. I am always a person, so this is true. It does not matter that it is impossible for me to be a horse.
Similarly, '3 is greater than or equal to 1' is always true. It is always true that 3 is greater than 1. It is never equal to 1, but this does not matter.
This question, like many others, can be resolved by returning to the definitions. For a statement of the form 'A or B' to obtain, at least one of A or B must be true. This is necessary and sufficient. As long as one of A or B is true, the status of the other doesn't matter. It doesn't even matter if the other can never be true. All that matters is that at least one of them is true.
For a more formal approach, consult any textbook on logic.

A: You are correct, and so is your reasoning: $3\ge 1$ is precisely equivalent to the compound statement
$$3>1\quad\text{or}\quad3=1\;.$$
You might try pointing out to your friends that in order to be consistent, they would have to argue that '$4$ is even or odd' is false, because $4$ is never odd!

A: Your argument is correct. If $x$ is greater or equal to $y$, this means that there exists a non-negative number $a$ such that:
$$y + a = x$$
this of course true for $ 3 \text{ and } 1$ $(a=2)$, so indeed $3 \ge 1$.

A: In programming, if one writes
if (condition1 || condition2)

where || means OR and condition1 is true, condition2 is, in most languages if not all, not even evaluated - for the very same reason: it does no longer matter. The whole expression is true.

A: You're correct. It's true that $3\geq 1$, however, if one wish to obtain the stronger statement, one can always specify that $3>1$. Both are correct, but the latter is more preferable.


text:
Q: Unable to bind event handler at init I have a form in which audio preview elements are created dynamically.  I want to execute code after the audio elements have been processed by the browser.  The following works:
Works if executed after audio elements have been created
  $('audio').on('loadeddata', ->
    alert "test audio"
  )

but it only works if I bind the event after the element has been created.  I am looking for a way to bind the event to all future 'audio' tags at document onload.  The following does not work:
Never Works
$(document).on('loadeddata', 'audio', ->
  alert "test audio"
)

The following always works
$(document).on('click', 'audio', ->
  alert "test audio"
)

My goal is to be able to bind these events once when my document is loaded.  Any help or insights would be greatly appreciated.
Edit
because I am using rails with turbolinks I execute The above snippets with both ready and onload events.  So the code is:
reload = ->
  #relevant code here

$(document).on 'page:load', reload

$ -> reload()

A: Start your event handling after your document has fully loaded:
$(document).ready(function(){
    $(document).on('loadeddata', 'audio', function(){
      alert "test audio"

     });
});

A: Try binding those events inside
$(document).ready(function(){
        // bind your events here
});


text:
Q: Unable to install flex module in angular application I am implementing a sample application in Angular with AngularMaterial and FlexLayout .
I have successfully installed and implementing Angular Material Components.I have also installed Flex using the below command
npm install @angular/flex-layout --save

But when I am running my application I am getting the following warning message in my Eclipse Terminal as shown below

And I am also getting the following error in my console.

Below shown is package.json file
{
  "name": "angular-material-demo",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/cdk": "^5.0.3",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/flex-layout": "^6.0.0-beta.16",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "^5.0.3",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "@types/jwt-decode": "^2.2.1",
    "core-js": "^2.4.1",
    "font-awesome": "^4.6.3",
    "hammerjs": "^2.0.8",
    "jwt-decode": "^2.2.0",
    "primeng": "^2.0.5",
    "rxjs": "^5.5.2",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.6.0",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "angular-ide": "^0.9.38",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.4.2"
  }
}

I tried doing the below steps also.
Edited package.json: Had to change my version for @angular/compiler-cli. In my case I had to bring it back to 5.2.0, as it somehow got to 5.2.10.

Deleted the node_modules directory.

Ran: npm install

Installed: npm install @angular/flex-layout.

But again i ran in different errors. I also tried changing the version of flex from "@angular/flex-layout": "^6.0.0-beta.16" to "@angular/flex-layout": "^2.0.0-beta.12" in package.json file but I am still getting these errors.
Can anybody please help me to resolve this issue?


text:
Q: CSS Div That Wraps Under With Shadow I know this has probably been covered a few times on the web, but I don't think I know how to properly describe the effect i'm looking for as I can't seem to find any results. Its quite a popular trend these days where the div seems to wrap under the edges of its parent:

Similar to the header element on the menus in the image. Doesn't have to be rounded as in the picture, but a similar effect would be nice, and all in pure CSS if possible.
I'm at a complete loss of where to start here, and any insight would certainly be appreciated.

A: Guess this will help you!
A pure implementation of CSS Ribbons. Demo here.

(source: red-team-design.com)
Another implementation of the same, Pure CSS Ribbon Builder. Builder here.

Or you can try this Corner Ribbon
You need to have this HTML

NEWS

And the CSS
.wrapper {
  margin: 50px auto;
  width: 280px;
  height: 370px;
  background: white;
  border-radius: 10px;
  -webkit-box-shadow: 0px 0px 8px rgba(0,0,0,0.3);
  -moz-box-shadow:    0px 0px 8px rgba(0,0,0,0.3);
  box-shadow:         0px 0px 8px rgba(0,0,0,0.3);
  position: relative;
  z-index: 90;
}

.ribbon-wrapper-green {
  width: 85px;
  height: 88px;
  overflow: hidden;
  position: absolute;
  top: -3px;
  right: -3px;
}

.ribbon-green {
  font: bold 15px Sans-Serif;
  color: #333;
  text-align: center;
  text-shadow: rgba(255,255,255,0.5) 0px 1px 0px;
  -webkit-transform: rotate(45deg);
  -moz-transform:    rotate(45deg);
  -ms-transform:     rotate(45deg);
  -o-transform:      rotate(45deg);
  position: relative;
  padding: 7px 0;
  left: -5px;
  top: 15px;
  width: 120px;
  background-color: #BFDC7A;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#BFDC7A), to(#8EBF45));
  background-image: -webkit-linear-gradient(top, #BFDC7A, #8EBF45);
  background-image:    -moz-linear-gradient(top, #BFDC7A, #8EBF45);
  background-image:     -ms-linear-gradient(top, #BFDC7A, #8EBF45);
  background-image:      -o-linear-gradient(top, #BFDC7A, #8EBF45);
  color: #6a6340;
  -webkit-box-shadow: 0px 0px 3px rgba(0,0,0,0.3);
  -moz-box-shadow:    0px 0px 3px rgba(0,0,0,0.3);
  box-shadow:         0px 0px 3px rgba(0,0,0,0.3);
}

.ribbon-green:before, .ribbon-green:after {
  content: "";
  border-top:   3px solid #6e8900;
  border-left:  3px solid transparent;
  border-right: 3px solid transparent;
  position:absolute;
  bottom: -3px;
}

.ribbon-green:before {
  left: 0;
}
.ribbon-green:after {
  right: 0;
}


text:
Q: selection of one row based on other columns in python small part of my csv file is like the following lines:
481116  ABCF3   466 0   ENSG00000161204 0
485921  ABCF3   466 0   ENSG00000161204 0
489719  ABCF3   466 0   ENSG00000161204 0
498136  ABCF3   466 2   ENSG00000161204 0.0019723866
273359  ABHD10  326 78  ENSG00000144827 0.0301158301
491580  ABHD10  326 0   ENSG00000144827 0
493784  ABHD10  326 0   ENSG00000144827 0
494817  ABHD10  326 1   ENSG00000144827 0.0012484395

the columns are separated by "," in the file. in the 2nd column there are many repeated ids and I would like to select only one of the ids based the values in the 6th column. in other word, for each id I want to choose the one with the highest number in the column 6.
the results for the mentioned part, must be like this.
498136  ABCF3   466 2   ENSG00000161204 0.0019723866
273359  ABHD10  326 78  ENSG00000144827 0.0301158301

I have tried to make it in python and wrote some pieces of codes in the following framework but non of them worked:
with open('data.csv') as f, open('out.txt', 'w') as out:
    line = [line.split(',')for line in f]
    .
    .
    out.write(','.join(results))

A: you_data.csv:
481116,ABCF3, 466,0, ENSG00000161204,0
485921,ABCF3, 466,0, ENSG00000161204,0
489719,ABCF3, 466,0, ENSG00000161204,0
498136,ABCF3, 466,2, ENSG00000161204,0.0019723866
273359,ABHD10,326,78,ENSG00000144827,0.0301158301
491580,ABHD10,326,0, ENSG00000144827,0
493784,ABHD10,326,0, ENSG00000144827,0
494817,ABHD10,326,1, ENSG00000144827,0.0012484395

code:
import csv
from collections import defaultdict

with open('you_data.csv', newline='') as f, open('out.csv', 'w', newline='') as out:
    f_reader = csv.reader(f)
    out_writer = csv.writer(out)
    d = defaultdict(list)
    for line in f_reader:
        d[line[1]].append(line)
    for _,v in d.items():
        new_line = sorted(v, key=lambda i:float(i[5]), reverse=True)[0]
        out_writer.writerow(new_line)

out.csv:
498136,ABCF3, 466,2, ENSG00000161204,0.0019723866
273359,ABHD10,326,78,ENSG00000144827,0.0301158301


text:
Q: Angular js load local json array I am new in angular js and ionic
I am trying to retreive the date (data that i want to retreive it) from an array and repeat it on html file
knowing  that my array was stored in local storage under the name of List like :
List: {
    error: false,
    List_issue: [
        0: {
            id: 16
            tittle "doggie"
            image: ""
            date: "2015-08-17 2:22:24 p.m."
        },
        1: {
            id: 17
            tittle "mmmmm"
            image: ""
            date: "2015-08-18 2:22:24 p.m."
        }
    ]
}

how can i do it ?? please help me

A: The JSON format is wrong in your code, update the JSON as in your controller as
$scope.lists = [{
            id: 16,
            tittle :"doggie",
            image: "",
            date: "2015-08-17 2:22:24 p.m."
        },
        {
            id: 17,
            tittle :"mmmmm",
            image: "",
            date: "2015-08-18 2:22:24 p.m."
        }
];

And in your html the code to print the Dates as
<ion-list>
 <ion-item ng-repeat = "list in lists">
   {{list.date}}
 </ion-item>
</ion-list>


text:
Q: How to we achieve code-reuse if we use React Redux Hooks? Let's say we have a component:
function Count() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();

  const increment = () => dispatch({ type: 'INCREMENT' });
  const decrement = () => dispatch({ type: 'DECREMENT' });

  return (

      <button onClick={increment}> + </button>
      {count}
      <button onClick={decrement}> - </button>

  );
}

suppose it actually is a complicated component, and instead of 3 lines of code inside the return (), there are 45 or 80 lines of code.  In that case, how do we achieve code-reuse if we don't want to repeat the code if we need to map this component to a different Redux state?
For example,

*

*what if we need two such components on the same page, one for countIceCream and one for countDrink?

*if on the To Go Order page, we need such component but it is for countSpoon?

A: what I will do is
make two components , the First IceCreamCount or DrinkCount  and the second is basic Count component which will not be connected to redux
example :
function Count(props){
     return (

      <button onClick={props.increment}> + </button>
      {props.count}
      <button onClick={props.decrement}> - </button>

  );
}

//connected to redux
function IceCreamCount(props){
    return <Count count={props.count} increment={...} decrement={...} />
}

A: If I understand correctly you want to produce the same output but get the state data from different places for CountIceCream and CountDrink. Also the actions are different for CountIceCream and CountDrink.
So here is an example for increment action for CountIceCream and CountDrink:
const incrementDrink = ()=>({type;INCREMENT_DRINK})
const incrementIceCream = ()=>({type;INCREMENT_ICE_CREAM})

Here are the selectors to get count data for drink and ice cream (this is a simple example, in projects I would advice using composable selectors to prevent duplication)
const selectIceCreamCount = state => state.iceCream.count;
const selectIceDrinkCount = state => state.drinkCream.count;

Your container can look something like this:
const CounterContainer = function CounterContainer(
  { selector, up, down, remove },
  props
) {
  const dispatch = useDispatch();
  const count = useSelector(selector);
  const propsForPresentational = {
    count
    increment: () => dispatch(incement),
    decrement: () => dispatch(decrement),
    ...props,
  };
  //a container should not return jsx,
  //  better create a presentational component instead
  return
bunch of jsx

};

Here is how you can create an ice cream count container:
export const IceCreamCountContainer = React.memo(
  function IceCreamCountContainer(props) {
    return CounterContainer(
      {
        selector: selectIceCreamCount,
        increment:incrementIceCream,
        decrement:decrementIceCream,
      },
      props
    );
  }
);


text:
Q: parent child relationship vs linking table I have a project management database structure which is modeled on a parent/child structure.
item (id,parentId)

However, I am told that I should be using a linking table instead.
item(id)

linkingtable(parentId,childId)

Currently, there is no requirement that the items can be linked many to many, so I do not see any benefit.
Am I missing anything?
I am a c# programmer, not a database designer, so want to make sure of what I am doing here.

A: IMHO if there is a slightest possibility of making the relation ManyToMany in future than you should go for association or intermediate table.
But if you are sure that this relation is pure ManyToOne then no need to create additional table.


text:
Q: SCSS compiler not working properly in PyCharm I am trying to set up a SCSS transpiler in PyCharm for Django project.
Basically, what I need is to convert /static/scss/main.scss to /static/css/main.css
Here are the configurations of SCSS File Watcher:
Program: /home/maverick/.rvm/gems/ruby-2.2.3/bin/scss

Arguments: --no-cache --update /home/maverick/Documents/DjangoProjects/timberg/static/css/$FileNameWithoutExtension$.css

Working directory: /home/maverick/Documents/DjangoProjects/timberg/static/scss

Output paths to refresh: /home/maverick/Documents/DjangoProjects/timberg/static/css/$FileNameWithoutExtension$.css

What is happening is that main.css is being generated where it should. But it contains only errors, not the expected css, like this:
/*
Error: Inconsistent indentation: 2 spaces were used for indentation,    but the rest of the document was indented using 8 spaces.
    on line 39 of    /home/maverick/Documents/DjangoProjects/timberg/static/css/main.css

and etc.
What is wrong here? How can I fix it?

A: The problem was in the Arguments part.
It should be:
$FileName$:/home/maverick/Documents/DjangoProjects/timberg/static/css/$FileNameWithoutExtension$.css

not just:
/home/maverick/Documents/DjangoProjects/timberg/static/css/$FileNameWithoutExtension$.css

My mistake was leaving out $FileName$: at the beginning.


text:
Q: Diferencia entre while y for en Python Hay alguna diferencia entre usar la instrucción for y while? (En los casos en que se permitan ambas formas, claro está).
Por ejemplo, los siguientes codigos:
i = 0
while i < 10:
    print(i)
    i += 1

for i in range(10):
    print(i)

Hay alguna diferencia en rendimiento o de algun otro estilo en usar una u otra instruccion? Gracias.

A: Es una pregunta que no es nada fácil de responder. Depende de qué versión del intérprete python uses (CPython, Pypy, pyodide, ...) y de cómo hagan las optimizaciones.
Sin entrar en cómo trabaja el intérprete, podemos analizar qué hace cada bucle:

*

*La versión while hace dos operaciones: i < 10 y i += 1. Con el incremento se crearán nuevos objetos (números enteros).

*La versión for range llama a la función range() para obtener un iterador que recorre el bucle para dar valores a i hasta quedar exhausto. Sin entrar en lo que haga range(), el bucle en sí no crea ningún objeto.
Si tenemos N iteraciones, el intérprete python tendrá que hacer 2*N operaciones y crear N objetos con el bucle while, mientras que con el bucle for range sólo tiene que llamar a una función e invocar el iterador, todo optimizado en lenguaje de bajo nivel.
La pregunta sería: ¿qué es más eficiente, las operaciones y creación de objetos que hace el while, o la llamada a range() y recorrer el iterador que hace el for?
La función range() y el iterador están optimizados (programado en C/C++ en el caso de CPython). Para un caso general, debería ser mucho más eficiente que usar el while. Pero hay optimizadores que saben optimizar el bucle while, siempre que no dependa de código externo. No se puede decir cuál de los dos bucles tendrá mejor rendimiento sin ver casos concretos.
Aún hay más. Cuando digo que i += 1 _"crea objetos", no es del todo cierto. El intérprete de python crea al inicio todos los objetos que piensa que va a necesitar. Entre otros, crea todos los números enteros del -1 al 256, por lo que en el bucle while del ejemplo, cuyo entero mayor será 10, ¡no crea ningúno de los números que usa!.
Dejando de lado el rendimiento, sí que hay algo que es importante considerar. Con el bucle while no se puede impedir que la variable de control sea modificada y que el bucle acabe antes de tiempo o que se produzca un error con la expresión de control. Estos problemas están más limitados con el bucle for, lo que es razón suficiente para recomendar su uso.

A: Encontré el módulo time, e hice la siguiente prueba:
import time

inicial_for = time.time()

for i in range(1000000):
    i += 1

print(time.time() - inicial_for, "segundos con FOR")

inicial_while = time.time()
n = 0
while n < 1000000:
    n += 1

print(time.time() - inicial_while, "segundos con WHILE")

Tomo el tiempo antes de la ejecución de cada uno de los bucles, tomo el tiempo al finalizar, y realizo la resta, para saber el tiempo de ejecución.
Devuelve los siguientes valores:
1000000 iteraciones
0.12027621269226074 segundos con FOR
0.12313008308410645 segundos con WHILE

10000000 iteraciones
1.1102118492126465 segundos con FOR
1.192373514175415 segundos con WHILE

100000000 iteraciones
10.883198022842407 segundos con FOR
11.439775705337524 segundos con WHILE

1000000000 iteraciones
107.99017834663391 segundos con FOR
114.22435331344604 segundos con WHILE

En la primera ejecución, las diferencias son mínimas, y se intercalan entre el for y el while. A mayor número de iteraciones, se nota más la diferencia de que el while es más lento en ejecución.
Espero que a alguien le sirva, gracias!

A: El rendimiento no es el punto: un for se ocupa para recorrer secuencias y un while para ejecutar mientras se cumpla una condición.
El concepto central del for es ir sacando elementos uno por uno hasta agotarlos todos:
for elemento in lista:
    ----

En el while la cantidad de elementos no es conocida de antemano; tienes que procesar hasta que se cumpla una condición que te diga parar. Ejemplo: procesar una entrada de teclado hasta que el usuario ingrese "exit"
opcion = ''
while opcion != "exit":
    ----


text:
Q: Spring webapp with multiple auth type: basic and social login togheter I wrote a spring boot webapp with spring security authentication over jpa. It uses jwt to grant access to a simple html/js application.
I'd like to add oauth2 flow in order to allow users to authenticate over github or google or whatever cloud system.
What kind of solution may I adopt to target it?
I see many applications like udemy, for example,  or others. They allow multiple authentication types:

*

*username and password

*google account

*facebook account

How may I replicate this behaviour in my webapp?


text:
Q: Get-WMIObject: why does != NULL work with MACAddress but not IPAddress? Can anyone tell me why this command works:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "MACAddress != NULL"

whereas this one:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPAddress != NULL"

produces:
Get-WmiObject : Invalid query "select * from Win32_NetworkAdapterConfiguration where IPAddress != NULL"
At line:1 char:1
+ Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPAddress != NUL ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

and what I should use, instead?

A: MacAddress is a string, and IPAddress is a string Array.
MSDN doc for Win32_NetworkAdapterConfiguration class
Essentially, you'll just have to get all the adapters and parse whether the IPAddress is valid or not, since NULL and Empty are invalid queries.


text:
Q: wireshark count packets by port I have a very large trace file and am trying to use Wireshark to determine which dest port has the most packets sent to it. Is there a way to get counts of packets sent to particular ports? Or to sort by number of packets sent a port?

A: You can write a simple wireshark listener in lua.
local tap

local ports = {}

local function packet(pinfo, tvb, userdata)
    -- store number of packets per each port
    local port = pinfo.dst_port
    ports[port] = (ports[port] or 0) + 1
end

local function draw(userdata)

    local maxi,maxv = 0,0
    -- print all gathered statictics and find max
    for i,v in pairs(ports) do
        print(i .. ":",  v)
        if maxv < v then
            maxi,maxv = i,v
        end
    end
    print ("Max:", maxi, maxv)
end

local function reset(userdata)
    ports = {}
end

local function show_ports()
    tap = Listener.new()
    tap.packet = packet
    tap.draw = draw
    tap.reset = reset
end

register_stat_cmd_arg('ports', show_ports)

Try it:
tshark -X lua_script:ports.lua -z ports -r in.pcap


text:
Q: what is difference between this two views ? (autorotation) http://www.freezpic.com/pics/d63adbfb5faec3ded732dcfee5cc71ef.jpg
in the image one i can enable  red arrows inside the inner square ...
http://www.freezpic.com/pics/736e30ef1accf1d174122f2e1b017b8d.jpg
but in the second image i can't enable red arrows inside the inner square.
why?

A: You can do it both.. Go to the view properties in the first view and set the status bar as none, then you will be able to do that.
Hope this helps.
Thanks,
Madhup


text:
Q: Change Data Directory: MySQL 5.6 + Workbench 6.0+ Windows 7 My data directory is a little messed up.
It keeps running an import of data as follows:
running : mysql.exe --defaults-extra-file="c:\users\thedes~1\appdata\local\temp\tmpgrqaof.cnf"  --host=localhost --user=root --port=3306 --default-character-set=utf8 --comments --database=mysql < "D:\Dh\Rs\Data\Yelp\xcd\xcd.sql"
Problem of course i s I have only so much c drive space .
I would like to use the d drive.
What I've tried:
1) went to my.ini in ProgramData and switched datadir to the path I want.
2) went to workbench (which is what I am using) and clicked on configurations , entered said path into datadir. no cigar.
Not sure what I am doing wrong here. Any help would be most appreciated!!


text:
Q: Trigger onFocus textBox Android gwt webapp phonegap 1.1 I'm running a webapp on Android galaxytab.
I have 3 textbox with FocusHandler-s erasing the textbox content onFocus.
This works well but if  the user uses the tab, previous or next buttons on the device's keyboard, the FocusEvent is not triggered.
I tried to catch Key events to prevent default action on TAB but the tab key is not triggerd either.
Does anyone know how to trigger a FocusEvent on tab or previous/next key press on an Android device keyboard? (Everything works well in computer's browser even if using tab key the focus event is triggered but not in Android's browser).

A: While this isn't a fix for your FocusHandler issue, if the content in the textbox that is being erased is a placeholder, perhaps you can benefit from this answer.

A: Take a look at http://www.m-gwt.com
The library provides placeholders for input elements in gwt.


text:
Q: built in "Offer Remote Assistance" not working because of permissions I'm trying to enable permissions for a user on a Windows7 machine to use the built in feature called "Offer Remote Assistance" or "Windows Remote Assistance".  This feature works fine if the user is added to the "domain admins" security group, but for security reasons, I cannot leave him in that group.  This is within a SBS2003 Domain.
I have added the user and also a group that he is apart of to the Small Business Server Remote Assistance Policy, after following some documentation I was able to find, but this has not worked.
Can you tell me how to enable this feature for this user and or a user group?
http://content.screencast.com/users/CASEIT/folders/Forum%20Pictures/media/2a518bc9-4184-4520-8b76-cdf46555f568/2011-08-18_1330.png

A: Have you configured this GPO: Computer Configuration/Administrative Templates/System/Remote Assistance?
The policy is defined as:

This policy setting allows you to turn on or turn off Offer
  (Unsolicited) Remote Assistance on this computer.
If you enable this policy, users on this computer can get help from
  their corporate technical support staff using Offer (Unsolicited)
  Remote Assistance.
If you disable this policy, users on this computer cannot get help
  from their corporate technical support staff using Offer (Unsolicited)
  Remote Assistance.
If you don't configure this policy, users on this computer cannot get
  help from their corporate technical support staff using Offer
  (Unsolicited) Remote Assistance.

A: REM ******* UAC needs to be disabled in order to run this script on a Vista or Windows 7 machine ********
runas /noprofile /user:domain/username "msra.exe /offerra"


text:
Q: JPA shared cache / second level cache in WildFly I'm using WildFly 8.1 so JPA 2.1 and Hibernate 4.3.5
I want to use JPA shared cache / second level cache in WildFly
I follow the WildFly documentation: https://docs.jboss.org/author/display/WFLY8/JPA+Reference+Guide#JPAReferenceGuide-UsingtheInfinispansecondlevelcache
here is my persitience.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="myAppPU" transaction-type="JTA">
    <jta-data-source>java:/jdbc/myAppDS</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="org.hibernate.flushMode" value="MANUAL"/>
      <property name="hibernate.cache.use_second_level_cache" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

I set the property hibernate.cache.use_second_level_cache to true
and set the shared-cache-mode to ENABLE_SELECTIVE
And entities (@Entity) I want to cached are annotated with @Cacheable(true), like that:
@Entity
@Cacheable(true)
public class Tooltip implements Serializable {
  @Id
  private String path ;
  private String description ;
  private Boolean rendered ;
  //...
}

But each time I visit a web page hibernate generate a lot of select to get all entities I have indicate as @Cacheable(true) even if I already visit the page (in the same session).
So it seems that the shared cache / second level cache is not working
Did I miss something?

Thank you hwellmann
I tried to put hibernate.cache.use_query_cache to true in the persitence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="myAppPU" transaction-type="JTA">
    <jta-data-source>java:/jdbc/myAppDS</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="hibernate.cache.use_second_level_cache" value="true"/>
      <property name="hibernate.cache.use_query_cache" value="true" />
      <property name="org.hibernate.flushMode" value="MANUAL"/>
    </properties>
  </persistence-unit>
</persistence>

and and the hint in the query I'm using
@Entity
@NamedQueries({
    @NamedQuery(name = "FieldInfos.findAll", query = "SELECT i FROM FieldInfos i", hints = {@QueryHint(name="org.hibernate.cacheable",value="true")}),
    @NamedQuery(name = "FieldInfos.findByPath", query = "SELECT i FROM FieldInfos i WHERE i.path = :path", hints = {@QueryHint(name="org.hibernate.cacheable",value="true")})
})
@Cacheable(true)
public class FieldInfos implements Serializable {
    //...
}

but the problem remain
I also try with the new version of WildFly: 8.2 so Hibernate 4.3.7 but the problem remain too

A: The second level cache only affects direct entity lookups, corresponding to EntityManager.find().
If you're trying to avoid all sorts of SELECT queries affecting your cached entities, you also need to enable the query cache:
    <property name="hibernate.cache.use_query_cache" value="true" />

and you need to set a query hint org.hibernate.cacheable=true for each query to be cached.


text:
Q: How to detect when FileDownloader in vaadin finish How can I detect fileDownloader finish to export my csv-file:
Here is the part, where I implemented the download-button
 Button downloadButton = new Button("Download");
    Exporter exporter = new Exporter();
    downloadButton.addClickListener(clickEvent -> {
     //something here
    });
    exporter.getFileDownloader().extend(downloadButton);

This is my exporter with the fileDownloader:
class Exporter{
    private FileDownloader fileDownloader;

    Exporter() {
        StreamResource streamResource = createResource();
        fileDownloader = new FileDownloader(streamResource);
    }

    private StreamResource createResource() {
        return new StreamResource(new StreamResource.StreamSource() {
            @Override
            public InputStream getStream() {
            // some logic here
            }
        }, "myfile.csv");
    }

    FileDownloader getFileDownloader() {
        return fileDownloader;
    }

    ...

A: I checked official documentation, it seems there is no way to detect that using FileDownloader. There is also similar thread you can check it. How to detect when Vaadin FileDownloader succeeds or fails


text:
Q: Is conjunction reduction possible within an if's compound apodosis? I have the following sentence:

If the researcher knew the mechanism, any feature of the population would be known, any (causal) relationships in the population would be completely traceable, and any realization of that population would be completely predictable.

In this case, it is extremly unlikely the researcher will ever know "the mechanism", so we use if + past tense in the conditional's protasis followed by modal would + infinitive in its resulting apodosis.
My question: Do I have to fully repeat would be in every conjoined clause, or can I also simplify by writing:

If the researcher knew the mechanism, any feature of the population would be known, any (causal) relationships in the population be completely traceable, and any realization of that population be completely predictable.

I can't really say why, but somehow this second version sounds right to me. However, being a non-native speaker, I'd rather ask for guidance here.


text:
Q: Spring cannot roll back committed transactions when one datasource transaction failed I am working on one microservice, which involves multiple datasources. For the sake of simplify, I am using two datasources here, MySql and Oracle. This is the pseudo code.
    domain.withNewTransaction {
      mySql.executeUpdate("update mySqlTable")
      oracle.executeUpdate("update oracleTable")
    }

One day there was an exception thrown up when trying to commit oracle update, however, I found mysql update is successfully committed and not rolled back.
I found the framework is using ChainedTransactionManager.java to manage multiple datasources commit. This is the code for commit method.
public void commit(TransactionStatus status) throws TransactionException {

        MultiTransactionStatus multiTransactionStatus = (MultiTransactionStatus) status;

        boolean commit = true;
        Exception commitException = null;
        PlatformTransactionManager commitExceptionTransactionManager = null;

        for (PlatformTransactionManager transactionManager : reverse(transactionManagers)) {

            if (commit) {

                try {
                    multiTransactionStatus.commit(transactionManager);
                } catch (Exception ex) {
                    commit = false;
                    commitException = ex;
                    commitExceptionTransactionManager = transactionManager;
                }

            } else {

                // after unsucessfull commit we must try to rollback remaining transaction managers

                try {
                    multiTransactionStatus.rollback(transactionManager);
                } catch (Exception ex) {
                    LOGGER.warn("Rollback exception (after commit) (" + transactionManager + ") " + ex.getMessage(), ex);
                }
            }
        }

        if (multiTransactionStatus.isNewSynchonization()) {
            synchronizationManager.clearSynchronization();
        }

        if (commitException != null) {
            boolean firstTransactionManagerFailed = commitExceptionTransactionManager == getLastTransactionManager();
            int transactionState = firstTransactionManagerFailed ? HeuristicCompletionException.STATE_ROLLED_BACK
                    : HeuristicCompletionException.STATE_MIXED;
            throw new HeuristicCompletionException(transactionState, commitException);
        }
    }

It turns out when one datasource commit failed, ChainedTransactionManager will only roll back the remaining uncommitted ones, nothing to do with committed transactions.
I understand it's complicated and risky to roll back the committed transaction. I'd like to know for application developer if any better idea to handle this multiple datasources transaction commit failure. Thanks in advance!

A: Find some info from grails document http://docs.grails.org/3.1.4/guide/conf.html#configGORM
Transactions across multiple datasources
Grails uses the Best Efforts 1PC pattern for handling transactions across multiple datasources.
The Best Efforts 1PC pattern is fairly general but can fail in some circumstances that the developer must be aware of. This is a non-XA pattern that involves a synchronized single-phase commit of a number of resources. Because the 2PC is not used, it can never be as safe as an XA transaction, but is often good enough if the participants are aware of the compromises.
The basic idea is to delay the commit of all resources as late as possible in a transaction so that the only thing that can go wrong is an infrastructure failure (not a business-processing error). Systems that rely on Best Efforts 1PC reason that infrastructure failures are rare enough that they can afford to take the risk in return for higher throughput. If business-processing services are also designed to be idempotent, then little can go wrong in practice.
The BE1PC implementation was added in Grails 2.3.6. . Before this change additional datasources didn't take part in transactions initiated in Grails. The transactions in additional datasources were basically in auto commit mode. In some cases this might be the wanted behavior. One reason might be performance: on the start of each new transaction, the BE1PC transaction manager creates a new transaction to each datasource. It's possible to leave an additional datasource out of the BE1PC transaction manager by setting transactional = false in the respective configuration block of the additional dataSource. Datasources with readOnly = true will also be left out of the chained transaction manager (since 2.3.7).
By default, the BE1PC implementation will add all beans implementing the Spring PlatformTransactionManager interface to the chained BE1PC transaction manager. For example, a possible JMSTransactionManager bean in the Grails application context would be added to the Grails BE1PC transaction manager's chain of transaction managers.
You can exclude transaction manager beans from the BE1PC implementation with the this configuration option:
grails.transaction.chainedTransactionManagerPostProcessor.blacklistPattern = '.*'
The exclude matching is done on the name of the transaction manager bean. The transaction managers of datasources with transactional = false or readOnly = true will be skipped and using this configuration option is not required in that case.
XA and Two-phase Commit
When the Best Efforts 1PC pattern isn't suitable for handling transactions across multiple transactional resources (not only datasources), there are several options available for adding XA/2PC support to Grails applications.
The Spring transactions documentation contains information about integrating the JTA/XA transaction manager of different application servers. In this case, you can configure a bean with the name transactionManager manually in resources.groovy or resources.xml file.
There is also Atomikos plugin available for XA support in Grails applications.
Best Efforts 1PC pattern link:
https://www.javaworld.com/article/2077963/distributed-transactions-in-spring--with-and-without-xa.html?page=2


text:
Q: Translation of sql query to Mongo languague I am trying to do the following query in Mongo:
SELECT *
FROM events
WHERE v1 - v2 > 20;

where v1 and v2 are names of columns in the SQL DB.
how can I translate it to Mongo Languague?

A: Assume you have these documents in your events:
{
    "_id" : ObjectId("54cdfde528bb923955eff8b4"),
    "v1" : 35,
    "v2" : 10
}

/* 1 */
{
    "_id" : ObjectId("54cdfde928bb923955eff8b5"),
    "v1" : 10,
    "v2" : 20
}

You cant use a simple find() query. You should use aggregation:
db.events.aggregate(
[
    { $project : { 'diff' : { $subtract : ['$v1', '$v2'] }, v1 : 1, v2 : 1 } },
    { $match : { diff : { $gt : 20} } },
    { $project : { v1 : 1, v2 : 1 } },
]).result

the result is:
{
    "0" : {
        "_id" : ObjectId("54cdfde528bb923955eff8b4"),
        "v1" : 35,
        "v2" : 10
    }
}


text:
Q: Using regression to determine the effect of a variable on changes to pre and post measures I am a stats novice, using R for my psychology dissertation.
Design:
At T1, each participant was measured on their level of the personality trait "conscientiousness".
They also reported their level of perceived well-being.
Then, they underwent an intervention.
At T2, after the intervention, they reported their level of perceived well-being, for a second time.
Statistics:
A paired samples t-test showed a significant increase in well-being from T1 to T2:
library(lsr)
pairedSamplesTTest(formula = ~ WB_T2 + WB_T1,
       data = prepost)

Output:
   Paired samples t-test

Variables:  WB_Avg2 , WB_Avg

Descriptive statistics:
            WB_Avg2 WB_Avg difference
   mean       3.169  3.006      0.162
   std dev.   0.468  0.465      0.383

Hypotheses:
   null:        population means equal for both measurements
   alternative: different population means for each measurement

Test results:
   t-statistic:  4.892
   degrees of freedom:  132
   p-value:  <.001

Other information:
   two-sided 95% confidence interval:  [0.097, 0.228]
   estimated effect size (Cohen's d):  0.424

I want to see whether this change in well-being is influenced (or mediated?) by one's level of conscientiousness.
To do this, I have tried a regression:
fit <- lm(WB_Avg ~ WB_Avg2*BF_Conscientiousness, data = prepost)
summary(fit)

Output:
Call:
lm(formula = WB_Avg ~ WB_Avg2 * BF_Conscientiousness, data = prepost)

Residuals:
     Min       1Q   Median       3Q      Max
-0.97588 -0.24927 -0.02415  0.23182  0.82299

Coefficients:
                             Estimate Std. Error t value Pr(>|t|)
(Intercept)                  -1.16709    0.85387  -1.367  0.17406
WB_Avg2                       1.23733    0.27272   4.537 1.29e-05 ***
BF_Conscientiousness          0.62495    0.23760   2.630  0.00957 **
WB_Avg2:BF_Conscientiousness -0.17303    0.07442  -2.325  0.02162 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.3397 on 129 degrees of freedom
Multiple R-squared:  0.4788,    Adjusted R-squared:  0.4667
F-statistic: 39.51 on 3 and 129 DF,  p-value: < 2.2e-16

My questions are:

*

*Have I done the t-test correctly?

*Is regression the correct
choice for determining the effect of conscientiousness on the change
in well-being?

*Have I done the regression correctly?

*If so, how do I interpret the "Coefficients:" section of the regression output?

My apologies if this is unclear or poorly worded.
Any help would be much appreciated.
Here is a link to my data file https://www.dropbox.com/s/ugxs3ju6cfwziwt/personality_pre_and_post.csv?dl=0

Thank you for the advice below, @Glen. I have three follow-up questions embedded in this edit...
I changed my model to:
lm(formula = WB_Avg2 ~ BF_Conscientiousness * WB_Avg, data = prepost)
Output:
                                Estimate Std. Error t value Pr(>|t|)
(Intercept)                  0.25410    0.88564   0.287  0.77464
BF_Conscientiousness         0.28758    0.25532   1.126  0.26211
WB_Avg                       0.91617    0.30041   3.050  0.00278 **
BF_Conscientiousness:WB_Avg -0.07971    0.08480  -0.940  0.34900

Residual standard error: 0.3509 on 129 degrees of freedom
Multiple R-squared:  0.4506,    Adjusted R-squared:  0.4379
F-statistic: 35.27 on 3 and 129 DF,  p-value: < 2.2e-16

So, if I am interpreting this right, the main effect (bottom row) is not significant. There is a significant effect of WB_Avg on WB_Avg2, but this is to be expected because the two variables are related. The p-value in the bottom right suggests the overall model is significant, but again this is because of WB_Avg and WB_Avg2 being related. So this model is not useful. Q1 Is this correct?
I get a similar output when I change the * to a +:
lm(formula = WB_Avg2 ~ BF_Conscientiousness + WB_Avg, data = prepost)

I am still not clear on what the difference is between these two models. Q2 Is the former looking for an interaction effect, and the latter an additive effect? If so, what does this mean in laymans terms?
Q3 So, am I right in concluding that although the intervention led to a significant increase in well-being, conscientiousness did not influence this increase?

A: It looks like you have done the t-test correctly.  You have a significant pre-post result (although the difference is relatively small).
For the regression model, you should have the post variable (WB_Avg2) as the outcome variable (left side) and the pre variable as the independent variable (right side).
If the interaction is significant, then you'll want to focus your analysis here.  To do this, I would make two-way interaction plots to examine how the response changes based on baseline value and BF_Conscientiousness.
If the interaction is not significant then I would remove it from the model and just focus on the main effect interpretation.  Example, if the BF_Conscientiousness coefficient is positive, then subjects with higher BF_Conscientiousness on average had a larger change in the response variable.  The pre-treatment variable will probably be positive, this just indicates larger baseline values were associated with larger post-treatment values and vice versa.
Note in your regression model the intercept term is the relevant test for whether or not the treatment had a significant effect while controlling for BF_Conscientiousness.


text:
Q: UIDocumentInteractionController preview .ics in ios6 iOS6 and xcode 5.01;
When i run with iphone simulator, it can preview the file, but with device, it failed.
//device path
NSString *path = @"/var/mobile/Applications/1AE864F5-A57F-47E7-829E-69DCFC63D8CD/tmp/11523invite.ics";
UIDocumentInteractionController *controller = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path isDirectory:NO]];
controller.delegate =self;
[controller presentPreviewAnimated:YES];

What's happend?

A: @property (nonatomic, retain) UIDocumentInteractionController *docController;

use property of UIDocumentInteractionController


text:
Q: Error: There was an error while applying the SQL script to the database Executing:
INSERT INTO leadcenter-test.user_details_final (id, account_type, email_id, first_name, is_active, is_verified, last_name, password, phone_number)
  VALUES ('1', 'ADMIN', 'bhavesh@gmail.com', 'Bhavesh', b'1', b'1', b'Jha', b'abcdef', b'8178436552');

Error:

Operation failed: There was an error while applying the SQL script to
the database. ERROR 1064: 1064: You have an error in your SQL
syntax;  check the manual that corresponds to your MySQL server
version for the right syntax to use near 'b'Jha', b'abcdef',
b'8178436552')' at line 1

How can I resolve this issue?

A: try running this query:
INSERT INTO leadcenter-test.user_details_final (id, account_type, email_id, first_name, is_active, is_verified, last_name, password, phone_number)
  VALUES ('1', 'ADMIN', 'bhavesh@gmail.com', 'Bhavesh', b'1', b'1', 'Jha', 'abcdef', '8178436552');

The main problem is that the b is added before multiple fields that are not binary. This can cause the error you are describing and as @Shadow's comment points out, there is no workaround aside from manually fixing the query every time.


text:
Q: Application-internal exception in Windows.UI.Xaml.dll I'm working on a Windows 10 Store Windows Universal app using Visual Studio 2015 Community, c#, and XAML.  It is decompressing a compressed file and displaying images found therein.
The build provides 0 warnings.
The debug version runs fine regardless of input file size.
The release version runs fine with typical input file sizes.
For large input file sizes (~100 1 megapixel images), the release build crashes consistently with 'Unhandled exception at 0x55E9A305 (Windows.UI.Xaml.dll) in appname.exe: 0xC000027B: An application-internal exception has occurred (parameters: 0x127DC468, 0x00000005).'
The crash occurs when the user tries to display the second image.  All decompression is complete and all the bitmaps have been created by this time.
I've fiddled with the Build settings and narrowed down the difference to the option 'Compile with .NET Native Tool chain'.  If that option is checked, the application crashes.  If that option is unchecked, the application runs fine.
All told, the application is using about 400 MB of heap so although not small it isn't near the capacity of the machine.
"So uncheck the option!", I hear you cry. Unchecking the box leads to the certification failure shown below:
 FAILED
 Supported APIs

• Error Found: The supported APIs test detected the following errors:
 -API OpenSemaphore in api-ms-win-core-synch-l1-1-0.dll is not supported for this application type. System.Threading.dll calls this API.
 -API CreateSemaphore in api-ms-win-core-kernel32-legacy-l1-1-0.dll is not supported for this application type. System.Threading.dll calls this API.
 -API ExecuteAssembly in uwphost.dll is not supported for this application type. StupidTest.exe calls this API.
 -API DllGetActivationFactory in uwphost.dll is not supported for this application type. StupidTest.exe has an export that forwards to this API.

An empty project suffers the same failure if Compile .Net Native tool chain is not selected.
So my questions:
Must Universal Apps use Compile .Net Native tool chain?
Is there any documentation on the meanings of the parameters in the internal exception or somewhere else I can turn to troubleshoot?
In short, any advice on getting out the "It doesn't work if selected, but you must select it to get certified" dilemma I find myself in?

A: I struggled with this issue also for the past few days, and I've found the answer!
So if you haven't updated Visual Studio 2015 to Update 1, do it. Because this error is a bug in the compiler and after the update you will be able to build the project with the Compile .Net Native tool chain option selected.
And yes, those four errors that the WACK tool picks up, is because of compiling your project without checking the .Net Native tool chain option in the Build menu of the Package.appxmanifest file.


text:
Q: Adobe® LiveCycle® ES - Whats the use of it and Alernatives of it? I am pretty much new in this.
I know Remoting, HTTPService and WebService.
I know on Messaging too.
I just want to know what's the use of LiveCycle DataServices and its Alternatives.

A: Here's a comparison between LiveCycle DataServces ES2 and Blaze:
http://192.150.8.60/products/livecycle/dataservices/compare.html


text:
Q: How to add popup window on Spring + Thymeleaf I do have some problems on how will I implement a pop-up on a link. I'm currently using Spring-boot with Thymeleaf
I'm planning to implement the pop up window upon pressing the "Edit" button. Currently it shows on a new tab.
Here's the HTML:

 Employee List

                    Add new Employee

                             Employee Name
                             Designation
                             Credentials
                             Department
                             Image
                             Image filename
                             Actions

                                <button type="button" class="btn btn-primary">Edit</button>

                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#empDeleteConfirm">Delete</button>

                                Upload Image

Are you sure?

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

                                    Do you want to delete this employee?

                                        <button type="button" class="btn btn-primary">Delete</button>
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

Here's the window to be shown on a pop up window:
<!DOCTYPE html>

 Edit Employee

                <form action="#" th:action="@{/admin/employees/update}" th:object="${employee}" method="post" th:fragment="empEdit">

                        <input type="hidden" th:field="*{name}"/>
                        <input type="hidden" th:field="*{image_fn}"/>

                             Designation:
                            <input type="text" th:field="*{designation}"/>

                             Credentials:
                            <input type="text" th:field="*{credentials}"/>

                            <select th:field="*{department}">
                                <option th:each="department: ${departments}" th:value="${department.name}" th:text="${department.description}"></option>
                            </select>

                            <button type="submit">Save</button>

                </form>

Using these controller:

import com.ppt.contentmanagementsystem.dao.DepartmentDAO;
import com.ppt.contentmanagementsystem.dao.EmployeeDAO;
import com.ppt.contentmanagementsystem.model.Department;
import com.ppt.contentmanagementsystem.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;

@Controller
public class EmployeeVC {

    @Autowired
    EmployeeDAO employeeDAO;
    @Autowired
    DepartmentDAO departmentDAO;

    @GetMapping("/admin/employees")
    public String employeesHomePage(Model model){
        List<Employee> employees = employeeDAO.getAllEmployees();
        model.addAttribute("employees", employees);
        model.addAttribute("title", "Employees");

        return "employeeHome";
    }

    @GetMapping("/admin/employees/new")
    public String newEmployeePage(Model model){
        Employee employee = new Employee();
        List<Department> departments = departmentDAO.getAllDepartments();
        model.addAttribute("employee", employee);
        model.addAttribute("departments", departments);

        return "employeeNew";
    }

    @PostMapping("/admin/employees/new")
    public String addEmployeePage(@ModelAttribute("employee") Employee employee){
        employeeDAO.addEmployee(employee);
        return "redirect:/admin/employees";
    }

    @GetMapping("/admin/employees/edit/{id}")
    public String editEmployeePage(Model model, @PathVariable String id){
        Optional<Employee> eopt = employeeDAO.getEmployee(id);
        Employee employee = eopt.get();
        List<Department> departments = departmentDAO.getAllDepartments();
        model.addAttribute("employee", employee);
        model.addAttribute("departments", departments);
        model.addAttribute("title", "Employee Edit");

        return "employeeEdit";
    }

    @GetMapping("/admin/employees/imageUpload/{id}")
    public String uploadEmployeeImagePage(Model model, @PathVariable String id){
        Optional<Employee> eopt = employeeDAO.getEmployee(id);
        Employee employee = eopt.get();
        model.addAttribute("employee", employee);
        model.addAttribute("title", "Employee Image");

        return "employeeImage";
    }

    @PostMapping("/admin/employees/imageUpload")
    public String updateEmployeeImage(@ModelAttribute("employee") Employee employee, @RequestParam("imageFile") MultipartFile imageFile) throws IOException{
        employeeDAO.saveEmployeeImage(employee, imageFile);

        return "redirect:/admin/employees";
    }

    @PostMapping("/admin/employees/update")
    public String updateEmployeePage(@ModelAttribute("employee") Employee employee){
        employeeDAO.updateEmployee(employee);

        return "redirect:/admin/employees";
    }

    @GetMapping("/admin/employees/delete/{id}")
    public String deleteEmployeePage(@PathVariable String id){
        employeeDAO.deleteEmployee(id);

        return "redirect:/admin/employees";
    }
}

A: For modal window you should add the JavaScript code to your template as described here
Thymeleaf documentation 13.4 Textual parser-level comment blocks: removing code

Simple implementation of the modal window in js is:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Modal Example

<button id="myBtn">Open Modal</button>

        ×

Some text in the Modal..

A: I've found a textual solution here: Spring MVC: Open link in new browser window in handler method
And a tutorial explaining Javascripts window.open function
https://www.youtube.com/watch?v=G83c-ZqZ7pk
Answering the question on how to open a new browser-window (popup) when clicked on an element or link.


text:
Q: why my uploading image code accept avi and flv files I write php code to allow user to submit image and upload it to the server. I get it working and the server receives the image. But it seems like the server is accepting even .avi and .flv files. I do write if/else statement for checking whether a file is an image, but why it doesn't work? Thank you
This is my php code
$tmpPath = $_FILES["image"]["tmp_name"];
$movedPath = "submit-img/" . $_POST["category"] . "/" . $_FILES["image"]["name"];

$fullURL = parse_url($_SERVER['HTTP_REFERER']);
$query = explode("&", $fullURL["query"]); //only choose first query
$prevPage = "gallery.php" . "?" . $query[0];

//I get the file type here
$fileType = strpos($_FILES["image"]["type"], "image/");

//if its not an image then redirect to the previous page and send a message
if ($fileType === false || ($_FILES["image"]["size"]) == 0 || $_FILES["image"]["size"]/1024 > 5000){
    $prevPage = $prevPage . "&imgSubmit=none#imgSubmitForm";
    header("Location: " . $prevPage);
}else if ($_FILES["image"]["size"] > 0){ //if file is an image
    if (!is_file($movedPath)){
        move_uploaded_file($tmpPath, $movedPath);
    }else{
        while (is_file($movedPath)){
            $extension = strrchr($movedPath, ".");
            $movedPath = str_replace($extension, "", $movedPath) . "1" . $extension;
        }
        move_uploaded_file($tmpPath, $movedPath);
    }
    $prevPage = $prevPage . "&imgSubmit=submitted#imgSubmitForm";
    header("Location: " . $prevPage);

}

A: }else if ($_FILES["image"]["size"] > 0){ //if file is an image

The comment on this line is fundamentally misleading. The size key in $_FILES is the size of the file in bytes; it has nothing to do with whether the "file is an image". (In particular, it is not the physical size of the image.)
If you need to test whether a file is an image, your best bet is to use the getimagesize function. This function will return the size of an image if it's an image type that PHP recognizes, or zero if it doesn't appear to be an image.
Do not use the type field of the $_FILES array to determine whether a file is an image. This field is populated by the browser, not by the server, and may contain misleading and/or flat-out incorrect information.

A: Not an answer, but your code is highly vulnerable to attacks:
1) You don't check for upload success, and assume it DID succeed. Always check for upload failure before you do anything:
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
   die("Upload failed with error code " . $_FILES['image']['error']);
}

2) You're using the ['type'] field for your validation. That's a USER-SUPPLIED value, and cannot be trusted. A malicious user can trivially manipulate that value to say image/jpeg but still be uploading nastyvirus.exe.
3) You're using the ['name'] field for storing on your server. That is also user-supplied data, and can be trivially manipulated to including pathing information, e.g. ../../../../../../../etc/passwd. Since you're using it blindly, you're allowing malicious users to scribble on any file on your server that the webserver has access to.


text:
Q: bucardo sync issue, function does not exist I have issues with adding database to sync. DB versions: PostgreSQL 9.6.8 (RDS), Jump system: Ubuntu18.04 LTS, bucardo version: 5.4.1.
When trying run this command:
bucardo add sync db_sync relgroup=copying_herd dbs=source_db:source,dest_db:target onetimecopy=1

I receive this error:
WARNING:  Issuing rollback() due to DESTROY without explicit disconnect() of DBD::Pg::db handle dbname=dc_sourcedb;host=xxx.aaa.xyz;port=5432 at line 126.
Failed to add sync: DBD::Pg::st execute failed: ERROR:  DBD::Pg::db do failed: ERROR:  function search_string(text) does not exist
LINE 5:             array_agg(search_string(x)),
                              ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
QUERY:
  SELECT
    coalesce(
        array_to_string(
            array_agg(search_string(x)),
            '|'
        )::text,
        ''
    )
  FROM unnest($1) x

CONTEXT:  SQL function "flatten_text_array" during inlining at line 126. at line 30.
CONTEXT:  PL/Perl function "validate_sync" at /usr/bin/bucardo line 4612.

Function search_string exist and I can run this function from psql command line


text:
Q: PHP exec() to open VS Code It is possible to open a directory in Visual Studio Code using this terminal command:
code /path/to/directory

Now I want to open a directory in VS Code using PHP exec(). This doesn't work however. I also tried the PHP function system(); it returns "sh: code: command not found".
How do I open VS Code using PHP?