How to reference a non-static object from a static WebMethod? - aspx, ajax

Question: I'm using a combination of aspx webforms and AJAX calls. I want to store variables privately on the C# end that are passed back and forth using ajax (then eventually save those variables to a SQL database before logout).
I've seen similar questions though I'm still unsure
Here's what some of my javascript file looks like:
$.ajax({
  type: "POST",
  url: "Index.aspx/DoStuff",
  data: JSON.stringify({ 'someVariable': varStr }),
  ...
});

My main structure of Index.aspx.cs is like so:
static SomeCollection g_Collection;

protected void Page_Load(object sender, EventArgs e)
{
  g_Collection = new SomeCollection();
}

[WebMethod]
public static string DoStuff(string someVariable)
{
  g_Collection.Add(someVariable);
}

// At some point ajax also calls another method that saves
// the g_Collection to a database *for that user* (important)
// - based on their GUID

For a single user everything works fine, however, when multiple users login the g_Collection gets saved as a singly used variable (as expected since the g_Collection variable is static).i.e. if 2 logged in users called the DoStuff() they would be adding to the same g_Collection instance.
Since the method DoStuff() is static I've declared g_Collection as static as well. How do I create instances of g_Collection instead?What do I need to declare (inside the Page_Load()?) so that g_Collection is an instance to a logged in user, while still keeping the same functionality in my static [WebMethod] methods?
Answer: I am not sure why you want to use a static member in this scenario.

If you want a collection per user, you should probably simply use a Session object.
If you want a global collection (1 for all users), an Application object.
Comment: Session Approach Fails when we open Application in Different Tab.Both Tab may send different Data.


Creating Async WCF operations in WCF +MVVM

Question: I am trying to implement MVVM for my WPF application. I have WCF services for which I want to create a data Model. My WCF does not implement callbacks.
I am having issues creating a Model for my Async WCF services.
Please provide me some sample on how to generate a function for a Asyn wcf service.
Suppose I have a WCF operation GetOrderDetails(DateTime startDate, DateTime endDate)
Then how will I go about creating a Model function using the GetOrderDetailsCompleted and GetOrderDetailsAsync
Comment: The Async aspect in this case is purely a client side thing. It's not about the service supporting async but rather the client making the call asynchronously. Does your client proxy not provide you with async methods?
Comment: I understand that async is client side thing. The proxy does provide me with Async operations. But I wish to implement MVVM. And wish to create a Model for the services on the client.
Answer: This is a purely client-side WCF issue, and is handled by the service utility code generator.
When you 'Add Service Reference...' you are able to instruct the service utility to create asynchronous operations.

'Add Service Reference...'
Click 'Advanced...'
In the Client section at the top, check the 'Generate asynchronous operations' box

The service operations will be created with asynchronous methods like OperationNameAsync(), and with additional events like OperationNameCompleted.  For samples on how to call the service asynchronously, check MSDN.
Comment: I have the Async operations generated when I add the Service reference. I am not asking on how to generate the Async operations for the Service added. But how to use these in a MVVM pattern?
Comment: Ok then you are done.  The MSDN link I provided explains how to use the async operations.


How to generate only test coverage from a specific folder with tests in Cypress

Question: I was reading Cypress docs and noticed that Cypress can generate index.html file inside coverage/lcov-report/index.html. That file contains the information about test coverage from the entire application.  Inside cypress/ folder i have another folder called main.
Question: How to generate the coverage result only taking into account the tests from that folder? At the end when i will open index.html file i need to see only the coverage from main folder.  Who can help with that? Or probably is possible to configure nyc?
Answer: Add some configuration to nyc.config.js

Using include and exclude arrays
If there are paths specified in the include array, then the set of instrumented files will be limited to eligible files found in those paths. If the include array is left undefined all eligible files will be included, equivalent to setting include: ['**']. Multiple include globs can be specified on the command line, each must follow a --include, -n switch.
Comment: there i can set the files that should be in test coverage, but i did not find a solution to include in the test report only a folder with tests not with eatures but with tests as i described in my question. Could you help?


How do I add a Remove button that removes the entire row with localstorage for shoppingcart

Question: Im new to javascript, I wanted to add a remove button on my shopping cart, how do I make one that removes 1 row from the local storage. My table for my shopping cart is in my javascript and I cant figure out how to add another function for the Remove butoon
function displayCart(){
    let cartItems = localStorage.getItem("productsInCart");
    cartItems = JSON.parse(cartItems);
    let productContainer = document.querySelector(".products");
    let cartCost = localStorage.getItem('totalCost');

    console.log(cartItems);
    if( cartItems && productContainer){
        productContainer.innerHTML = '';
        Object.values(cartItems).map(item => {
            productContainer.innerHTML += `

                <button class="btn btn-danger" onclick="removeItems()" >Remove</button>

                ${item.name}

                ₱${item.price}.00

 ${item.inCart}

                    ₱${item.inCart * item.price}.00

            `
        });

        productContainer.innerHTML += `

                Cart Total

                ₱${cartCost}.00

        `;
    }
}

I tried putting another function, localstorage.removeItem(); above that function but it doesnt work either.
Answer: remove item from object array
An example of an approach that could be used to manage your shopping cart is described here.
The cart is stored in an array of objects which is ideally suited to storing in local storage (and network transfer) as a json string, and makes for easy rendering of the data to the html page. The example data structure I have used for the example is:
    const cart = [
    {name: "shoes", price: 85, tag:"img_001", inCart: 1},
    {name: "hat", price: 42, tag:"img_002", inCart: 1},
    {name: "belt", price: 24, tag:"img_003", inCart: 2}
    ] // end cart array

To store the data in localstorage, the array would be converted to a string using JSON.stringify(cart), and the retrieved string would be converted to a javascript array using JSON.parse(stringName) (where stringName is whatever variable the read local storage was stored in).
the remove function has to know which item had its remove button clicked
the easiest way to achieve this is to include the index of each object in the cart array to it's relevant button when the cart is rendered to the html document.
So, a renderCart() function (to read the cart data and render it in the html document) would include a modified version of the button markup:
<button class="btn btn-danger" onclick="removeItems(${index})" >Remove</button>

Notice the onclick attribute now includes an index argument for your removeItems() function. The value of index has come from an optional argument in the array.map method (which can supply both the element, in this case an object, and its index position in the array):
array.map((element,index)=> {// both the element and its numerical index are available here;}

The removeItems function now receives the index of the cart array holding the data relevant to the button that was clicked. The index can be used to remove that element from the array, before calling the renderCart() function to display the modified car in the html document.:
 function removeItems(elementIndex) {
console.log(elementIndex);
cart.splice(elementIndex, 1);
renderCart();
// code to replace local storage copy of cart goes here;
 } // end function removeItems

The function should also then replace the localStorage version of the data, for which you will need another function that converts it to a json string and sets the data to localstorage.
demonstration snippet
The following snippet demonstrates these principles and should be adaptable to your particular case:

const cart = [
{name: "shoes", price: 85, tag:"img_001", inCart: 1},
{name: "hat", price: 42, tag:"img_002", inCart: 1},
{name: "belt", price: 24, tag:"img_003", inCart: 2}
] // end cart array

productContainer = document.getElementById('container');

renderCart();

function renderCart() {
productContainer.innerHTML = "";
cart.map((item, index) => {
            productContainer.innerHTML += `

                <button class="btn btn-danger" onclick="removeItems(${index})" >Remove</button>

                ${item.name}

                price (each): $${item.price}.00

 quantity: ${item.inCart}

                total: $${item.inCart * item.price}.00

           `
        });
 } // end function renderCart

 function removeItems(elementIndex) {
console.log(elementIndex);
cart.splice(elementIndex, 1);
renderCart();
// code to replace local storage copy of cart goes here;
 } // end function removeItems


aws elastic beans container commands

Question: I am trying to copy Apache server setup file wsgi.conf to httpd/conf.d folder when deploying myapp via elastic beanstalk. However, after deployment, if I sftp to httpd/conf.d I don't see my file.
myapp folder structure:
myapp/
- .ebextension
--- configuration.conf
- folderx
- foldery
- wsgi.conf

in the configuration.conf file i have the following:
container_commands:
  04_wsgireplace:
    command: "cp ../wsgi.conf /etc/httpd/conf.d/wsgi.conf"

after deployment, in the eb deployment logs I see success for the copy command.

are the relative paths I'm using correct?
what am I doing wrong?

PS. What I want to achieve is set a rewrite rule for http --> https re-directions. Is there an alternative solution for this?
Thanks.
Answer: I wish I could find something more official, but I did find several references (1,2) to folks using something like this:
container_commands:
  04_wsgireplace:
    command: "cp wsgi.conf ../wsgi.conf"

or
container_commands:
  04_wsgireplace:
    command: "cp .ebextensions/wsgi.conf ../wsgi.conf"

It depends on where in your project you've stored wsgi.conf, I assume.  I'm about to try it myself (for a flask project), and I'll report back!
Update: I tried it out (with wsgi.conf in .ebextensions), and it worked (for me).

aws elastic beans container commands


Even if no errors on Compilation and Runtime, Program output is not as expected

Question: A Java Swing applet which includes 3 Checkboxes and a TextField. The specified checkbox when clicked displays title assigned to the corresponding checkbox in the given TextField. The problem is that even if no errors on Compilation and Runtime, a blank frame is shown as output..!!
here is the Java code :
SwingAll class :
package swingall;

import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class SwingAll extends JFrame implements ItemListener {

JTextField t1;
JCheckBox c1,c2,c3;

public void init()
{
    Container cp=getContentPane();
    t1=new JTextField(20);
    c1=new JCheckBox("Arts");
    c2=new JCheckBox("Commerce");
    c3=new JCheckBox("Science");
    add(c1);
    add(c2);
    add(c3);
    add(t1);
    c1.addItemListener(this);
    c2.addItemListener(this);
    c3.addItemListener(this);
}

public void itemStateChanged(ItemEvent e) {

    if (e.getSource()==c1)
    {
        t1.setText("Arts");
    }
    if (e.getSource()==c2)
    {
        t1.setText("Commerce");
    }
    if (e.getSource()==c3)
    {
        t1.setText("Science");
    }
}
}

The Main Class is :
package swingall;

public class Main {

public static void main(String[] args) {

    SwingAll sg=new swingAll();
    sg.setSize(500, 500);
    sg.setVisible(true);
}
}

Comment: Even if it compiles and runs, code does what you tell it to do, not what you *think* you're telling it to do.
Comment: Which part of your code do you expect to prevent that?
Answer: You never called your init() method.
Therefore, you never put anything into the frame.
Answer: You dont call your init-method.
Add a constructor
public SwingAll () {
   init();
}

Answer: you need to make your class init() to constructor which it should be SwingAll
try adding private static final long serialVersionUID = 1L;
i don't see a title for the window try setting
super("window name");

and
 setDefaultCloseOperation(EXIT_ON_CLOSE);

Answer: As mentioned in other answers, init() was not being called.  OTOH, when it is, only one component is displayed.  This variant fixes both problems.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingAll extends JFrame implements ItemListener {

JTextField t1;
JCheckBox c1,c2,c3;

public void init()
{
    // end the JVM when frame is closed.
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    Container cp=getContentPane();
    // set a layout that takes many components without a
    // constraint and displays them.
    cp.setLayout(new FlowLayout());
    t1=new JTextField(20);
    c1=new JCheckBox("Arts");
    c2=new JCheckBox("Commerce");
    c3=new JCheckBox("Science");
    add(c1);
    add(c2);
    add(c3);
    add(t1);
    c1.addItemListener(this);
    c2.addItemListener(this);
    c3.addItemListener(this);
    // pack the GUI to the size needed to display the content
    pack();
}

public void itemStateChanged(ItemEvent e) {

    if (e.getSource()==c1)
    {
        t1.setText("Arts");
    }
    if (e.getSource()==c3)
    {
        t1.setText("Commerce");
    }
    if (e.getSource()==c3)
    {
        t1.setText("Science");
    }
}

public static void main(String[] args) {
    // should be started on the EDT.
    SwingAll sg= new SwingAll();
    sg.init();
    sg.setVisible(true);
}
}

Other tips

// should be started on the EDT.  Swing GUIs should be started and updated on the Event Dispatch Thread - left as an exercise for the user.
The default layout of a frame is BorderLayout.  This layout has 5 possible areas that can be specified by constraints, each of which can hold exactly one component.  By adding the components to the border layout without constraints, they all defaulted to BorderLayout.CENTER.
Don't set the size of the GUI, simply call pack() after the components are added.
If those check-boxes should be 'one only at a time', look to JRadioButton and ButtonGroup.
Comment: cp.setLayout(new FlowLayout()); that's what I forgot to give and also I didn't called init() as you mentioned earlier.....thanks a lot Sir....java is challenging always....!! done...output is shown as mentioned above...!!


By completing the square, show that $\int_{0}^{\frac{1}{2}}\frac{dx}{x^2-x+1}=\frac{\pi }{3\sqrt{3}}$

Question: By completing the square, show that $\int_{0}^{\frac{1}{2}}\frac{dx}{x^2-x+1}=\frac{\pi }{3\sqrt{3}}$. I found that $\int_{0}^{\frac{1}{2}}\frac{dx}{x^2-x+1}$ equals to $\int_{0}^{\frac{1}{2}}\frac{x+1}{x^3+1}dx$ so it becomes $\sum_{n=0}^{\infty}\frac{(-1)^{n}x^{3n+1}}{(3n+1)}+\sum_{n=0}^{\infty}\frac{(-1)^{n}x^{3n+2}}{(3n+2)}$, but can't go any further.
Comment: What you found is not completing the square.
Comment: If you can write $x^2-x+1=(x+b)^2+b^2$ the substitution $u=x+b$ helps a LOT.
Comment: Can someone explain how to transform the integral in the series?
Comment: @JpMcCarthy why do you have two $b$'s there?
Comment: @Kaster because I am an idiot! Of course it should be $(x+b)^2+a^2$ of course thank you.
Answer: It goes like this: $x^2 - x + 1 = (x - \dfrac{1}{2})^2 + (\sqrt{3}/2)^2$, and you can take: $u = \sqrt{3}/2\cdot tan(x -\frac{1}{2})$ to transform it into an $tan^{-1}$ anti derivative form.
Answer: Complete the square in denominator per your own hint.
\begin{align}
I &= \int_0^{\frac 12} \frac {dx}{x^2-x+1} = \int_0^{\frac 12} \frac {dx}{\left ( x^2 -x + \frac 14\right ) + \frac 34} = \int_0^{\frac 12} \frac {dx}{\left( x- \frac 12\right)^2 + \frac 34} = \\
&= \int_{-\frac 12}^0 \frac {dt}{t^2 + \frac 34} = \left . \frac 2{\sqrt 3} \arctan \frac {2t}{\sqrt 3} \right |_{-\frac 12}^0 = ???
\end{align}
Can you take it from here?


Getting started with Intel x86 SSE SIMD instructions

Question: I want to learn more about using the SSE.
What ways are there to learn, besides the obvious reading the Intel® 64 and IA-32 Architectures Software Developer's Manuals?
Mainly I'm interested to work with the GCC X86 Built-in Functions.
Answer: First, I don't recommend on using the built-in functions - they are not portable (across compilers of the same arch).
Use intrinsics, GCC does a wonderful job optimizing SSE intrinsics into even more optimized code. You can always have a peek at the assembly and see how to use SSE to it's full potential.
Intrinsics are easy - just like normal function calls:
#include <immintrin.h>  // portable to all x86 compilers

int main()
{
    __m128 vector1 = _mm_set_ps(4.0, 3.0, 2.0, 1.0); // high element first, opposite of C array order.  Use _mm_setr_ps if you want "little endian" element order in the source.
    __m128 vector2 = _mm_set_ps(7.0, 8.0, 9.0, 0.0);

    __m128 sum = _mm_add_ps(vector1, vector2); // result = vector1 + vector 2

    vector1 = _mm_shuffle_ps(vector1, vector1, _MM_SHUFFLE(0,1,2,3));
    // vector1 is now (1, 2, 3, 4) (above shuffle reversed it)
    return 0;
}

Use _mm_load_ps or _mm_loadu_ps to load data from arrays.
Of course there are way more options, SSE is really powerful and in my opinion relatively easy to learn.
See also https://stackoverflow.com/tags/sse/info for some links to guides.
Comment: Make a question for it, and I'll make sure to help :)
Comment: @evandrix: `x86intrin.h` is gcc/clang only (and maybe ICC).  Definitely not available on MSVC.  The correct catch-all portable header for SSE/AVX intrinsics is `immintrin.h`.  It was a good idea to replace `xmmintrin.h` (because that only defines  SSE1 intrinsics), though.
Comment: Do you know hot to make a dot product of two arrays of int32 elements each?
Answer: Since you asked for resources:
A practical guide to using SSE with C++: Good conceptual overview on how to use SSE effectively, with examples.
MSDN Listing of Compiler Intrinsics: Comprehensive reference for all your intrinsic needs. It's MSDN, but pretty much all the intrinsics listed here are supported by GCC and ICC as well.
Christopher Wright's SSE Page: Quick reference on the meanings of the SSE opcodes. I guess the Intel Manuals can serve the same function, but this is faster.
It's probably best to write most of your code in intrinsics, but do check the objdump of your compiler's output to make sure that it's producing efficient code. SIMD code generation is still a fairly new technology and it's very possible that the compiler might get it wrong in some cases.
Answer: I find Dr. Agner Fog's research & optimization guides very valuable!  He also has some libraries & testing tools that I have not tried yet.
http://www.agner.org/optimize/
Answer: Step 1: write some assembly manually
I recommend that you first try to write your own assembly manually to see and control exactly what is happening when you start learning.
Then the question becomes how to observe what is happening in the program, and the answers are:

GDB
use the C standard library to print and assert things

Using the C standard library yourself requires a little bit of work, but nothing much. I have for example done this work nicely for you on Linux in the following files of my test setup:

lkmc.h
lkmc.c
lkmc/x86_64.h

Using those helpers, I then start playing around with the basics, such as:

load and store data to / from memory into SSE registers
add integers and floating point numbers of different sizes
assert that the results are what I expect

addpd.S
#include <lkmc.h>

LKMC_PROLOGUE
.data
    .align 16
    addps_input0: .float 1.5, 2.5,  3.5,  4.5
    addps_input1: .float 5.5, 6.5,  7.5,  8.5
    addps_expect: .float 7.0, 9.0, 11.0, 13.0
    addpd_input0: .double 1.5, 2.5
    addpd_input1: .double 5.5, 6.5
    addpd_expect: .double 7.0, 9.0
.bss
    .align 16
    output:       .skip 16
.text
    /* 4x 32-bit */
    movaps addps_input0, %xmm0
    movaps addps_input1, %xmm1
    addps %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, addps_expect, $0x10)

    /* 2x 64-bit */
    movaps addpd_input0, %xmm0
    movaps addpd_input1, %xmm1
    addpd %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, addpd_expect, $0x10)
LKMC_EPILOGUE

GitHub upstream.
paddq.S
#include <lkmc.h>

LKMC_PROLOGUE
.data
    .align 16
    input0:       .long 0xF1F1F1F1, 0xF2F2F2F2, 0xF3F3F3F3, 0xF4F4F4F4
    input1:       .long 0x12121212, 0x13131313, 0x14141414, 0x15151515
    paddb_expect: .long 0x03030303, 0x05050505, 0x07070707, 0x09090909
    paddw_expect: .long 0x04030403, 0x06050605, 0x08070807, 0x0A090A09
    paddd_expect: .long 0x04040403, 0x06060605, 0x08080807, 0x0A0A0A09
    paddq_expect: .long 0x04040403, 0x06060606, 0x08080807, 0x0A0A0A0A
.bss
    .align 16
    output:       .skip 16
.text
    movaps input1, %xmm1

    /* 16x 8bit */
    movaps input0, %xmm0
    paddb %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddb_expect, $0x10)

    /* 8x 16-bit */
    movaps input0, %xmm0
    paddw %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddw_expect, $0x10)

    /* 4x 32-bit */
    movaps input0, %xmm0
    paddd %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddd_expect, $0x10)

    /* 2x 64-bit */
    movaps input0, %xmm0
    paddq %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddq_expect, $0x10)

LKMC_EPILOGUE

GitHub upstream.
Step 2: write some intrinsics
For production code however, you will likely want to use the pre-existing intrinsics instead of raw assembly as mentioned at: https://stackoverflow.com/a/1390802/895245
So now I try to convert the previous examples into more or less equivalent C code with intrinsics.
addpq.c
#include <assert.h>
#include <string.h>

#include <x86intrin.h>

float global_input0[] __attribute__((aligned(16))) = {1.5f, 2.5f, 3.5f, 4.5f};
float global_input1[] __attribute__((aligned(16))) = {5.5f, 6.5f, 7.5f, 8.5f};
float global_output[4] __attribute__((aligned(16)));
float global_expected[] __attribute__((aligned(16))) = {7.0f, 9.0f, 11.0f, 13.0f};

int main(void) {
    /* 32-bit add (addps). */
    {
        __m128 input0 = _mm_set_ps(1.5f, 2.5f, 3.5f, 4.5f);
        __m128 input1 = _mm_set_ps(5.5f, 6.5f, 7.5f, 8.5f);
        __m128 output = _mm_add_ps(input0, input1);
        /* _mm_extract_ps returns int instead of float:
        * * https://stackoverflow.com/questions/5526658/intel-sse-why-does-mm-extract-ps-return-int-instead-of-float
        * * https://stackoverflow.com/questions/3130169/how-to-convert-a-hex-float-to-a-float-in-c-c-using-mm-extract-ps-sse-gcc-inst
        * so we must use instead: _MM_EXTRACT_FLOAT
        */
        float f;
        _MM_EXTRACT_FLOAT(f, output, 3);
        assert(f == 7.0f);
        _MM_EXTRACT_FLOAT(f, output, 2);
        assert(f == 9.0f);
        _MM_EXTRACT_FLOAT(f, output, 1);
        assert(f == 11.0f);
        _MM_EXTRACT_FLOAT(f, output, 0);
        assert(f == 13.0f);

        /* And we also have _mm_cvtss_f32 + _mm_shuffle_ps, */
        assert(_mm_cvtss_f32(output) == 13.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 1)) == 11.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 2)) ==  9.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 3)) ==  7.0f);
    }

    /* Now from memory. */
    {
        __m128 *input0 = (__m128 *)global_input0;
        __m128 *input1 = (__m128 *)global_input1;
        _mm_store_ps(global_output, _mm_add_ps(*input0, *input1));
        assert(!memcmp(global_output, global_expected, sizeof(global_output)));
    }

    /* 64-bit add (addpd). */
    {
        __m128d input0 = _mm_set_pd(1.5, 2.5);
        __m128d input1 = _mm_set_pd(5.5, 6.5);
        __m128d output = _mm_add_pd(input0, input1);
        /* OK, and this is how we get the doubles out:
        * with _mm_cvtsd_f64 + _mm_unpackhi_pd
        * https://stackoverflow.com/questions/19359372/mm-cvtsd-f64-analogon-for-higher-order-floating-point
        */
        assert(_mm_cvtsd_f64(output) == 9.0);
        assert(_mm_cvtsd_f64(_mm_unpackhi_pd(output, output)) == 7.0);
    }

    return 0;
}

GitHub upstream.
paddq.c
#include <assert.h>
#include <inttypes.h>
#include <string.h>

#include <x86intrin.h>

uint32_t global_input0[] __attribute__((aligned(16))) = {1, 2, 3, 4};
uint32_t global_input1[] __attribute__((aligned(16))) = {5, 6, 7, 8};
uint32_t global_output[4] __attribute__((aligned(16)));
uint32_t global_expected[] __attribute__((aligned(16))) = {6, 8, 10, 12};

int main(void) {

    /* 32-bit add hello world. */
    {
        __m128i input0 = _mm_set_epi32(1, 2, 3, 4);
        __m128i input1 = _mm_set_epi32(5, 6, 7, 8);
        __m128i output = _mm_add_epi32(input0, input1);
        /* _mm_extract_epi32 mentioned at:
        * https://stackoverflow.com/questions/12495467/how-to-store-the-contents-of-a-m128d-simd-vector-as-doubles-without-accessing/56404421#56404421 */
        assert(_mm_extract_epi32(output, 3) == 6);
        assert(_mm_extract_epi32(output, 2) == 8);
        assert(_mm_extract_epi32(output, 1) == 10);
        assert(_mm_extract_epi32(output, 0) == 12);
    }

    /* Now from memory. */
    {
        __m128i *input0 = (__m128i *)global_input0;
        __m128i *input1 = (__m128i *)global_input1;
        _mm_store_si128((__m128i *)global_output, _mm_add_epi32(*input0, *input1));
        assert(!memcmp(global_output, global_expected, sizeof(global_output)));
    }

    /* Now a bunch of other sizes. */
    {
        __m128i input0 = _mm_set_epi32(0xF1F1F1F1, 0xF2F2F2F2, 0xF3F3F3F3, 0xF4F4F4F4);
        __m128i input1 = _mm_set_epi32(0x12121212, 0x13131313, 0x14141414, 0x15151515);
        __m128i output;

        /* 8-bit integers (paddb) */
        output = _mm_add_epi8(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x03030303);
        assert(_mm_extract_epi32(output, 2) == 0x05050505);
        assert(_mm_extract_epi32(output, 1) == 0x07070707);
        assert(_mm_extract_epi32(output, 0) == 0x09090909);

        /* 32-bit integers (paddw) */
        output = _mm_add_epi16(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04030403);
        assert(_mm_extract_epi32(output, 2) == 0x06050605);
        assert(_mm_extract_epi32(output, 1) == 0x08070807);
        assert(_mm_extract_epi32(output, 0) == 0x0A090A09);

        /* 32-bit integers (paddd) */
        output = _mm_add_epi32(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04040403);
        assert(_mm_extract_epi32(output, 2) == 0x06060605);
        assert(_mm_extract_epi32(output, 1) == 0x08080807);
        assert(_mm_extract_epi32(output, 0) == 0x0A0A0A09);

        /* 64-bit integers (paddq) */
        output = _mm_add_epi64(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04040404);
        assert(_mm_extract_epi32(output, 2) == 0x06060605);
        assert(_mm_extract_epi32(output, 1) == 0x08080808);
        assert(_mm_extract_epi32(output, 0) == 0x0A0A0A09);
    }

    return 0;

GitHub upstream.
Step 3: go and optimize some code and benchmark it
The final, and most important and hard step, is of course to actually use the intrinsics to make your code fast, and then to benchmark your improvement.
Doing so, will likely require you to learn a bit about the x86 microarchitecture, which I don't know myself. CPU vs IO bound will likely be one of the things that comes up: What do the terms "CPU bound" and "I/O bound" mean?
As mentioned at: https://stackoverflow.com/a/12172046/895245 this will almost inevitably involve reading Agner Fog's documentation, which appear to be better than anything Intel itself has published.
Hopefully however steps 1 and 2 will serve as a basis to at least experiment with functional non-performance aspects and quickly see what instructions are doing.
TODO: produce a minimal interesting example of such optimization here.
Comment: IDK if it's a good idea to mention Linux kernel modules using SIMD without warning that you need `kernel_fpu_begin()` / `_end()` around your SIMD code.  An LKM is the last place you would expect to find SIMD, and the hardest place to test it, so it seems maybe confusing to bring that up as the first steps in an intro-to-SIMD answer.
Comment: @PeterCordes hi Pete, everything under userland/ in that crazy repo is, well, userland programs :-) (ARM asm / C ones also run in baremetal via Newlib + crosstool-NG btw, not done for x86 only because lazy).  Kernel modules are under kernel_modules/  I had never tried floating operations in kernel modules, good to know about `kernel_fpu_begin()`. I hacked up an example right now for fun [here](https://github.com/cirosantilli/linux-kernel-module-cheat/blob/819ef42ea418dc9351716f259fb36945627c3bbc/kernel_modules/float.c).
Answer: You can use the SIMD-Visualiser to graphically visualize and animate the operations. It'll greatly help understanding how the data lanes are processed


About an example of split chain complex of vector spaces

Question: I can't understand an example Weibel gives in his Introduction to Homological Algebra, page 15.
So let $C.$ be any chain complex of vector spaces over a field. We use the following decomposition:
$$C_n=Z_n\oplus B_n'$$
where $B_n'\cong C_n/Z_n=d(C_n)=B_{n-1}$, and
$$Z_n=B_n\oplus H_n'$$
where $H_n'\cong Z_n/B_n=H_n(C)$
Therefore we can form the composition
$$C_n\longrightarrow Z_n\longrightarrow B_n\cong B_{n+1}'\subseteq C_{n+1}$$
to get splitting maps $s_n:C_n\longrightarrow C_{n+1}$ such that $d=dsd$.
What I can't understand is why $d=dsd$.
Answer: This is related to Exercise 1.1.3 on page 2 of Weibel :-)
OK, so we have a complex of vector spaces
$$\cdots \to C_{n+1} \xrightarrow{d_{n+1}} C_n \xrightarrow{d_n} C_{n-1} \to \cdots$$
By definition, $Z_n = \ker d_n$, $B_n = \operatorname{im} d_{n+1}$, and we have short exact sequences
$$0 \to B_n \to Z_n \to H_n \to 0$$
and
$$0 \to Z_n \to C_n \xrightarrow{d_n} B_{n-1} \to 0$$
Since we are working over a field, there are some subspaces $H_n' \subseteq Z_n$, $H_n' \cong H_n$ and $B_{n-1}'\subseteq C_n$, $d_n\colon B_n' \xrightarrow{\cong} B_{n-1}$, such that
$$Z_n = B_n \oplus H_n' \quad\text{and}\quad C_n \cong Z_n \oplus B_n'.$$ So we have a decomposition
$$C_n \cong B_{n+1}' \oplus H_n' \oplus B_n',$$
and the differential $d_n\colon C_n\to C_{n-1}$ under this decomposition is given by
\begin{align*}
d_n\colon B_{n+1}' \oplus H_n' \oplus B_n' & \to B_n' \oplus H_{n-1}' \oplus B_{n-1}',\\
(x,y,z) & \mapsto (z,0,0).
\end{align*}
The splitting $s_n\colon C_n\to C_{n+1}$ is given under this decomposition by
\begin{align*}
s_n\colon B_{n+1}' \oplus H_n' \oplus B_n' & \to B_{n+2}' \oplus H_{n+1}' \oplus B_{n+1}',\\
(x,y,z) & \mapsto (0,0,x).
\end{align*}
Now
$$d_n\circ s_{n-1}\circ d_n (x,y,z) = (z,0,0) = d_n (x,y,z).$$
Comment: $d$ corresponds to $(x,y,z) \mapsto (z,0,0)$. And $(x,y,z) \mapsto (0,0,x)$ is the definition of $s$.
Comment: $x$ and $y$ go to zero, and $z \in B_n'$ goes to the corresponding component of $C_{n-1}$.
Comment: Maybe this notation is confusing. $B_n'$ denotes something that is isomorphic to $\operatorname{im} d_n = B_{n-1}$. And $H_n'$ is isomorphic to $H_n = \ker d_n / \operatorname{im} d_{n+1}$.
Comment: I can't get why does $d$ correspond to $(x,y,x)\to (0,0,x)$ under that iso. I mean, I can see why $x$ goes to zero, since $x\in\operatorname{Im}(d_{n+1})$ and $d_n\circ d_{n+1}=0$, but not the rest
Comment: Yes ok, because $B'_{n+1}$ is in both factorizations. But why $y$ and $z$ go to zero under $d$?


Single worker thread for all tasks or multiple specific workers?

Question: I'm creating a simple GUI application using PyQt5 where I request some data from an API which is then used to populate various controls of the UI.
The examples I was following about worker threads in PyQt all seem to sub-class QThread and then do their business logic in the overridden run() method. This works fine but I want to execute different API calls at different times using a worker.
So my question is: do I need to create a specific worker thread for every operation I wish to do or is there a way of having a single thread class that I can use to carry out different operations at different times and therefore avoid the overhead of creating different thread sub-classes?
Comment: You shouldn't be subclassing `QThread`. Instead, use `QtConcurrent::run`, or perhaps subclass `QObject`, and move these worker objects to a single worker thread.
Answer: What you can do is design an object to do all these tasks (inherit QObject for slots / signals). Lets say each task is defined as a separate function - lets designate these functions as slots.
Then (a general order of events):

instantiate a QThread object.
instantiate your class.
Move your object into the thread using YouClass->moveToThread(pThread).
Now define a signal for each slot and connect these signals to the relevant slots in your object.
Finally run the thread using pThread->start()

Now you can emit a signal to do a particular task in the thread. You do not need to sub-class QThread just use a normal class derived from QObject (so that you can use slots/signals).
You can either use one class in one thread to do many operations (note: they will be queued). Or make many classes in many threads (to run "parallel").
I don't know python well enough to attempt an example here so I won't :o
Note: The reason to sub-class QThread would be if you wanted to extend the functionality of the QThread class - i.e. add more/specific thread-related functions. QThread is a class that controls a thread, and is not meant to be used to run arbitrary/generic tasks... even though you can abuse it to do so if you wish :)
Comment: Excellent answer, especially they hint that the jobs will automatically be queued. Maybe I'll write an example for that.
Comment: @Trilarion thanks, and yes please feel free to add examples : )
Comment: Are we able to give the QThread more than 1 thread to run on in case needs more computing bandwidth? I am under the impression that a QThread literally means it can only have 1 thread
Comment: @fatbringer - yes QThread manages one single thread. However [QThreadPool](https://doc.qt.io/qt-6/qthreadpool.html) manages a pool of QThreads :)
Answer: Here is a concise example of one (but could be as many as you wish) worker object which is moved to a single running QThread (started) and is communicating via signals. Also the thread is stopped at the end. It demonstrates what code_fodder outlined in his answer.
from PyQt4 import QtCore
QtCore.Signal = QtCore.pyqtSignal

class Master(QtCore.QObject):

    command = QtCore.Signal(str)

    def __init__(self):
        super().__init__()

class Worker(QtCore.QObject):

    def __init__(self):
        super().__init__()

    def do_something(self, text):
        print('current thread id = {}, message to worker = {}'.format(int(QtCore.QThread.currentThreadId()), text))

if __name__ == '__main__':

    app = QtCore.QCoreApplication([])

    # give us a thread and start it
    thread = QtCore.QThread()
    thread.start()

    # create a worker and move it to our extra thread
    worker = Worker()
    worker.moveToThread(thread)

    # create a master object and connect it to the worker
    master = Master()
    master.command.connect(worker.do_something)

    # call a method of the worker directly (will be executed in the actual thread)
    worker.do_something('wrong way to communicate with worker')

    # communicate via signals, will execute the method now in the extra thread
    master.command.emit('right way to communicate with worker')

    # start the application and kill it after 1 second
    QtCore.QTimer.singleShot(1000, app.quit)
    app.exec_()

    # don't forget to terminate the extra thread
    thread.quit()
    thread.wait(5000)


How to make libs editable? Possible? (coding amateur)

Question: I use the achartengine libs and downloaded the achartengine-1.0.0.jar from google. I imported the library into my code and recognized that I can ONLY read it but I'd like to apply some patches. How can I make a library editable?
I use Android Studio.
Comment: possible duplicate of [How to build the achartengine library after modification?](http://stackoverflow.com/questions/25463308/how-to-build-the-achartengine-library-after-modification)
Answer: In the jar-File are only the compiled .class-Files, no .java-Files.
If you want to edit or patch, you need the src-.java-Files. Here you can check out the SVN-Project:
https://code.google.com/p/achartengine/source/checkout
Here you can see the files, which you would need, if you want to edit the library:
https://code.google.com/p/achartengine/source/browse/#svn%2Ftrunk%2Fachartengine%2Fsrc%2Forg%2Fachartengine%253Fstate%253Dclosed
Comment: Yes, I downloaded the whole SVN-Project and then patch it, now I have to create a jar-File again but how?
Comment: Why you do not just put the source files into your project? Then you can patch whenever you want and you will not be forced to get the source files from that `.jar` again. Anyway if you want to create a jar: http://docs.oracle.com/javase/tutorial/deployment/jar/build.html
Comment: OMG You are a GENIUS. Thank You! You were the first person who helped me friendly. Thank You!
Answer: Most Android Libraries have a pom.xml file which means that it should be built by maven. Install it, and navigate to the directory containing that file. Then mvn install. Reading the output, you will see where the artifacts(the jar) is stored.


Balance and proportions

Question: This question is a weird one because I've already solved the problem but I'm not quite happy in the process. Here is question:
We have a recipie for an orange juice cocktail of 130cc. In order to obtain the best cocktail on the earth you have to mix 7 parts of water with 3 parts of orange juice (uhmm not so juicy) but unfortanetly you have only a brick with a juice made 50% of water and 50% of orange juice. How much water you have to add to keep the ratio intact?
My thinking process was logical and not strictly mathematical. So if I have to keep the juyce to 3 parts, this will automatically add 3 parts of water that must be subtracted by the 7 part max we can add.
So we have to add 4 parts more to achieve the desired ration. How much water in cc we hate to add? First we have to find how many cc is a "part" and this will be
$$7x+3x = 130$$
so one part is 13cc. Then is straight forward:
$$ 13 * 4 = 52$$
52cc is our ansewer! The problem is that I have very hard time to put this stuff in mathematical terms and reduce my thinking process to a system of equations. . . Any help?
Answer: Out of the $130$ cc of final product, we want $39$ cc of pure orange juice.  We can get that by using $\frac {39}{0.5}=78$ cc of the brick.  We also want $91$ cc of water.  We got $39$ cc of that from the brick, so we need to add $91-39=52$ cc of water.
Comment: Or *slightly* simpler:  You put in $78$ cc of "stuff", to have the juice you want, so you need $52$ cc of water to make $130$ cc total you want...
Answer: Denote the amount of pure water that has te be added with $x$.  The unknown $y$ is the volume of bricky orange juice you need.
The total amount of liquid is then $x+y$.  This has to be $130 cc$ so:
$$
x + y = 130 $$
The amount of water in the liquid is $x + \frac{1}{2} y$, because half of the content of the brick is pure water.  The ratio of water to orange juice has to be 7/10.  Hence:
$$
\frac{x + \frac{1}{2}y}{x + y} = \frac{7}{10}.
$$
We simplify this equation
$$
10 x + 5y = 7x +7y,
$$
and putting everything to the same side of the equation, we get
$$
3x - 2y = 0.
$$
Now you have a system of two linear equations with two unkown:
\begin{cases}
x + y = 130 \\ 3x - 2 y = 0
\end{cases}
Have fun solving this for $x$ and $y$.
Comment: Hold on a sec! I realise this is not entirely what you want.  I shall edit!
Comment: Great! I was almost there but what I did was 1/2x + 1/2y = 1 and got stuck. . .

Balance and proportions


Using a function in Matlab

Question: Very new to MATLAB and Im trying to use the FFT function. I got a video which showed me that a function and a normal m file is needed. Created that but now dont know how to call the function from the m file. Here's is the function:
function [ X,freq ] = positiveFFT( x,Fs )
%This function takes data,and discards negatives only taking the
%positives,getting rid of complex values
%adopted from blinkdagger.com

N=length(x);
k=0:N-1;
T=N/Fs;
freq=k/T; %create the frequency range
X=fft(x)/N; %normalise the data
cutOff=ceil(N/2); %cut off frequency
X=X(1:cutOff);
freq=freq(1:cutOff);
end
and the m-file:fo=4; %freqency of the sine wave(4cycles,4Hz)
Fs=100; %sampling rate
Ts=1/Fs; %sampling time interval
t=0:Ts:1-Ts;
n=length(t); %number of samples
y=2*sin(2*pi*fo*t);
[YfreqD,freqRng]=positiveFFT(y,Fs);
stem(freqRng,abs(YFreqD));
Answer: @manny264
It looks like you ARE calling the function positiveFFT from within the m-file. the positiveFFT function in turn is calling the fft function of matlab.
[YfreqD,freqRng]=positiveFFT(y,Fs);
it is calling the function from within the "main". Not clear what else you expect it to do.
Answer: I think you should change
stem(freqRng,abs(YFreqD));

as
stem(freqRng,abs(YfreqD));

Comment: actually didnt notice that thanx alot...guess it was the pressure to hand in the assignment on time
Comment: You are welcome

Using a function in Matlab


Showing the associated graded group of a separated, filtered group $G$ is an $R$-Lie Algebra

Question: Let $G$ be the group of $3 \times 3$ upper unitriangular matrices with entries in $R$, a commutative ring:
$$G = \left\{ \left(\matrix{1 & x & z \\ 0 & 1 & y \\ 0 & 0 & 1}\right) \mid x,y,z \in R\right\}$$
I am asked to show that if we give $G$ the filtration:
$\omega(g) = \sup\{n \in \mathbb N \mid g \in \gamma_n(G)\}$, where the $\gamma_n(G)$ are the lower central series of $G$, then:
$(G, \omega)$ is a separated filtration and:
$grG$, the associated graded group of $(G,\omega)$ is an $R$-Lie Algebra: $RX \bigoplus RZ \bigoplus RY$, where:
$gr_1G = RX \bigoplus RY, \; gr_2G = RZ$,
and $[X,Y] = Z, [X,Z] = [Y,Z] = 0$
First of all, I considered the matrices: $X = \left(\matrix{1 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}\right), Y = \left(\matrix{1 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1}\right), Z = \left(\matrix{1 & 0 & 1 \\ 0 & 1 & 0 \\ 0 & 0 & 1}\right)$,
and taking the Lie Bracket to be the commutator, then we get the relations we want, which would mean that, if $X,Y,Z$ multiplicatively generate G, then:
$\gamma_1(G) = G$ by definition
$\gamma_2(G) = \langle Z \rangle$
$\gamma_3(G) = \{I\}$
Which means that:

$(G, \omega)$ is separated as $G$ is nilpotent.
$G_1 = \{g \in G \mid \omega(g) \geq 1\} = \langle X,Y,Z\rangle = G$
$G_{1^+} = \{g \in G \mid \omega(g) > 1\} = G_2 = \langle Z \rangle $
$G_3 = \{I\}$

Therefore:

$gr_1G = G_1 / G_{1^+} = \langle X, Y\rangle$
$gr_2G = G_2 / G_{2^+} = \langle Z \rangle $

So by the commutative properties of the associated graded group, we see that we must in fact have $gr_1G, gr_2G$ being commutative, so:
$gr_1G = RX \bigoplus RY, \; gr_2G = RZ$ as required.
That this is an $R$-Lie Algebra is, I believe, a simple check, so we are effectively done presuming we can show that $\langle X, Y, Z \rangle = G$.
In my working I noted that by multiplication on the left, using $X, Y, Z$, we can generate the subgroup of $G$ with entries taken from a subring of $R$, isomorphic to $\mathbb Z$. However, I don't know how I can extend this to include the rest of the entries from $R$ as $R$ is a general, commutative ring.
This then makes me think perhaps we need more than just $X, Y, Z $, but then there would be problems with showing that the filtration is separated.
I believe it might be possible that I am approaching this question from the wrong path, but I am unsure of how to fix it. Any help would be appreciated, thank you.
Comment: Sorry, can you make a bit clearer what you have already proved and what your actual question is?
Comment: @TorstenSchoeneberg how can I show that the associated graded group $grG$ is an $R$-Lie Algebra of the above form? I believe I have effectively proven it in the case that $R = \mathbb Z$, but when this is not the case I do not know what to do.
Comment: But what fails in the case of general $R$? If the notation $\langle ? \rangle$ means "subgroup generated by $\lbrace ? \rbrace$", it is indeed not true in general that $\langle X,Y \rangle = G$, but you don't need that, as certainly still $G=G_1$ and $G_2 = RZ$ holds, as well as everything else -- assuming $RZ$ is short (and abused) notation for $\lbrace \pmatrix{1 & 0 &* \\0&1&0 \\0&0&1}: * \in R\rbrace$, and analogously for $RX$ and $RY$.
Comment: @TorstenSchoeneberg Here, $RZ$ was given in the question and I assumed that it meant $\{rZ \mid r \in R\}$. The problem is then that $Z$ multiplicatively only generates $\mathbb Z Z$ which is not all of $RZ$ under this interpretation. Additionally, I don't think $X,Y,Z$ multiplicatively generate all of $G$, thus the argument fails at the very start.
Comment: But what is "$rZ$" supposed to mean (if not, as I suggest, by bad notation the element $\pmatrix{1 & 0 & r \\ 0 & 1 & 0 \\ 0 & 0 & 1}$)? There is no obvious $R$-action on $G$.
Comment: @TorstenSchoeneberg I apologise for all my previous rushed and unclear responses in these comments. I was abusing bad notation and had not full realised how bad it way, I'm sorry. I believe however that I have solved this question and have posted my answer. Thank you for your help.
Answer: I believe I have solved this.
First, for a subset $S \subset G$, let $\langle S \rangle$ denote the subgroup of $G$ generated multiplicatively by the elements of $S$.
Now define the matrices $X_r = \pmatrix{1 & r & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}, Y_s = \pmatrix{1 & 0 & 0 \\ 0 & 1 & s \\ 0 & 0 & 1}, Z_t = \pmatrix{1 & 0 & t \\ 0 & 1 & 0 \\ 0 & 0 & 1}$ for $r,s,t \in R$.
Further, let $X_1 = X, Y_1 = Y, Z_1 = Z$, and define the additive group (also the $R$-module):
$RX = \{ rX \mid r \in R\}$ where $rX = \pmatrix{1 & r & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}$,
and define $RY, RZ$ similarly.
Then if $S = \{X_r, Y_s, Z_t \mid r,s,t \in R\}$, we have $G = \langle S \rangle$.
Additionally, if we define $(A,B) = A^{-1}B^{-1}AB$ for $A, B \in G$, then for $r,s \in R$:
$(X_r,Y_s) = \pmatrix{1 & -r & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}\pmatrix{1 & 0 & 0 \\ 0 & 1 & -s \\ 0 & 0 & 1}\pmatrix{1 & r & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}\pmatrix{1 & 0 & 0 \\ 0 & 1 & s \\ 0 & 0 & 1}$
$ = \pmatrix{1 & -r & rs \\ 0 & 1 & -s \\ 0 & 0 & 1}\pmatrix{1 & r & rs \\ 0 & 1 & s \\ 0 & 0 & 1} = \pmatrix{1 & 0 & rs \\ 0 & 1 & 0 \\ 0 & 0 & 1} = Z_{rs}$
And:

$(X_r, Z_s) = \pmatrix{1 & -r & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}\pmatrix{1 & 0 & -s \\ 0 & 1 & 0 \\ 0 & 0 & 1}\pmatrix{1 & r & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}\pmatrix{1 & 0 & s \\ 0 & 1 & 0 \\ 0 & 0 & 1}$
$= \pmatrix{1 & -r & -s \\ 0 & 1 & 0 \\ 0 & 0 & 1}\pmatrix{1 & r & s \\ 0 & 1 & 0 \\ 0 & 0 & 1} = \pmatrix{1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1} = I$
$(Y_r, Z_s) = \pmatrix{1 & 0 & 0 \\ 0 & 1 & -r \\ 0 & 0 & 1}\pmatrix{1 & 0 & -s \\ 0 & 1 & 0 \\ 0 & 0 & 1}\pmatrix{1 & 0 & 0 \\ 0 & 1 & r \\ 0 & 0 & 1}\pmatrix{1 & 0 & s \\ 0 & 1 & 0 \\ 0 & 0 & 1}$
$= \pmatrix{1 & 0 & -s \\ 0 & 1 & -r \\ 0 & 0 & 1}\pmatrix{1 & 0 & s \\ 0 & 1 & r \\ 0 & 0 & 1} = \pmatrix{1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1} = I$

So we see, that:

$G_1 = \gamma_1(G) = G$, by definition,
$G_{1^+} = G_2 = \gamma_2(G) = \{Z_r \mid r \in R\}$,
$G_{2^+} = G_3 = \gamma_3(G) = \{I\}$, which tells us $G$ is nilpotent and thus the filtration is separated.

Hence:

$G_1/G_{1^+} = gr_1G = \langle \{X_r, Y_s, Z_t | r,s,t \in R\} \rangle / \langle \{Z_t \mid t \in R\}\rangle$
$\Rightarrow gr_1G \cong \left\{\pmatrix{1 & r & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1} \mid r \in R\right\} \oplus \left\{\pmatrix{1 & 0 & 0 \\ 0 & 1 & s \\ 0 & 0 & 1} \mid s \in R \right\} = RX \oplus RY $
$G_2 / G_{2^+} = gr_2G = \{Z_r \mid r \in R\} = RZ$

Hence:
$grG = gr_1G \oplus gr_2G \cong RX \oplus RY \oplus RZ $
Define now a bracket $[\cdot, \cdot]_{\lambda, \mu} : gr_\lambda G \times gr_\mu G \rightarrow gr_{\max(\lambda + \mu, 2)}G$ on homogenous elements by:
$[A + G_{\lambda^+}, B + G_{\mu^+}] = (A,B) + G_{\max (\lambda + \mu, 2) ^ + }$
and extend $R$-linearly to cover all of $gr_\lambda G \times gr_\mu G$. Combining all of these gives us a bracket:
$[\cdot, \cdot] : grG \times grG \rightarrow grG$, which we may easily check to see that it satisfies the properties of being a Lie bracket.
Additionally we see that with this bracket, the desired relations of $X,Y,Z$ are also satisfied, by the work done previously.
Thus I believe we have shown everything we wanted to show.


How to remove/add quotes?

Question: I would like a command to remove/add quotes
"This is a text" ->  This is a text
 This is a text  -> "This is a text"

Is there some?
Comment: +1, and no idea why someone downvoted. I think this is good question, direct way to get to know about mighty surround plugin.
Comment: http://vim.wikia.com/wiki/Simple_Macros_to_quote_and_unquote_a_word
Answer: You can use the popular surround.vim plugin:

yss" surrounds a line with quotes.
ds" deletes the closest surrounding quotes.

See also this tutorial for more examples of what you can do with this plugin.
Answer: Yes, go to command mode, then type :
:%s/\(^"\|"$\)//g

To quote lines :
:%s/\(^\|$\)/"/g

This performs substitution on all lines, adapt it to your needs if needed.
Answer: For deleting quotes you can simulate a new object o" meaning "outside quotes":
nnoremap do" di"viwp

Type do" in a quoted text and you'll get the text without quotes.
For adding quotes you could do (though this only works linewise):
nnoremap yo" I"<end>"<esc>

If you use surround.vim you can use yss" to quote an entire line without having to map a new command for it.

How to remove/add quotes?


How to train in models, with efficient inferences, like belief-propagation ?

Question: There are many papers that are devoted to efficient inference in graphical models. Though many of these paper don't explicitly talk about the learning (training, etc) problem. For example:
http://videolectures.net/mlss09uk_minka_ai/
I am a little confused on how these models being trained. I thought they are probably doing an EM-like algorithm, i.e.

Inference  (and calculating all marginals, using VB or EP)
Maximizing the likelihood using some blackbox optimization toolboxes using the marginals in the previous case

For example, consider different variants of Belief-Propagation. There are HUGE number of variants for BP, but how a graphical model could be trained?
Any comments?
Answer: I'm a little confused by your question. Tom Minka's tutorial you are referring to is completely devoted to inference in graphical models. Learning the parameters of a graphical model is an inference problem, and, therefore, methods explained in the tutorial such as expectation propagation or variational inference can be applied to it. In fact, all of the examples in the tutorial show how to learn parameters in various graphical models.
EM algorithm can be applied to this problem as well. It should be, however, noted the the EM algorithm delivers point estimates for the parameters of interest, and, therefore, can be inferior to the approximate Bayesian inference methods discussed in the tutorial, since these methods aim to capture all the uncertainty present in the posterior distribution over parameters.
Comment: The word 'inference' means finding posterior distribution (not the most probable value!) on some variables of the model, given values of some other variables. Variables of interest can be output labels or model parameters, or latent variables. In Bayesian inference there is no explicit distinction between different kinds of variables.
Comment: No, sorry, you got it wrong. It's not that the posterior distribution over parameters does not exist or is improper. It's just that BP is a weak method which can handle very limited number of models only, because it attempts to compute marginals exactly. It can be possible for discrete or Gaussian models, but that's pretty much it. EP, on the other hand, approximates marginals and, therefore, is out of trouble. And in discrete and Gaussian models EP will work exactly as BP.
Comment: @Daniel. In Jordan & Wainwright's book, parameter learning has its own chapter, Chapter 6 called **"Variational Methods in Parameter Estimation"** and they make the distinction between `"EM estimation"` and `"Variational Bayes"` which is the application of message passing methods to parameter learning in a bayesian setting. That said, I think they mention that unfortunately the term **"Variational Bayes"** has been reserved to "mean-field" approximations, even though, you could technically apply other methods such as Expectation Propagation, Bethe-Kikuchi & Sum-Product to parameter estimation
Comment: Oh, I see. I think I was confusing these two: {
1. Finding the most probable "output label/value" given "input observation"

2. Finding the most probable "parameters of the model", given pairs of training data.}  By "inference" I usually refer to 1(and "train" refers to 2), but apparently Minka refers to 2, by "inference" (as in inferring the efficient parameters). Right?
Comment: BTW, one thing I don't understand myself is why **Expectation Propagation** is not seen as an example of **Variational Bayes**. Don't all these models operate in a Bayesian setting using message-passing to approximate the posterior?
Comment: @Josh: First Comment: Agreed. Second commend: As Waingwright explains, "Variational" is an umbrella term for approximations using "functionals". In that sense, EP is indeed a variational approximation.
Comment: @hr0nix: Thanks for the illuminating comment. This filled in an important gap I had in mind! :D
Just to get more sense of other posterior approximation techniques, do you know any available examples of BP (e.g. on factor-graphs) for parameter estimation?
Comment: @Josh I think that by "Variational Bayes" people usually mean "meal-field approximation", which is different from what EP does. Also I have to note that neither EP nor Variational Bayes imply message passing.
Comment: @Daniel are you asking if I know a probabilistic model where BP has been successfully used to infer model variables which can be interpreted as the parameters of the model? Note that EP includes BP as a special case, so if you've familiarized yourself with EP, you don't need to study BP separately .
Comment: @hr0nix: Yes, I have read Minka's notes and that EP includes BP. The proof is not really trivial, so I prefer not to convince myself with that. Just our of curiosity, can you point me to some work which use BP for model selection?
Comment: @hr0nix (your comment to @Josh): I don't agree. "Mean-field" refers the way people usually factorize their approximate distribution. Though "variational" is a very general name referred to the approximation scheme. "Variational" is extensively used, even in other approximation schemes in other communities.
Comment: @Daniel Thing is, BP is exact, and, therefore, limited to discrete or Gaussian models. That's why it's usually employed when the model parameters are known and some sort of discrete labels need to be inferred. One quite trivial example of using BP to learn model parameters I can think of is inferring mean of a Gaussian with a known precision from a bunch of samples, but it is of little interest.
Comment: @hr0nix: That's weird ...
Comment: @hr0nix: OK, at the same time that BP it is very similar to EP, it is different. So, for BP, given that we have a graphical model with probabilities for observations, and given their parameters,  we can efficiently find marginals, and do prediction.
Now the question is, given training samples, how can we efficiently learn parameters of the model. In one hand, this is an inference problem, and there are good approximations for that. But the problem is that, the probabilities are defined for observation variables, *not parameters*.
Comment: Continued: In other word, a distribution in our graphical model, is a *proper* distribution, with respect to its variable(s), but not necessarily with respect to all of its parameters. For example, $p \sim N(x|\mu, \Sigma)$, is a defined over x (the random variable), but it is not a proper probability distribution with respect to $\Sigma$ (right?). That makes using BP-like approach, hard (impossible?) for parameter learning problem; since your probabilities are not proper with respect to their unknown parameters(then, the formula for calculating messages, don't hold anymore).
Comment: ok, agree, it works most efficiently on the "exponential family", where computation of messages is simpler.

That said, even for exponential family, I still have some doubts. Wherever in Wainwright & Jordan (2008) I read, it is talking about "inference", where the distribution of the target variation is in the exponential family. But this assumption doesn't usually hold for the model parameters. So, his methods won't work for parameter estimation (ignoring the chapter 6 on "variational mean field")
Comment: Continued: So, let's go simple. Say in a graphical model, of Gaussian random variables, how can you perform parameter estimation with BP? Any pointers?
Answer: Training is done by EM, repeating the E-step and M-step until convergence.

E-step: calculate sufficient statistics using the posterior over the hidden variables given the observed variables.
M-step: update the parameters using the sufficient statistics computed in the E-step

For example, see this paper on how it proves learning parameters of HMM is also a belief propagation.
http://homepages.inf.ed.ac.uk/csutton/notes/sutton04fbbp.pdf
Comment: I see your point. This is almost something that I've mentioned in my question body. But what @hr0nix mentioned is more interesting me. As I understand, he is treating training the parameters just like an inference problem.
Answer: BP like methods find the optimal parameters for maximizing posterior. This is basically the parameter estimation. Inference can also be done in a similar way. Prediction of the new label could be cast as maximizing a posterior given the optimal parameters of the new model. This is a fully Bayesian approach to estimation, in contrary to directly doing EM steps. For more details see section 4 @ http://www.eecs.berkeley.edu/~wainwrig/Papers/Wainwright06_JMLR.pdf


Managing several different screen sizes

Question: I am working a project for mobile IOS,
It came to me that I should start worrying about different screen sizes, the default size for all my CSS objects are for the iphone 6 resolution, default 320px x 536px.
I started adding in Iphone 6 compalitbility using JS to detect the screen size, it does not look good when I resize stuff using the jQuery object .css(..)
Someone refrenced me to using the following.
@media screen and (max-width: 375px) {
#obj1 {
      blabla: blabla
  }
}

The only issue with this is I have to wrap the @media screen and... around every single css object I have?? Or can I just wrap it around all my divs inCSS, I have like 300 CSS Objects right now and It would be sooo annoying to wrap the @media... on every single one.
Comment: use **[bootstrap](http://getbootstrap.com/)**, then you can handle all phone screen sizes
Comment: I think you're confusing a couple of very different concepts here. The first is retina screens (double and triple density screens). You can handle that a number of ways, but typically you make the larger images and then size them in CSS. The other issue is responsive layouts where you re-configure your layout via CSS using the @media queries.
Answer: You need to set to all your divs one class, in order to avoid going one by one by id.

@media screen and (max-width: 375px) {
.myclass {
      blabla: blabla
  }
}

Comment: I already have like 300 divs, it is a little late for me to that :=(
Comment: No. In your IDE or Text editor just find "<div" then replace it with "<div class='myclass' " - if you have Notepad++ you can select the area you want to replace.
Comment: That's merely one way to handle it. To give a specific answer we need to see the specific HTML. Also, if you want this apply to *all* divs, there's no need to give it a class at all.
Comment: But each one of my divs are for a object in my game they all have different  `CSS` properties wouldn't making it all one class make them all the same??
Comment: @Nick you can have multiple classes in one element. ``
Answer: You should build a responsize design.  Bootstrap has a really awesome solution for building a responsive design based on a 12 column layout. You can apply classes to the layout to decide what shows up based on how much space is available. Read more about it here: http://getbootstrap.com/css/#grid
W3Schools has an explanation about it here: http://www.w3schools.com/bootstrap/bootstrap_grid_system.asp

Managing several different screen sizes


Showing that this complex polynomial is proper

Question: Let $X = \mathbb{C} \setminus \{2,-2\}$ and $Y = \mathbb{C} \setminus \{\pm 1,\pm 2\}$. The polynomial I'm examining is $p: Y \to X$ given by $p(z) = z^3 - 3z$. I wanted to show that it's a covering map, and to do that I just need to show that it's a proper local homeomorphism. I can explain why it's a local homeomorphism and I think I know why it's proper too, but I was just wondering if an argument along these lines is valid (I haven't filled in the details):
$p : Y \to X$ can be extended naturally to a surjective polynomial $p': \mathbb{C} \to \mathbb{C}$ which is proper (that's a standard proof), so $p: p'^{-1}(X) \to X$ is proper.
Comment: The argument is certainly true: if $K$ is a compact subset of $X$ then $p'^{-1}(K)$ is compact (because $p'$ is proper) and $p^{-1}(K)\subseteq p'^{-1}(K)$ is closed thus compact.
Comment: Thank you for your comment. I'm aware that the statement you've written is correct, but that is only one part of my argument; do you think that my explanation looks correct overall?
Comment: I'm not sure what exactly you are refering to? If you can prove that polynomial functions are proper then the explanation is correct.
Answer: The argument is not complete, because of the following hole.
Since the function $p' : \mathbb{C} \to \mathbb{C}$ is proper, you do know that if $K \subset X$ is a compact subspace then, since $K \subset X \subset \mathbb{C}$ is compact, it follows that the subspace $(p')^{-1}(K) \subset \mathbb{C}$ is compact.
However, the function you are trying to prove is proper, namely $p : Y \to X$, is defined as the domain-and-range restriction of $p'$. And in order to prove that $p$ is proper, given $K \subset X$ a compact subspace then you must prove that the subspace
$$p^{-1}(K) = Y \cap (p')^{-1}(K) \subset Y
$$
is compact. It is not true that a general domain-and-range restriction of a proper function is proper. And without using something special about the particular restriction $p$, compactness of $p^{-1}(K)$ does not follow from compactness of $(p')^{-1}(K)$. One way to think about what can fail is the statement in the comment of @freakish: in general $p^{-1}(K)$ need not be a closed subset of $(p')^{-1}(K)$.
So you still have a bit of work to do. You'll have to use something special about the restriction function $p$.
Comment: How about this? Since $Y = (p')^{-1}(X)$, $p^{-1}(K) = Y \cap (p')^{-1}(K) =  (p')^{-1}(X) \cap (p')^{-1}(K) = (p')^{-1}(K)$ which is compact in $\mathbb{C}$ because $p'$ is proper, and thus compact in Y also (using subspace topology).
Comment: That looks good, the key fact making it work being the first equation.


a call to template-function - is it legal?

Question: I have a template function (generic func to find the minimum), which look's like that:
template<class T, class Func>
int findmin(const T* a, int n, Func less){
   //...
}

and a call:
int smallest_matrix(const Matrix*a, int n){
    return findmin(a,n,less_matrices);
}

where less_marices is:
bool less_matrices(const Matrix& m1, const Matrix& m2){
     //...
}

Is that right syntax?
Shouldn't I define a function-object with operator () which will do the boolean check that less_matrices do, and the call for findmin shouldn't it look like:
 int smallest_matrix(const Matrix*a, int n){
    minMatrixFunc f;
    return findmin<Matrix, minMatrixFunc>(a,n,f);
}

where minMatrixFunc is a function-object with the right operator()???
Comment: No, you can also pass a function, as you did. Anything "callable" works.
Answer:
Is that right syntax?

Yes.

Shouldn't I define a function-object with operator ()

You may, but it's not necessary.
You don't show the definition of findmin. But presumably, all you do with Func less is use the function call operator on it: less( argument_list ). If so, any callable type will do as long as the overload resolution finds a matching argument list. That includes pointers to functions, which is what you had used.


Remove Element when change redux state

Question: I have problem with updating component when remove element from redux state.
my component:
const mapStateToProps = state => ({
  products: state.shoppingBasket.list,
});

const ShoppingBasket = React.createClass({
  propTypes: {
    removeProduct: React.PropTypes.func.isRequired,
    products: React.PropTypes.array,
    open: React.PropTypes.func.isRequired,
  },
  removeFromBasket(index, name) {
    this.props.removeProduct(index);
  },
  render() {
    return (

        {this.props.products.map((product, index) => (

                product.name
                <button onClick={() => this.RemoveFromBasket(index)}

            );
          )}

    );
  },
});

export default connect(mapStateToProps, actions)(ShoppingBasket);

my reducer:
export default function shoppingBasket(
  state = {
    list: [],
  },
  action
) {
  let tmp = [];
  switch (action.type) {
    case SHOPPING_BASKET_ADD:
      return { list: [...state.list, action.payload.product] };
    case SHOPPING_BASKET_REMOVE:
      tmp = state.list;
      tmp.splice(action.payload.index, 1);
      return { list: tmp };
    default:
      return state;
  }
}

When insert element in redux state my component successfuly update, but when i click on button and call removeFromBasket element was remove from redux state but commponent shouldn't update.
Answer: splice doesn't return new array but only mutates array on which it's called so refernce to list property doesn't change. In Redux you must always return new state object (never mutate state) otherwise your component will not updated because internally it performs shallow comparision of current and next properties so if references hasn't changed it considers them equal and prevents component re-render. You can remove item fron an array in a Redux way like this:
   case SHOPPING_BASKET_REMOVE:
      return { list: [
       ...state.list.slice(0, action.payload.index),
       ...state.list.slice(action.payload.index + 1)
      ]
   }

Comment: Thanks, also work and `return { list: state.list.filter((_, i) => i !== action.payload.index) };`

Remove Element when change redux state


Apply DNS configuration to all interfaces

Question: On Ubuntu 20.04, how can I configure DNS for all Ethernet interfaces, regardless of how they've been named? I have some machines with eth0 as the primary network interface and others with ens5. I'd like to use the same DNS configuration regardless of interface names. A colleague had recommended NetPlan, so that's what I've been trying first. The following configuration (with placeholder IP addresses, domain names, and MAC addresses) avoids some errors, such as an unescaped * being interpreted as a YAML alias attempt, or match: {name: {}} generating a Name= networkd configuration line that its logs flag as ignored. But it renders the machine unreachable.
network:
  version: 2
  ethernets:
    all-ethernet-interfaces:
      match:
        name: "*"
      dhcp4-overrides:
        use-dns: no
      nameservers:
        addresses: [10.1.2.3, 10.1.2.4]
        search: [my.domain.com]

The only other netplan configuration fragment is 50-cloud-init.yaml:
network:
    ethernets:
        eth0:
            dhcp4: true
            dhcp6: false
            match:
                macaddress: 01:20:34:50:67:08
            set-name: eth0
    version: 2

I have been able to work around the issue with duplicate, interface-specific, configuration sections, but I'd prefer to use a less repetitious and more flexible approach. I'm open to configuring systemd-networkd or systemd-resolved more directly instead of using netplan. I'll be using Ansible to apply the configuration once it's developed.
Answer: You don't need use the netplan to do it. So remove any dns-related settings from the netplan configuration files to avoid occasionally changes of dns settings. Then edit the /etc/systemd/resolved.conf file according your configuration. See man resolved.conf for details. Anyway the systemd-resolved is main tool to manage dns by default.


Drupal 8 + Twig background-color -field select

Question: How I do with twig this:
I got list -field where I got differents color:
black|Black
grey|Grey

black = background-color: #000;
grey = background-color: #eee;

When I select Black it will appear somewhere on the node or field.

Example

Answer: One way to do this is provide a field template for that field that just prints the value and no markup:
field--your-field-name.html.twig:
{% for item in items %}
  {{ item.content }}
{% endfor %}

Then in the main template, wherever you want to output that field value, you would have:

Example

The result should be just the field value, with no whitespace, so "black" or "grey".


Como pegar nome de cidades que estão ao meu redor com API em um servidor remoto?

Question: Atualmente utilizo as linhas de código abaixo para listar a cidade onde estou através de latitude e longitude, porém, com as mesmas coordenadas, quero que liste também as cidades que estão ao redor, por quilometragem por exemplo. É possível? Pesquisei bastante sobre isto mas não encontrei uma solução.
Segue o código que estou utilizando para puxar a cidade atual:
<code> $latitude = htmlspecialchars($_GET["latitude"]);
       $longitude = htmlspecialchars($_GET["longitude"]);
       $geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$latitude.','.$longitude.'&sensor=false');
        $resultado = json_decode($geocode);

          for($j=0;$j<count($resultado->results[0]->address_components);$j++){
               $cn=array($resultado->results[0]->address_components[$j]->types[0]);
           if(in_array("locality", $cn))
           {
            $s = $resultado->results[0]->address_components[$j]->long_name;
           }
            }
</code>
Agradeceria muito se me ajudassem a encontrar uma solução.
Comment: Se a resposta selecionada serviu, sugeriria tirar Google e Google Maps das tags e do título da pergunta, pois a resposta não obtém os resultados do Google.
Answer: Achei um post que combina o Google Maps Geocoding API com GeoNames.org API para fazer isso que voce quer, segue abaixo o codigo .php
<code>$geocodeObject = json_decode(file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address={CITY NAME},{COUNTRY CODE}'), true);

//Pegar a latitude e longitude
$latitude = $geocodeObject['results'][0]['geometry']['location']['lat'];
$longitude = $geocodeObject['results'][0]['geometry']['location']['lng'];

//Entrar com os parametros
$responseStyle = 'short';
$citySize = 'cities15000'; //Voce ainda pode definir um numero minimo de habitantes por cidades
$radius = 30; // Raio em KM
$maxRows = 30;
$username = '{YOUR USERNAME}'; //Seu USERNAME no GeoNames

$nearbyCities = json_decode(file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$latitude.'&lng='.$longitude.'&style='.$responseStyle.'&cities='.$citySize.'&radius='.$radius.'&maxRows='.$maxRows.'&username='.$username, true));

foreach($nearbyCities->geonames as $cityDetails)
{

}
</code>
Fonte: https://stackoverflow.com/questions/10172084/can-i-use-google-api-for-finding-nearest-cities
Espero ter ajudado :)
Att. Jeiferson
Comment: Não vi vantagem em pegar as coordenadas do google, já que vai usar GeoNames para obter as cidades vizinhas. Poderia pegar tudo do GeoNames diretamente.
Comment: funcionou perfeitamente, obrigado...
Comment: Exatamente isso que fiz, uma vez que quem envia as coordenadas para o servidor são os dispositivos mobile. Então a partir da linha $responseStyle = 'short'; o código resolveu meu problema.
Comment: Testei o mesmo e está dando o seguinte erro: HTTP request failed! HTTP/1.1 401 Unauthorized. Eu criei a conta e mesmo assim está dando esse erro. Sabe o que pode ser?


Can't SSH to Amazon Lightsail server using browser-based client

Question: I've been able to use the browser-based SSH client without any issues until today. Now, I'm getting the following error each time I try to connect. I've tried restarting, stopping/starting, and removing/adding back the static IP.

CONNECTION ERROR
  An error occurred and we were unable to connect or stay connected to your instance. If this instance has just started up, try again in a minute or two.

Here is a screenshot:
Comment: Are you using DHCP on the client side that might have changed the address of your computer?  You might need to update the address allowed to connect to SSH through the security group.
Comment: No, not using DHCP or anything different. It's the same case for multiple computers I've tried. For Lightsail, there's no configuration like that; it just works out of the box when you launch the browser-based client while logged in.
Comment: "This question does not show any research effort; it is unclear or not useful" This question shows the research done and is useful to anyone else who has this issue.
Answer:
To fix it, add following 2 lines to /etc/ssh/sshd_config

TrustedUserCAKeys /etc/ssh/lightsail_instance_ca.pub

CASignatureAlgorithms +ssh-rsa

Restart

/etc/init.d/ssh restart

Problem
Log in failed. If this instance has just started up, try again in a minute or two.
CLIENT_UNAUTHORIZED [769]
Comment: This solve my problem ,
recently I upgraded debian from debian 10 to debian 11 , and after that Iam unable to access the SSH using 'connect to ssh' from lightsail console and I got CLIENT_UNAUTHORIZED [769], and after I add what you said and restart sshd then Iam able to access the ssh using lightsail console again.
Comment: I wasn't able to use the browser-based SSH tool on lightsail web console to connect to my instance after upgrading to debian 11 (while `ssh` command from my personal machine worked fine). The line `CASignatureAlgorithms +ssh-rsa` fixed it for me.
Comment: I noticed this issue started after I restored a new LightSail instance from a snapshot. Question is why did the browser SSH stop working after restore the instance from a snapshot (external SSH clients had no impact)?
Answer: The issue was I enabled the ufw firewall on Ubuntu and closed my SSH session. Naturally, I was unable to SSH back in on port 22 since only ports 80 and 443 were allowed at that point.
For Lightsail, I don't think there's a way around it, unless a snapshot from one instance can be loaded onto another instance.
For AWS, you can unmount and put the volume on a new instance: https://forums.aws.amazon.com/thread.jspa?threadID=112384
Comment: I locked myself out the same way. I created the snapshot, created a new instance from that snapshot but ran with (sudo ufw allow ssh) in launch script which fixed the issue
Answer: I've seen this happen multiple times and it seems caused by incomplete setup of the server stack due to exhaustion of RAM memory... I don't know why this happens more on AWS than other clouds (even when I setup the exact same server stack).
Try to use a VM with at least 2GB memory and reinstall fresh.
Also I'm not 100% sure but I think port 22 is required for the AWS web-based Console to function regardless of changes you make to sshd_config... and keep in mind that the root user is disabled by default on AWS servers, even in Console mode, so using sudo is required.
On other clouds if there's any issues I can always use the Console to login as root and fix settings and reboot the server but this isn't supported on Amazon, so I use the default port 22 for SSH when using Amazon cloud servers. Also be sure you enable access to that port in both the Networking tab of the machine (AWS UI) and in any firewall too like UFW Firewall.
Besides all this, the Console has had general instability in the past as per @Carlo answer. Again, all of these challenges seem unique to Amazon...
I recommend using other clouds whenever possible lol.
Answer: I had a similar problem after creating an Ubuntu 20 Lightsail VM then doing an in-place upgrade to Ubuntu 22 (via sudo do-release-upgrade). Luckily I added my own public key to the ubuntu user's authorized_keys file before the upgrade, so I was able to ssh in directly from my laptop after the upgrade completed.
The web-based SSH console, however, gave me a "CLIENT_UNAUTHORIZED [769]" error.
Examining /var/log/auth.log showed the following error:
sshd[1449]: userauth_pubkey: key type email@example.com not in PubkeyAcceptedAlgorithms [preauth]

This keytype is apparently not supported by default on Ubuntu 22 Jammy, though it was on Ubuntu 20 Focal. Compare the two man pages...
Search for PubkeyAcceptedKeyTypes:
https://manpages.ubuntu.com/manpages/focal/man5/sshd_config.5.html
Search for PubkeyAcceptedAlgorithms:
https://manpages.ubuntu.com/manpages/jammy/man5/sshd_config.5.html
I then edited my server's /etc/ssh/sshd_config to include the following at the bottom:
PubkeyAcceptedAlgorithms +email@example.com

Then after a sudo service ssh restart, I was able to connect as expected from AWS's web-based SSH console again.
Answer: Found a solution from the AWS forums that encountered the same problem.
There seems to be an issue that happens with Lightsail setups wherein the web-based SSH service stops working properly for some reason.  The advise was to create a snapshot of the Lightsail instance to preserve the current data then create a new instance that installs an updated SSH server using user-data similar to the following:
#!/bin/bash
sudo apt-get remove openssh-client openssh-server
sudo apt-get install openssh-client openssh-server

It says that web-based SSH might not be possible after since they seem to be using a special SSH configuration for it.  You will need to SSH directly to the server using a SSH client.
Comment: Does Lightsail allow applying a snapshot from one instance to another instance?
Answer: Experienced same issue after I enabled ufw firewall on ubuntu 20.04 but had Installed webmin before this issue.
So I used the webmin console to enable ssh via port 22 on the ufw.


How to put into querySelector some IDs?

Question: querySelector("#ID1, #ID2, ID#3")

Is there a possibility to put into one querySelector some IDs?
Comment: `ID#3` should be `#ID3`. Other than that, is there something unclear about the documentation on [`document.querySelector`](//developer.mozilla.org/docs/Web/API/Document/querySelector)? What isn't working?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: querySelectorAll can be used to target multiple selectors.
document.querySelectorAll("#div1, .div2, h3");

Answer: Simple ! Use following code.
document.querySelectorAll('#id1, #id2 , #id3');

This will return nodelist which you can iterate and can perform actions that you want.
Answer: The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
Keep in mind that to return all the matches, use the querySelectorAll() method instead.
example

.first

.second

//get the first element with class bar
let firstElement = document.querySelector('.bar');
//log the first match
console.log(firstElement)

//get all elements with class bar
let allElements = document.querySelectorAll('.bar')
//You can use any common looping statement to access the matches
allElements.forEach(function(elements){
console.log(elements);
});
    /*
    querySelector("#ID1, #ID2, ID#3")

    *select element matches #ID1
    *select element matches #ID2
    *select element matches #ID3

    **/
//select  elements matches specified selectors #id1 , #id2 , #id3 and use any common looping statement to access them
let allMatchesId = document.querySelectorAll('#id1 , #id2 , #id3');
allMatchesId .forEach(function(elements){
console.log(elements);
});

read the docs here at MDN https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Answer:

const divs = document.querySelectorAll('#id1, #id2');
console.log(divs[0], divs[1]);

Source
Answer: Just some more explanation:
This will work (if you correct the error ID#3 instead of #ID3), however querySelector only returns the first element in the document that it matches (NOT the first ID in the list).
If you want all of the elements, then use querySelectorAll, but again the order of the elements will NOT be the order of the IDs, but the order of elements in the document. For example, given the following HTML:

then following JS:
 const divs = document.querySelectorAll("#id1, #id2");
 alert(divs[0].id); // This will show "id2"!

How to put into querySelector some IDs?


Is treatment conditionally independent from outcome in Single Experiment Design?

Question: I'm reading this slides.
At slide 10 there is written that in "Single Experiment Design" we assume "Randomization of treatment", that is:
$ \{ Y_i(t,m),M_i(t') \} \perp  T_i \lvert X $
I don't understand how the outcome and the treatment can be conditionally independent given X, as long as the treatment has an effect on the outcome.
Here there is written that:

The rule here is that after you've drawn out the graph, two events are conditionally independent if you can't traverse from one node to the other without going through a "blocked" node, where a "blocked" node is an event that has has already happened.

But it looks like, if the treatment has an effect on the outcome, I can go from treatment to outcome without going through the X.
What am I not understanding?
I think he wants to say that the treatment is random, meaning there are no unobserved covariates that determine both treatment and outcome.
But this seems not to imply that treatment and outcome are conditionally independent of each other given X.
Or maybe he is abusing notation?
Comment: Are you mixing up potential outcomes and observed outcomes?
Comment: Related question [here](https://stats.stackexchange.com/q/182222/7071).
Comment: @dimitry I think the point I'm missing is that  T is treatment *assignment* and not *actually treated*? But still, treatment *assignment* is correlated with *actually treated*, and *actually treated* is correlated with the *potential* outcome (if the treatment effect is non-zero). So I still not understand why treatment *assignment* can be conditionally independent on *potential outcome*. I guess I need clear definitions and maybe an example?
Comment: I am not sure you need to worry about compliance here. Suppose the treatment effect is positive, and I ranked people by $Y_1-Y_0$ in descending order and gave treatment to the top of the list. Giving treatment to the people with the biggest effect would violate independence with potential outcomes. The actual/observed outcome is $Y=Y_1 \cdot T + (1-T) \cdot Y_0$, so it's always going to be correlated with treatment, assuming treatment does something.
Answer: This is what I think I was missing:

If the treatment assignment is randomized, as in the Brader, Valentino, and Suhay (2008) study, then the treatment is jointly independent of the potential outcomes because the probability of receiving the treatment is identical regardless of the values of the potential outcomes. We can write this as {Yi(1), Yi(0)}⊥⊥ Ti with the standard symbol of statistical independence.

So it's not treatment that is not correlated with outcome, it's the probability of receiving treatment that does not depend on the value of potential outcome.
Reference:
Imai, K., Keele, L., Tingley, D., Yamamoto, T., 2011. Unpacking the Black Box of Causality: Learning about Causal Mechanisms from Experimental and Observational Studies. Am Polit Sci Rev 105, 765–789. https://doi.org/10.1017/S0003055411000414


Should RESTful services return different data when retrieving multiple items vs a single item

Question: With a REST API, is it expected that the data returned for a certain resource is always represented exactly the same?
For instance, is it against a spec or common practice to have the following for a list of resources:
GET /api/users

{
    userId: 1,
    username: 'User1'
},
{
    userId: 2,
    username: 'User2'
}

but when making a call for a single resource, return the following:
GET /api/users/1

{
    userId: 1,
    username: 'User1',
    email: 'email@example.com',
    firstName: 'User',
    lastName: 'One'
}

I'm used to only sending data I need over the wire, so it feels strange to me to send everything about a resource back in the response when it's not going to be used.
An example of my concern would be when populating a dropdown using a list of resources IDs and names, there could potentially be a very large amount of unnecessary data sent through.
Comment: All the data is kept indexed. That's why you see this behaviour
Comment: I think this might help you https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#92-serialization
Answer: It's perfectly ok to have an abbreviated data structure when listing resources vs loading a single resource - in fact, I'd argue that's the expected behavior and most RESTful APIs I've seen/used use this form. After all, if you were to send all of the data when listing resources then why would you even need a separate resource loader apart from someone guessing resource IDs and retrieving the data for them?
The only question is how much should the listing abbreviate the data and that boils down to a typical use case of your service - if it's expected to populate a list of usernames only before digging deeper into the data, ID and username are more than enough.


Line bundle on projective $A$-scheme is the difference between two very ample line bundles

Question: Let $\mathcal{L}$ be an invertible sheaf on a projective $A$-scheme $X$.
Then we can always find two very ample invertible sheaves such that $$\mathcal{L}= \mathcal{M} \otimes \mathcal{N}^*$$
(here * stands for the dual).
By a projective $A$-scheme I mean a scheme X that is isomorphic to a closed subscheme of $\mathbb{P}^n_A$, for some $n.$
I have tried using the line bundle associated with the closed embedding to the projective space, which would be very ample, but I don't know how to do anything meaningful with it.
Any help, please?
Comment: Just trying to rewrite @orangeskid idea. $\mathcal{P}^n$ is very ample for all n. Also for large enough n $\mathcal{P}^n \otimes \mathcal{L}$ is generated by global sections and now using Exercise 7.2(d) chapter 2 in hartshorne, we get that $\mathcal{P}^{n+1} \otimes \mathcal{L}$ is very ample. And now $\mathcal{L}$ is the difference of two very ample line bundles.
Answer: I have a feeling for a proof: consider the line bundle associated to the projective embedding $\mathcal{O}(1)$. Then for every line bundle $\mathcal{L}$, the bundle $\mathcal{O}(n) \otimes \mathcal{L}$ will be very ample if $n$ is large enough. So now you have two very ample bundles $\mathcal{O}(n)$ and $\mathcal{O}(n) \otimes \mathcal{L}$, and you take the quotient of them to get $\mathcal{L}$.


JPQL para consultar data/hora do banco com hibernate sem native query

Question: Existe uma maneira de consultar da data/hora do banco de dados sem usar ative query?
No Oracle eu faço isso:
<code> SQLQuery qry = session.createSQLQuery("SELECT SYSDATE FROM dual");
</code>
Porém gostaria de uma consulta genérica para não ficar preço ao banco de dados.
Comment: Você precisa usar o sysdate mesmo? Não pode pegar a data usando `new Date()`, ou `Calendar.getInstance();`? Porque aí você realmente não ficaria preso ao banco.
Comment: Sim amigo, preciso tentar recuperar do bando de dados a data.
Answer: Tente essa query:
<code>SQLQuery query = session.createSQLQuery("SELECT CURRENT_DATE");
</code>
Comment: Obrigado pela atenção, mas essa query é nativa e funciona para postgres e talvez para mysql, mas não no Oracle. Procuro uma consulta JPQL em vez de native query
Comment: @DemysCota Na verdade existe isso no JPA, mas ao que parece somente pode ser usado em comparações. [Veja o site do uauHebert](http://uaihebert.com/jpa-consultas-e-dicas/6/).
Comment: Muito obrigado pela comentário, pelo que vi vou ter que me contentar com a native query mesmo.


How to show local html into WebView?

Question: I got a html in assets folder:

Hi

Tried to show it in WebView:
public class ContentWebActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_content_web);

    final WebView webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("file:///android_assets/webview.html");
    webView.getSettings().setJavaScriptEnabled(true);

}

}
Run emulator and got an error:
The webpage at file:///android_assets/webview.html could not be loaded becouse:
net::ERR_FILE_NOT_FOUND

What can be wrong?
Answer: It will be "file:///android_asset/webview.html", you actually used android_assets
final WebView webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("file:///android_asset/webview.html");
    webView.getSettings().setJavaScriptEnabled(true);

Comment: Thank, did not noticed this `s`.

How to show local html into WebView?


Scala - schedule a task at a given time of the day: run a task everyday at 6pm

Question: my questions is how i schedule a task to be executed every day at a given time.
I have the next code:
class ScheduleService {
   private val mail = new MailController

   def sendMailSchedule={

     val actorSystem = ActorSystem()
     val scheduler = actorSystem.scheduler
     val task = new Runnable {
      def run() {
        mail.sendMail("email@example.com", "Subject", "Body")
        println("Send")}
      }
     implicit val executor = actorSystem.dispatcher

     scheduler.schedule(
       initialDelay = 0 seconds,
       interval = 7 day,
       runnable = task)
  }
}

Mail Controller is implemented and it send mails.
This code sends a mail every 7 days. What i want is to send a mail at 6 pm everyday.
Comment: How about using a [Crontab](http://linux.die.net/man/5/crontab)?.
Answer: In your code, you have an initial delay of zero seconds. If you calculate the distance in time between now, and the next instance of 6pm, then use that as an initial delay, with a standard delay of 1 day, you will get what you want.
For example if right now it is 4:45pm, you want an initial delay of 75 minutes.
scheduler.schedule(
   initialDelay = timeToNext6pm,
   interval = 1 day,
   runnable = task)

Comment: What do you mean by "with a standard delay of 1 day, you will get what you want"?

I get the part about the initialDelay i will try to implement it, but do you mean to set the interval to 1 day? (interval: 1 day)?

After setting up the initialDelay how i say it to be every day?
Comment: Just make sure you don't hardcode `timeToNext6pm`, but calculate it at runtime.
Comment: Thanks! it worked :D ye i calculate the time with Calendar.getInstance.getTime.
Comment: You may consider DST and TimeZone, it may move one hour ahead and early depending on GST if you go by exactly fixed intervals.


Interface-Based and API based programming in Django

Question: I have searched the web for this issue. And there is a post already with the same title, but not really describing the actual question. So I haven't found the right solution.
I'm developing very large projects. So it is absolutely necessary to split it up into several layers or components or whatever you want to call it.
Each layer exposes some functionality. For each layer it is not important how it will be implemented (since this changes oftenly on large projects), but what is important, is how we call the functionality and what it returns us => the contract!
If we have two layers one concerning the TransactionService and another the BankService, the BankService is a layer higher than the TransactionService and will use the transactionservice.
The transactionService will merely do a transaction:
TransactionVO doTransaction(clientFromVO, clientToVO);

And another layer which does additional stuff.. TransactionVO is not an model class! They are value-objects so the implementation of the service is not exposed to outside the layer.
In java we can achieve this by:
public interface TransactionService {
   TransactionVO doTransaction(clientFromVO, clientToVO);
}

The implementation would be like:
public class TransactionServiceImpl {
   public TransactionVO doTransaction(clientFromVO, clientToVO) {
     // implementation
   }
}

Because we define our interfaces up front, we have a contract which states how each service will look like (without having an actual implementation, the TransactionServiceImpl doesn't need to exist yet).
Therefor 2 teams can work simultaneously on each layer and they can mock the implementation.
I wonder how to achieve this in Django! Creating a REST api for each layer is simpily not done (to much overhead, performance issues..) So for those who have experience on very large projects?
Answer: Python does not have "interfaces" in the same sense as Java. Instead, there is "duck typing" - where the "interface" is implied by the exposed behavior. The answers in this question ( How to handle "duck typing" in Python? ) should address some of the issues around this.
With a dynamic language like Python, if you want to define the behavior of an class before it is implemented, you write a test case in advance. If you are new to test driven development in Python, you can start by reading this.
There are a number of mocking libraries available for Python. This is an example.
Comment: It's to difficult to describe all of the advantages of interface-programming here. But the duck typing isn't a solution. For instance, the DragonServiceImpl could provide a method fly(). The YellowDuckServiceImpl and WhiteDuckServiceImpl also provide such method fly(). But a dragon is not a duck! Anyways it's to complex to describe all the advantages of API or interface-based programming here. It seems to me there is no perfect solution in python. But there i a module which might adress a part of the problem I'm looking into right now: http://docs.python.org/2/library/abc.html
Answer: It seems python does not provide this out of the box. But there is something called abc module:
I quote from http://www.doughellmann.com/PyMOTW/abc/
"By defining an abstract base class, you can define a common API for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations..."
It's not a perfect solution but it provides some of the things I need.
The following comment has let me to this: Java abstract/interface design in Python therefor it's worth mentioning ;)
Comment: Perhaps you should stop trying to write Java in Python?
Comment: I understand your argument. But it's not because you don't understand the need for this approach that it is a bad approach. If it was, not so many books would have been written mentioning interface-based or API based programming. That being said, you understanding the need for such an approach is irrelevant, so questioning the approach doesn't bring any-one with a similar problem anywhere closer to a solution.


For Loop Algorithm ( number of operations )?

Question: Please can someone help me in how to count number of operations for (for nested loop) like this one:
for(int c=0; c<10; c++){
    for(int j=0; j<n; j++)
       for(int r=0; r<n; r++)
           cout<<j;
      cout<<endl;
      }

Comment: n*n*10. Where's the point in this??
Comment: is that an interview question? Probably someone playing smart with the fact that there are no braces arround the inner for statement so endl will only be printed n*10 times. Still you have to define what do you mean by operation etc
Comment: @izomorphius Indeed, does incrementing the counters count as an operation?
Answer: That would be (roughly proportional to) 10n2.
Not exactly, depending on how you define operations. For example, the output of the newline only happens 10 times.
So, if your operation was a cout statement, it would be 10n2 + 10.
Answer: n*n*10 + 10, if both std::cout << j and std::cout << endl; count as a separate operation.
Answer: correct indentation would be:
for(int c=0; c<10; c++) {
    for(int j=0; j<n; j++)
        for(int r=0; r<n; r++)
            cout<<j;
    cout<<endl;
}

adding the missing braces you get:
for(int c=0; c<10; c++) {
    for(int j=0; j<n; j++) {
        for(int r=0; r<n; r++) {
            cout<<j;
        }
    }
    cout<<endl;
}

now you can clearly see how many times it will print:
(10 * n * n) + (10)

Comment: I think what you have do is just to determine the big(O) for this code which is O(n^2).
what about C++ , j++ and r++?
also,c=0,j=0 and r=0 each of these statements we can consider it as an operation,so as in the loop how I can evaluate the number of iteration for each one?
Comment: @user1735329 you need to first define **operation** for that but it's highly architecture dependant. `r++` might correspond to one machine level instruction in one machine and three instructions in another. it is usually not required, why exactly do you need it for?
Answer: The number of iterations is
  10 * n * n