text:
Q: Creating a graph network using d3 v5: error generating the links/edges between nodes I'm currently trying to replicate the following graph network (https://bl.ocks.org/mapio/53fed7d84cd1812d6a6639ed7aa83868) with my own data. The issue that I have has to do with generating the links/edges between nodes.
The error:

Uncaught (in promise) Error: missing: B_01_062

Is occurring from this line:
.force("link", d3.forceLink(graph.links).id(function (d) { return d.id; }).distance(50).strength(1))

Which is where the graph layout variable is defined. If you comment out this line, the graph will generate with just the nodes.
I've tried converting the graph object returned from the d3.tojson function into an in place javascript object structured like this.
var g = {
    nodesL: [...],
    linksL: [...]
}

This did not work either.
Here is a subset of the example data looks like:
{
  "nodes": [
    {
      "id": "Myriel",
      "group": 1
    },
    {
      "id": "Napoleon",
      "group": 1
    },
    {
      "id": "Mlle.Baptistine",
      "group": 1
    },
   ]
  "links": [
      {
      "source": "Napoleon",
      "target": "Myriel",
      "value": 1
    },
    {
      "source": "Mlle.Baptistine",
      "target": "Myriel",
      "value": 8
    },
    {
      "source": "Mme.Magloire",
      "target": "Myriel",
      "value": 10
    },
   ]
}

Here is a subset of my current data looks like:
{
  "nodes": [
    {
      "id": "&=ARMS-CROSS", "Code": "J_01_098", "NeighborhoodDensity": 3},
    {
      "id": "&=CLAP", "Code": "J_02_076", "NeighborhoodDensity": 3},
    {
      "id": "&=RAISE-HAND", "Code": "H_02_48", "NeighborhoodDensity": 3},

  "links": [
      {
        source: "B_01_062",
        target: "A_01_002"
      },
      {
        source: "B_03_025",
        target: "A_01_002"
      },
      {
        source: "C_03_023",
        target: "A_01_002"
      }
   ]
}

I've even tried converting the source and target values to actual numbers.

// convert to a javascript object
    function convertToObj(link_obj) {
        var conv_obj = {}

        // conv_obj.source = link_obj['source'];
        // conv_obj.target = link_obj['target'];

        conv_obj.source = parseInt(link_obj['source'].replace(/\D[^\.]/g, ""));
        conv_obj.target = parseInt(link_obj['target'].replace(/\D[^\.]/g, ""));

        // console.log(conv_obj.source);
        // console.log(conv_obj.target);
        // console.log(conv_obj);

        return conv_obj;
    }

The links array will look like this

    links: [
        {
         source: 162,
         target: 102
        },
        {
         source: 325,
         target: 102
        },
        {
         source: 323,
         target: 102
        }
    ]


text:
Q: Setting HttpReferrer In Unit Tests In my view.py I have the following check on several consecutive pages:
if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
            return redirect('page1')

This is performed on every page, checking that the user was redirected from the previous page, so (for example), if a user tries to enter the url for page4 in the address bar, the test will fail and he will be sent to page3, then that pages test will fail and he will fall back to page2, and so on.
Im doing this because I have several pages linked together which users must visit consecutively.
The problem comes when I want to unit test.  The following test would throw an error because it fails the redirect test and therefore cannot test the logic of the page which im trying to test:
def test_user_information_updated_on_validation_success(self):
        user = User.objects.create_superuser('username')
        self.client.force_login(user)

        self.client.post(reverse('page_4'), {
            'exampleQuestion': 'exampleAnswer'
        })
        user.refresh_from_db()

        self.assertEqual(user.exampleform.somefield, 'exampleAnswer')

How can I access the page within a unit test as if it had been redirected.
Thank you.

A: A request in the test client accepts keywords that are mapped to WSGI environment variables. Environment variables that start with HTTP and are all uppercase, with dashes mapped to underscores - are Http headers, so the short version is that we can set HTTP headers as such:
# Wrong: Generates absolute paths without hosts
self.client.post(
    reverse('page_4'), {'exampleQuestion': 'exampleAnswer'},
    HTTP_REFERER=reverse('page_3')
)

Edit:
It's a little too simple, because HTTP referrers are fully qualified, so we need:

referer = 'http://testserver{}'.format(reverse('page_3'))
self.client.post(
    reverse('page_4'), {'exampleQuestion': 'exampleAnswer'},
    HTTP_REFERER=referer
)

FYI: The protocol (wsgi.scheme) and host name (HTTP_SERVER) come from djang.test.client.RequestFactory._base_environ(). If you use a modified client that changes servername and/or protocol, you should adjust accordingly. In that case it would be wise to override _base_environ in your modified test client and derive values from that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove Filelist object I was trying to delete or remove an object from Filelist of <input type="file"multiple/> in Javascript or JQuery but could not remove or delete the object.
I was trying to delete with an operator like delete $(input[type="file"]).files[0]; but is not working either.

A: You can do something like this:

let deleteButton =  document.getElementById("deleteFiles");
deleteButton.onclick  = function () {
     let element = document.getElementById("filesInput");
     console.log("Files: ");
     console.log(element.files);
     element.value = '';
     console.log("Files after removal: ");
     console.log(element.files);
}
<input type="file" id="filesInput">
<button id="deleteFiles">delete file</button>

This is implemented on vanillaJavascript but you can use Jquery to help you throw the implementation.


text:
Q: How to move multiple files with whitespace on linux Hello I'm newbie in linux, what I'm going to ask is about moving file on linux using awk and xargs, apologies if I'm reposting..
I have apprx 1000-5000 files like this:
-rw-rw-r--  1 wm files   77641 Mar  3 11:20 sendOrder.ZBAM.0005167032-20130503 11:20:35.txt
-rw-rw-r--  1 wm files   77647 Apr  3 11:20 sendOrder.ZBAM.0005167033-20130503 11:20:36.txt
-rw-rw-r--  1 wm files   77655 May  3 11:20 sendOrder.ZBAM.0005167034-20130503 11:20:37.txt
-rw-rw-r--  1 wm files   77661 May  3 11:20 sendOrder.ZBAM.0005167035-20130503 11:20:38.txt
-rw-rw-r--  1 wm files   77556 May  3 11:20 sendOrder.ZBAM.0005167036-20130503 11:20:39.txt
-rw-rw-r--  1 wm files   77549 May  3 11:20 sendOrder.ZBAM.0005167037-20130503 11:20:40.txt
-rw-rw-r--  1 wm files   77549 Jun  3 11:20 sendOrder.ZBAM.0005167038-20130503 11:20:41.txt
-rw-rw-r--  1 wm files   77543 Jun  3 11:20 sendOrder.ZBAM.0005167039-20130503 11:20:42.txt
As you can see the filename contains whitespace at -20130503 11:20:42.txt, so I'm using:
STEP 1
ls -la|grep -e "May"|awk "{print $9, $10}" > some.files
In step 1 I've already got the list file i want to move by month of "May" inside some.files
STEP 2
xargs -0 some.files mv -t dir/newdir/
Step 2 won't work.. What am I supposed to do? I'm using Linux CentOS 5.3

A: There's probably 400 ways to do this.. using find is likely the more efficient way, but:
You can use a for loop:
for i in `ls`; do mv $i dir/newdir/; done

Or a while loop with the file you created in your step 1:
ls -la|grep -e "May"|awk "{print $9, $10}" > some.files; cat some.files | while read mFILE; do mv $mFILE dir/newdir; done

Or with find (where +30 is greater than X days):
find ./ -mtime +30 -exec mv dir/newdir {} \;

OR, if you want to use awk and xargs:
ls -la|grep -e "May"|awk "{print $9, $10}" | xargs mv dir/newdir/

A: With GNU Parallel you can do:
 ls | parallel -X mv {} dir/newdir/

10 seconds installation:
wget -O - pi.dk/3 | sh

Learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1


text:
Q: How to set application insights operation_Name from javascript? I am trying to set the operation_Name property from the javascript client for application insights. But I expect I pass in the wrong property name. Not found any relevant documentation. This has no effect:
AppInsights.trackPageView(name, url, { 'operation_Name': 'something' }, measurements, duration);

Any suggestions?

A: This value is set in the Operation Context which can be modified using
 AppInsights.queue.push(() => {
    AppInsights.context.addTelemetryInitializer(envelope => {
      envelope.tags['ai.operation.name'] = 'FabrikamResidences';
    });
  });


text:
Q: Fermionic oscillator and reducible representation Consider the fermionic oscillators $\{a, a^\dagger\} = 1$, $\{a, a\} = \{a^\dagger, a^\dagger\} = 0$. The commonly used irreducible representation is given by $|0\rangle$, $a^\dagger |0\rangle$ where $a$ annihilates $|0\rangle$.
I am curious about what happens if we consider $|0\rangle$ not annihilated by $a$? In this case, I think there are four states, $|0\rangle, a|0\rangle, a^\dagger |0\rangle, a^\dagger a |0\rangle$, in the game. Of course, the representation is reducible: for example,
$$
a|0\rangle, \ a^\dagger a|0\rangle
$$
forms an invariant subspace, since $aa^\dagger a |0\rangle = a|0\rangle$.
But is this representation a direct sum of two irreducible representation? Note that the naive complement $|0\rangle, a^\dagger |0\rangle$ does not form an invariant subspace. Maybe it is decomposable, but I fail to see how to reorganize the states to make it explicit.
In case that it is not decomposable into two irreps, is it interesting to consider such representation as the Hilbert space?

A: the general method of finding the irreducible representations is to look at the kernel of $a$, orthogonal kets in this set will generate orthogonal irreducible representations. In your case, any ket orthogonal to $a|0\rangle$ in the kernel will do the trick.
Actually, you need more assumptions to study your representation. For example, you can have the case $a^\dagger|0\rangle = 0$, which gives the usual representation (switching $a$ and $a^\dagger$) and even if it not null, you could have for example $|0\rangle = \frac{1}{\sqrt 2}(|0\rangle'+a^\dagger|0\rangle')$ with $|0\rangle'$ in the kernel of $a$.
I think you are interested in the case that the four kets $|0\rangle,a|0\rangle,a^\dagger|0\rangle,a^\dagger a|0\rangle$ are assumed to be independent, and thus generate a representation of dimension 4. In this case, the kernel of a is of dimension 2, generated by $a|0\rangle,aa^\dagger|0\rangle$, so the orthogonal representation would be generated by the ground state $aa^\dagger|0\rangle-\frac{\langle 0|a|0\rangle}{\langle 0|a^\dagger a|0\rangle} a|0\rangle$.
I hope it helps and please tell me if you find a mistake.

A: To complement @Ipz 's answer, I will answer the question by considering the finite dimensional representation theory of the anti-commutation relations.
Define $P = a^\dagger a$ and $Q = aa^\dagger$. Then, using the anticommutation relation, we see that $P^2 = P$, $Q^2 = Q$, $PQ = QP = 0$ and $1 = P + Q$. Also $P^\dagger = P$ and $Q^\dagger =Q$.
Consider a finite dimensional representation $V$.  Let $V_0$ be the kernel of $P$ and $V_1$ the kernel of $Q$. Then $V = V_0 \oplus V_1$ and $V_0$,$V_1$ are orthogonal subspaces. Therefore, $a$ is one-to-one from $V_1$ to $V_0$ and $a^\dagger$ is one-to-one from $V_0$ to $V_1$. If $|0,i\rangle$ for $i=1,\ldots,k$ are an orthogonal basis of $V_0$, then we define $|1,i\rangle = a^\dagger |0,i\rangle$. We have :
$$\langle 1,j|1,i\rangle = \langle 0,j| aa^\dagger|0,i\rangle = \langle 0,j|0,i\rangle = \delta_{ij}$$
We see that $V$ is a direct sum of $k$ subrepresentations isomorphic to the $2$-dimensional one.
Now back to the question at hand. From the analysis above, we know that the representation are even dimensional. From one vector $|\psi\rangle$, we can generate at most a space of dimension $4$.

*

*If we have a representation of dimension $4$, then we know that it is of the form $|0\rangle,|0'\rangle,|1\rangle,|1'\rangle$. A generic vector is of the form :
$$|\phi\rangle = a|0\rangle + b|0'\rangle + c |1\rangle + d |1'\rangle$$
with $|a|^2 + |b|^2 + |c|^2 + |d|^2 + 1$. It generates the whole $4$ dimensional space under the action of $a$ and $a^\dagger$ if, and only if :
$$\det \begin{pmatrix} a & b \\ c&d\end{pmatrix} \neq 0$$

*If we have a vector space of dimension $2$, then we have a basis $|0\rangle,|1\rangle$, and any unit vector $|\psi\rangle=a|0\rangle + b|1\rangle$ with $|a|^2 + |b|^2 = 1$ generates the whole vector space.


text:
Q: EDIT control text overflow This is simple. I created an EDIT control like this:
HWND MYTEXT= CreateWindowEx(WS_EX_CLIENTEDGE, L"EDIT", L"",
                            WS_CHILD|WS_VISIBLE|ES_LEFT|ES_MULTILINE,
                            20, 120, 150, 20, hWnd, NULL, hInst, NULL);

but when I type text inside of it I can't type more text than the width of the EDIT control. When I reach the end it's like there's no more space and I get a beep. How can I make the text scroll in this situation?

A: You can give your edit control the WS_HSCROLL and/or WS_VSCROLL window styles. For instance:
HWND myText
    = CreateWindowEx(WS_EX_CLIENTEDGE, L"EDIT", L"",
                     WS_CHILD | WS_VISIBLE | WS_HSCROLL | ES_LEFT | ES_MULTILINE,
                     20, 120, 150, 20, hWnd, NULL, hInst, NULL);

Alternately, as Matthew T. Staebler rightfully suggests, use ES_AUTOHSCROLL and/or ES_AUTOVSCROLL (note the ES_ prefix, as these are edit styles, not window styles).


text:
Q: JFreeChart DateTickUnit does not work properly I am giving user change ability  to filter graph result.For example user can select to show results for 2 day.Then TimeUnitType  is day, timeAmount is 2.But This is not work properly.For this case,  it must be only 2 thick unit.Date related to first day must be shown in related tick unit. Another data related to day 2 must be shown in second thick unit.
For example by default 1 day is selected.It shows a black line under domain axis.

I am selecting 1 month interval .DomainAxis does not show any thick.
    private void customizeGraphView(JFreeChart chart, TimeUnitType timeUnit, Integer timeAmount) {
    CombinedRangeXYPlot combinedPlot = (CombinedRangeXYPlot) chart.getPlot();
    @SuppressWarnings("unchecked")
    /** read 2 subplot*/
    List<XYPlot> subPlots = combinedPlot.getSubplots();
    for (int plotIndex = 0; plotIndex < subPlots.size(); plotIndex++) {
        /** get plot */
        XYPlot plot = subPlots.get(plotIndex);
        plot.setDomainGridlinesVisible(false);
        // plot.setRangeGridlinesVisible(false);
        XYItemRenderer itemRenderer = plot.getRenderer();
        /** if line and shape rendere */
        if (itemRenderer instanceof StandardXYItemRenderer) {
            StandardXYItemRenderer renderer = (StandardXYItemRenderer) itemRenderer;
            /** show shapes in time series */
            renderer.setBaseShapesVisible(true);
            /** fill shapes in time series */
            renderer.setBaseShapesFilled(true);
            renderer.setBaseFillPaint(Color.BLACK);
            // addItemLabels(renderer);
        }
        /** change DateAxis specific vaues */
        DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
        /** change Date Axis Time Unit format */
        dateAxis.setTickLabelsVisible(true);
        /** add severity bar */
        if (plotIndex == 0) {
            dateAxis.setAutoRange(true);
            if(getFirstGraphMinRange() != null && getFirstGraphMaxRange() != null)
            {
                dateAxis.setRange(getHistoryGraphMinRange(), getHistoryGraphMaxRange());
                dateAxis.setTickUnit(new DateTickUnit(getTickUnitType(timeUnit), timeAmount));
            }
        } else {
            dateAxis.setDateFormatOverride(new SimpleDateFormat("HH:mm", Locale.getDefault()));
            dateAxis.setRange(getSecondGraphMinRange(), getSecondGraphMaxRange());
            dateAxis.setTickUnit(new DateTickUnit(DateTickUnitType.MINUTE, 5));
        }
    }

}

    /**
 * @param timeUnit
 * @return
 */
private DateTickUnitType getTickUnitType(TimeUnitType timeUnit) {
    DateTickUnitType unitType = null;
    switch (timeUnit) {
    case HOUR:
        unitType = DateTickUnitType.HOUR;
    break;
    case DAY:
        unitType = DateTickUnitType.DAY;
    break;
    case MONTH:
        unitType = DateTickUnitType.MONTH;
    break;
    default:
    break;
    }
    return unitType;
}

A: It is difficult to find the problem with what you posted as there are other parameters that might affect that behavior.
For example, if you are using a Timeline that excludes some dates, it may explain why you don't see the ticks.
For example, if you use a tickunit of 1 month and use a timeline that excludes sunday, all the month that started on a Sunday will not have a tick.
You can try using a timeline that includes all the dates to see if the problem still happens.
EDIT
Based on your comments, you are trying to set the tickunit to 4 days with a chart that has a date range of a few hours. I am not sure what is the expected behavior of such a seutp. If I replicate those parameters on such a chart, I don't see any ticks on the date axis either. If I setup the tickunit to 10 minutes instead (for example) I can see the ticks again.
I suppose the conclusion is that your tickunit has to be granular enough so that there is at least 1 tick on your chart to make sure it is seen (in other words, the duration between 2 ticks has to be less than the date range).
If you want more control on the domain axis, you might prefer to use a custom NumberAxis instead of a DateAxis (see here for example).


text:
Q: How to detach an attribute from a class? Having a class C with an attribute coordinates.
class C():
   def __init__():
      self.coordinates=[]

c = C()
coords = c.coordinates

if I change now coords, I would like to change it only "local", so I would like to detach coords from C, so that c.coordinates isn't changed.
Is there a better way than
coords_ = coords[:]


text:
Q: Python - pip virtualenv wrong root error Looking through StackOverflow I see that a lot of people have had problems with pip and virtualenv, but I haven't been able to find an answer to this specific problem.
I am trying to pip install in a virtual environment, but whenever I try, it attempts to install in a virtual environment in a different directory, one which I have long since deleted. I cd into website but when I run flask/bin/pip install flipflop I receive:
zsh: flask/bin/pip: bad interpreter: /Users/User/Downloads/lyric_website/flask/bin/py: no such file or directory

It's very frustrating!


text:
Q: Reading and writing to a txt file on the server, using Javascript Is it possible to modify and read a text file that is stored on the server using Javascript? If so how can I do it?
Free web space does not let me use php so I'm trying to use txt as a database.


text:
Q: Woocommerce, payment successfully, run SQL command and email I want to find a correct solution to my search. I use Woocommerce, I created 5 products including 3 dedicated virtual products.
Here is the id of these products "Product 1" = #id23, "Product 2" = #id24 and "Product 3" = #id26
I would like when the payment for the order has been made successfully, the script (to be included in the functions.php of my child theme) analyzes my order, like that:
For example, if the buyer bought "product 1" in quantity x2, the script will run the script twice like adding something to the database (like an automatically generated password, a random serial number too, a date, the name of the product, a meta info ...).
Please note: that the information looped twice must however be different, in particular for the password, a serial number, for example)
And the buyer has to buy "Product 2", the script will have to be run again ....
So if you understood me this script would have to run n times including the products with their ids (id#23, id#24, id#26) and their quantities.
Here is a piece of code (which does not work) that is logical, since I am asking for help ;)
CODE CHANGED/UPDATED but doesn't works :(
                <?php
    // When payment is OK
    function so_32512552_payment_complete( $order_id )
    {
        // Connecting to external DB credentials
        // the file 'connect_sql.inc.php' is in the same directory than functions.php on your child theme?
        include ('connect.inc.php');
        // Create connection, try to avoid this, use wpdb class
        //$conn = new mysqli($DBHost, $DBLogin, $DBPass, $DBName);
        $conn = mysqli_connect($DBHost, $DBLogin, $DBPass, $DBName);

        // Check all specific products IDs (#23, #24 and #26) to be treat --- Possibility to add new products IDs later...
        // this must implement in other way, but depend on your process
        //$productsIds = array(18, 19, 20, 21, 22, 23);
        $productsIds = array(18, 19, 20, 21, 22, 23);
        // Check if the connection has no errors
        if (!$conn->connect_error)
        {
            $order = wc_get_order( $order_id );
            // remember $item is an instance of WC_Order_item
            foreach ( $order->get_items() as $item )
            {
                // no use $item['product_id']
                if ( in_array($item->get_id(), $productsIds) )
                {
                    //$qty = $order->get_quantity_from_item( $item );
                    // the correct way for get the quantity is this, but not necesary here, there will not be reuse
                    // $qty = $item->get_quantity();
                    // this is an infinite loop
                    // while ($qty):
                    for ($i=0; $i < $item->get_quantity(); $i++)
                    {
                        // Get datas into variables
                        // this will not work
                        // $customer_name = $order->get_customer_name();
                        // use instead billing or shippings fields
                        $customer_name = $order->get_billing_first_name().' '.$order->get_billing_last_name();
                        // this will not work
                        // $customer_email = $order->get_customer_email();
                        $customer_email = $order->get_billing_email();
                        // this will not work
                        // use
                        $product = wc_get_product($item->get_id());
                        //$product_name = $order->get_product_from_item($item);
                        $product_name = $product->get_name();
                        // no use this, no good
                        // $password = rand(9999,9999999);
                        $password = wp_generate_password( 10, false );
                        // neither this
                        // $serial_number = rand(9999,9999999);
                        // this implementation depend on your project
                        $serial_number = rand(9999,9999999);

                        // Add a new entry in DB thru SQL command
                        // where the sql is executed?
                        //$sql = "INSERT INTO tableTest_v5 (user_fullname, user_email, software_product, user_passwd, user_licensenumber, val1) VALUES ('$customer_name', '$customer_email', '$product_name', '$password', '$serial_number')";

                        mysqli_query("INSERT INTO `tableTest_v5` (`id`, `state_account`, `user_email`, `user_passwd`, `user_fullname`, `user_corporate`, `user_licensenumber`, `software_product`, `software_license`, `activation_date`, `software_expiredate`, `wcid`, `user_computerinfos`, `activation_cpuname`, `activation_id`, `activation_cpt`, `superaccess`) VALUES (NULL, -1, 'email', NULL, 'Nick POHENIS', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 3, 0)");

                        //$conn->query($sql);

                        // Then entry added, prepare and send the mail to customer
                        // this not good, use other implementation if can
                        $message = 'Hi,'.$customer_name;
                        $message .= 'Your product: '.$product_name;
                        $message .= 'Name: '.$customer_name;
                        $message .= 'ID: '.$customer_email;
                        $message .= 'Password: '.$password;
                        $message .= 'Serial number: '.$serial_number;
                        wp_mail('mail@domaine.com', 'Email: Additionnal Info', $message);
                    }
                    //endwhile;
                }
            }
            // Close DB
            //$conn->close();
            mysqli_close($conn);
        } else {
            // no die, because we are in woocommerce task 'payment_complete'
            // register as other way for inform to you
            // die("Connection failed: " . $conn->connect_error);
        }
    }
    add_action( 'woocommerce_payment_complete', 'so_32512552_payment_complete' );
    ?>

Hope you understood, anyway, thank you very much in advance for your help. Because I've been doing research for weeks without success. Your help will be welcome !!!!
Regards,
Nico

A: <?php

// When payment is OK
// remove this, it is not in use
// global $woocommerce;

function so_32512552_payment_complete( $order_id )
{
    // Connecting to external DB credentials
    // the file 'connect_sql.inc.php' is in the same directory than functions.php on your child theme?
    include ('connect_sql.inc.php');
    // Create connection, try to avoid this, use wpdb class
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check all specific products IDs (#23, #24 and #26) to be treat --- Possibility to add new products IDs later...
    // this must implement in other way, but depend on your process
    $productsIds = array(23, 24, 26);
    // Check if the connection has no errors
    if (!$conn->connect_error)
    {
        $order = wc_get_order( $order_id );
        // remember $item is an instance of WC_Order_item
        foreach ( $order->get_items() as $item )
        {
            // no use $item['product_id']
            if ( in_array($item->get_id(), $productsIds) )
            {
                //$qty = $order->get_quantity_from_item( $item );
                // the correct way for get the quantity is this, but not necesary here, there will not be reuse
                // $qty = $item->get_quantity();
                // this is an infinite loop
                // while ($qty):
                for ($i=0; $i < $item->get_quantity(); $i++)
                {
                    // Get datas into variables
                    // this will not work
                    // $customer_name = $order->get_customer_name();
                    // use instead billing or shippings fields
                    $customer_name = $order->get_billing_first_name().' '.$order->get_billing_last_name();
                    // this will not work
                    // $customer_email = $order->get_customer_email();
                    $customer_email = $order->get_billing_email();
                    // this will not work
                    // use
                    $product = wc_get_product($item->get_id());
                    //$product_name = $order->get_product_from_item($item);
                    $product_name = $product->get_name();
                    // no use this, no good
                    // $password = rand(9999,9999999);
                    $password = wp_generate_password( 16, false );
                    // neither this
                    // $serial_number = rand(9999,9999999);
                    // this implementation depend on your project
                    $serial_number = rand(9999,9999999);

                    // Add a new entry in DB thru SQL command
                    // where the sql is executed?
                    $sql = "INSERT INTO MyData_v5 (fullname, email, productname, password, serialnumber, val1) VALUES ('$customer_name', '$customer_email', '$product_name', '$password', '$serial_number')";
                    // maybe $conn->query($sql);

                    // Then entry added, prepare and send the mail to customer
                    // this not good, use other implementation if can
                    // $message = 'Hi,'.$cumstomer_name;
                    // has an extra 'm'
                    $message = 'Hi,'.$customer_name;
                    // need '_'
                    $message .= 'Your product: '.$product_name;
                    // has an extra 'm'
                    // $message .= 'Name: '.$cumstomer_name;
                    $message .= 'Name: '.$customer_name;
                    $message .= 'ID: '.$customer_email;
                    $message .= 'Password: '.$password;
                    $message .= 'Serial number: '.$serial_number;
                    wp_mail($customer_email, 'Email: Additionnal Info', $message);
                }
                //endwhile;
            }
        }
        // Close DB
        $conn->close();
    } else {
        // no die, because we are in woocommerce task 'payment_complete'
        // register as other way for inform to you
        // die("Connection failed: " . $conn->connect_error);
    }
}
add_action( 'woocommerce_payment_complete', 'so_32512552_payment_complete' );


text:
Q: power 12v fan using laptop charger while running laptop I have a laptop with partially damaged internal fan. Dont want to buy new one. I am thinking of swapping the internal fan to a 12V fan. The 12V fan I have can fit as it is small. Internal fan is 5V.
Most solution out there

*

*uses external power supply to power 12V fan

*uses 5V from usb to power 12V fan

*uses laptop charger to power 12V fan but laptop is not connected

What I want

*

*power up 12V fan using laptop charge WITH laptop connected. 12V voltage level will be achieved using a step down converter with 19V laptop charger as input. OR connect in parallel to an existing 12V connection in motherboard circuitry.

*5V usb is good idea but I want to operate the fan at its full power using 12V.

Point of doubt

*

*Laptop charger is already used to supply power to laptop. External load (fan) will definitely drain current but will it interfere with the normal laptop operation?

Question

*

*can i use buck converter to step down voltage to power up 12V fan safely?

*is laptop charger capable of giving more juice even when it is already used on laptop?

Do please share your knowledge. Much appreciated. Thanks!

A: Yes, you would use a voltage regulator. Depending on the current required by the laptop + the current required by your fan, you can tell how much the charger could support. An extra 100 mA for a fan won't affect it much.

A: Instead of using buck convertor. You can find many small boost convertor modules. Buy it and fix it within your laptop near internal fan. Supply it with original 5V supply of laptop for fan.
Regarding your Questions: I dont think there will be a problem using buck convertor with charger.
NOTE: Replace original fan with the fan which have same number of wires. Usually they have third wire for feedback to control the speed of fan and temperature of CPU

A: Depends on the power of the fan, if it is low enough.
What I did: grabbed one of the step up modules from ebay, they even come with a a potentiometer to adjust the output voltage. Powering it from USB and I can even adjust the fan speed.


text:
Q: is it possible to find out if a ruby socket is in state ESTABLISHED or CLOSE_WAIT without actually sending or reading data? s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
s.connect(Socket.pack_sockaddr_in('port', 'hostname'))

ssl = OpenSSL::SSL::SSLSocket.new(s, sslcert)
ssl.connect

From here on I would like to check in a thread if the ssl connection and the underlying socket is still ESTABLISHED or if it went into CLOSE_WAIT after the default of 7200 seconds or even worse got closed without actually needing to .write() to or .read() from it.
Is it done withselect(), IO.select() or another method?
BTW: The socket never receives any data it just sends some occasionally.

A: The answer is implementation specific.  You'll need to check tcp implementation header files on your OS.  Here is a sample client for linux that returns the socket state.
  ts = TCPSocket.new('localhost', 5777)
  ssl = OpenSSL::SSL::SSLSocket.new(ts, OpenSSL::SSL::SSLContext.new)
  ssl.sync = true
  ssl.connect
  # TCP_INFO is 11
  # note that TCP_INFO isn't defined in the ruby source.
  # i had to look up the integer value in /usr/include/netinet/tcp.h
  optval = ts.getsockopt(Socket::SOL_TCP, 11)
  state = optval.unpack "i"
  puts "state: #{state}"

Here's the tcp_info struct for my up-to-date ubuntu linux
struct tcp_info
{
  u_int8_t      tcpi_state;
  u_int8_t      tcpi_ca_state;
  u_int8_t      tcpi_retransmits;
  u_int8_t      tcpi_probes;
  u_int8_t      tcpi_backoff;
  u_int8_t      tcpi_options;
  u_int8_t      tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4;

  u_int32_t     tcpi_rto;
  u_int32_t     tcpi_ato;
  u_int32_t     tcpi_snd_mss;
  u_int32_t     tcpi_rcv_mss;

  u_int32_t     tcpi_unacked;
  u_int32_t     tcpi_sacked;
  u_int32_t     tcpi_lost;
  u_int32_t     tcpi_retrans;
  u_int32_t     tcpi_fackets;

  /* Times. */
  u_int32_t     tcpi_last_data_sent;
  u_int32_t     tcpi_last_ack_sent;     /* Not remembered, sorry.  */
  u_int32_t     tcpi_last_data_recv;
  u_int32_t     tcpi_last_ack_recv;

  /* Metrics. */
  u_int32_t     tcpi_pmtu;
  u_int32_t     tcpi_rcv_ssthresh;
  u_int32_t     tcpi_rtt;
  u_int32_t     tcpi_rttvar;
  u_int32_t     tcpi_snd_ssthresh;
  u_int32_t     tcpi_snd_cwnd;
  u_int32_t     tcpi_advmss;
  u_int32_t     tcpi_reordering;

  u_int32_t     tcpi_rcv_rtt;
  u_int32_t     tcpi_rcv_space;

  u_int32_t     tcpi_total_retrans;
};

You may note that my script only returns an integer.  Here's the C enum that details the TCP states and their integer values.  Again, this was found in /usr/include/netinet/tcp.h
enum
{
  TCP_ESTABLISHED = 1,
  TCP_SYN_SENT,
  TCP_SYN_RECV,
  TCP_FIN_WAIT1,
  TCP_FIN_WAIT2,
  TCP_TIME_WAIT,
  TCP_CLOSE,
  TCP_CLOSE_WAIT,
  TCP_LAST_ACK,
  TCP_LISTEN,
  TCP_CLOSING   /* now a valid state */
};

Also, this thread says that you can detect CLOSE_WAIT by reading EOF.  But since you're concerned about whether data has been sent, you'll probably need to unpack up to tcpi_last_data_sent.
Finally, a caveat.  I took on the challenge of answering your question 'cause it sounded fun and it was but my C legs are still wobbly so YMMV. :)


text:
Q: Why does the by() function not work in the way described in this blog post I am trying to reproduce the analysis given in this blog post for the by() function. When I paste the code into R I get an error message, however, instead of the nice table of summarised iris data on the blog post.
attach(iris)
head(iris)

      Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

So the data frame's there and all is well.
Pasting in the by() function from the blog gives me this error:
by(iris[, 1:4], Species, mean)
Species: setosa
[1] NA
----------------------------------------------------------------------------------
Species: versicolor
[1] NA
----------------------------------------------------------------------------------
Species: virginica
[1] NA
Warning messages:
1: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA
3: In mean.default(data[x, , drop = FALSE], ...) :
      argument is not numeric or logical: returning NA

I really can't see what's wrong here. I've tried it with other data frames and so on and the problem seems to be with the 1:4 sequence in the indexing for the data frame. If I just specify one column it gives me the means no problem. I can't work out why it's spitting its dummy when given more than one column. Any suggestions?

A: I am not sure, how old is the blogpost, but if I look into documentation of by, the functionality is different from what the blogpost describes.
by splits input data into subseted dataframes, but you can not get a mean of a dataframe!
mean(iris[,1:4])
[1] NA
Warning message:
In mean.default(iris[, 1:4]) :
  argument is not numeric or logical: returning NA

You can use by, if you want to get mean of values in one column
by(iris[,1], iris$Species, mean)
iris$Species: setosa
[1] 5.006
---------------------------------------------------------------------------------------------
iris$Species: versicolor
[1] 5.936
---------------------------------------------------------------------------------------------
iris$Species: virginica
[1] 6.588

But for getting means for all columns, use aggregate as suggested by @Thomas

A: I'm not sure how that blog post got that answer, because R produces the same out for me as it does for you. Consider aggregate instead:
> aggregate(. ~ Species, iris, mean)
     Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1     setosa        5.006       3.428        1.462       0.246
2 versicolor        5.936       2.770        4.260       1.326
3  virginica        6.588       2.974        5.552       2.026

A: The error message is telling you that 'mean.default' is giving you the error.  If you want to know why mean.default is doing what it does, you could look at the source:
> mean.default
function (x, trim = 0, na.rm = FALSE, ...)
{
    if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
        warning("argument is not numeric or logical: returning NA")
        return(NA_real_)}
...

'by()' does what it is supposed to, but "mean()" fails because a dataframe it is passed fails the is.numeric() test.


text:
Q: Is it possible to create bottom navigation bar in a stack flutter I want to add a bottom navigation bar for my code. but don't know where to add it properly. is it possible to add it in a stack? if not how do I add a navigation bar to my code without errors? can someone please suggest to me what to do about this? here's my home.dart and bottom navigation bar code I hope to add.
home.dart
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget{
  @override
  _HomePageState createState() => _HomePageState();}

class _HomePageState extends State <HomePage>{
  @override
  Widget build (BuildContext context){
    return Scaffold(
      backgroundColor: Color(0xffEDEFF4),
      body: Padding(
        padding: const EdgeInsets.only(top: 40, left: 20, right: 20),
        child: ListView (
          children: [
            buildSearchInput(),
            Stack(
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 45, 10, 0),
                    child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20.0),
                          color: Color(0xffCAEC93),
                        ),
                        height: 137,
                        width: 327,
                        child: Column(
                          children: const [
                            Padding(
                              padding: const EdgeInsets.fromLTRB(20, 40, 100, 40),
                              child: Text(
                                "Banana",
                                style: TextStyle(
                                    fontFamily:'Roboto',
                                    fontSize: 22,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w700),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        )
                        )
                ),

                const Padding(
                  padding: EdgeInsets.fromLTRB(200, 0, 10, 0),
                  child: Image(
                    image: AssetImage("assets/images/banana.png"),
                  ),
                ),
              ],
            ),

            Stack(
              children: [
                Padding(
                    padding: const EdgeInsets.fromLTRB(0, 45, 10, 0),
                    child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20.0),
                          color: Color(0xffCAEC93),
                        ),
                        height: 137,
                        width: 327,
                        child: Column(
                          children: const [
                            Padding(
                              padding: const EdgeInsets.fromLTRB(20, 40, 100, 40),
                              child: Text(
                                "Tangerine",
                                style: TextStyle(
                                    fontFamily:'Roboto',
                                    fontSize: 22,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w700),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        )
                    )
                ),

                const Padding(
                  padding: EdgeInsets.fromLTRB(200, 0, 10, 0),
                  child: Image(
                    image: AssetImage("assets/images/orange.png"),
                  ),
                ),
              ],
            ),

            Stack(
              children: [
                Padding(
                    padding: const EdgeInsets.fromLTRB(0, 45, 10, 0),
                    child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20.0),
                          color: Color(0xffCAEC93),
                        ),
                        height: 137,
                        width: 327,
                        child: Column(
                          children: const [
                            Padding(
                              padding: const EdgeInsets.fromLTRB(20, 40, 100, 40),
                              child: Text(
                                "Kiwi",
                                style: TextStyle(
                                    fontFamily:'Roboto',
                                    fontSize: 22,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w700),
                                textAlign: TextAlign.left,
                              ),
                            ),
                          ],
                        )
                    )
                ),

                const Padding(
                  padding: EdgeInsets.fromLTRB(200, 0, 10, 0),
                  child: Image(
                    image: AssetImage("assets/images/kiwi.png"),
                  ),
                ),
              ],
            ),

          ],

        ),
      ),
      );

  }

  Widget buildSearchInput() => Container(
    decoration: BoxDecoration(
        color: Colors.white, borderRadius: BorderRadius.circular(14)),
    child: Padding(
      padding: const EdgeInsets.only(left: 20.0, right: 20),
      child: Row(
        children: [
          Icon(
            Icons.search,
            size: 30,
            color: Colors.grey.shade300,
          ),
          Flexible(
            child: TextField(
              decoration: InputDecoration(border: InputBorder.none),
            ),
          ),
        ],
      ),
    ),
  );

  Widget buildCard()=> Container (
    height: 23,
    width: 90,
    color: Color(0xffE6E848),

  );
}

my code for bottom navigation bar
 Stack(
              children: [
                bottomNaavigationBar:BottomNaavigationBar(
                  items:[
                    BottomNavigationBarItem(
                      icon:Icon(Icons.Icons.home),
                      backgroundColor:Colors.blue,
      ),
      BottomNavigationBarItem(
        icon:Icon(Icons.Icons.Icons.favorite),
        label:'Feed'
        backgroundColor:Colors.blue,
      ),
      BottomNavigationBarItem(
        icon:Icon(Icons.Icons.chat),
        label:'Chat'
        backgroundColor:Colors.blue,
      ),
      BottomNavigationBarItem(
        icon:Icon(Icons.Icons.person),
        label:'Profile'
        backgroundColor:Colors.blue,
      ),

                    ),
                  ],

                ),

A: Scaffold has a property bottomNavigationBar
Use it like so:
Scaffold(
 bottomNavigationBar: BottomNavigationBar(
   items: [],
 ),
 ...
)

A: You can add it in Scaffold, sure if you want.
Here is BottomNavBar example with PageView.
Let's define a pageController and currentTab variable for PageView inside our class,
    PageController _pageController = PageController();
    int _currentTab = 0;

Then we can initialize our controller for initial page.
  @override
  void initState() {
    _pageController = PageController(initialPage: _currentTab);
    super.initState();
  }

Then here our view codes.
Scaffold(
        drawer: const CustomDrawerWidget(),
        bottomNavigationBar: BottomAppBar(
          shape: const CircularNotchedRectangle(),
          child: BottomNavigationBar(
            currentIndex: _currentTab,
            iconSize: 24,
            selectedItemColor: Theme.of(context).colorScheme.primary,
            type: BottomNavigationBarType.fixed,
            items: _items,
            onTap: (index) {
              setState(() {
                _pageController.jumpToPage(index);

              });
            },
          ),
        ),
        body: PageView(
          physics: const NeverScrollableScrollPhysics(),
          pageSnapping: true,
          controller: _pageController,
          children: _pages,
          onPageChanged: (page) {
            setState(() {
              _currentTab = page;
            });
          },
        ),

      );

BottomNavigationBar items:
const _items = [
  BottomNavigationBarItem(icon: Icon(Icons.home), label: "Feed"),
  BottomNavigationBarItem(icon: Icon(Icons.people), label: "Chat"),
  BottomNavigationBarItem(icon: Icon(Icons.person), label: "Profile"),
];

Here is page list:
    const _pages= [
  FeedPage(),
  ChatPage(),
  ProfilePage(),
    ];


text: Q: утечка памяти при удалении элемента DOM Здравствуйте. Есть приложение, которое должно работать длительное время, все это время в нем удаляются/создаются элементы таблицы(элементы загружаются с сервера). Удаляю строки при помощи jquery(.remove()).Однако элементы при удалении не удаляются из памяти, отладчик показывает, что при каждом создании нового элемента растет "private memory", но после удаления не очищается. Пробовал предварительно, перед удалением, отвязывать обработчики при помощи метода .off, обнулять ссылку на удаленный элемент, но ничего из этого особенно не помогает и память продолжает утекать! Может кто нибудь знает как удалить элемент DOM из памяти совсем? Или, возможно, есть другие выходы из ситуации?


text:
Q: WPF RadioButton groups in Xaml In the WPF app we are building, we have 3 groups of RadioButtons in individual StackPanels side by side. We are trying to program the following behavior. When tabbing through the form, we don't want to tab through each of the radiobuttons (standard behavior), instead we would like to tab to the "first" radiobutton in each group and have the ability to arrow up/down to the other radiobuttons (list) in each group once we tab to the group. We have set the IsTabStop=False for the radiobuttons below each of the first radiobutton in the list. This gives us the desired behavior for tabbing through each group, but this does not allow for the ability to arrow up/down the list. The arrow up/down behavior only works if the IsTabStop=True. We also tried setting the GroupName attribute of the radiobutton, but the behavior is the same as described above. In the old win forms, there was a radiobutton list control that had this behavior and we are just trying to recreate it. Does anyone have any idea as to how to recreate this behavior? Thanks in advance for your help...!

A: I think the KeyboardNavigation attached properties will do the trick.
I mocked up a quick WPF example in XAML (sorry for the length), using ItemsControls to group the RadioButton elements:
<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
  x:Class="Experiment.MainWindow"
  x:Name="Window"
  Title="MainWindow"
  Width="640" Height="480">

  <Grid x:Name="LayoutRoot">
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="91,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton Content="Alpha" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Delta" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Gamma" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
        <RadioButton Content="Beta" KeyboardNavigation.TabIndex="2"/>
      </ItemsControl>
    </Grid>
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="244,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton x:Name="First" Content="Eenee" KeyboardNavigation.TabIndex="2"/>
        <RadioButton x:Name="Second" Content="Meenee" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
        <RadioButton x:Name="Third" Content="Mynee" KeyboardNavigation.TabIndex="2"/>
        <RadioButton x:Name="Fourth" Content="Moe" KeyboardNavigation.TabIndex="2"/>
      </ItemsControl>
    </Grid>
    <Grid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" Margin="391,139,0,0">
      <ItemsControl KeyboardNavigation.IsTabStop="False" KeyboardNavigation.TabNavigation="Once" KeyboardNavigation.DirectionalNavigation="Contained">
        <RadioButton Content="Extralarge" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Large" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Medium" KeyboardNavigation.TabIndex="2"/>
        <RadioButton Content="Small" IsChecked="True" KeyboardNavigation.TabIndex="1"/>
      </ItemsControl>
    </Grid>
  </Grid>
</Window>

A: A solution is to use the technique of styling a list box to look like a radio button group.  Then it's possible to tab between the styled list boxes, and use arrow keys to select individual 'radio button' list box items.
Here's a complete demo which can also be downloaded as a sample application
public class RadioButtonGroupsViewModel
{
    public RadioButtonGroupsViewModel()
    {
        Items1 = new List<string> {"One", "Two", "Three"};
        Selected1 = "One";

        Items2 = new List<string> {"Four", "Five", "Six"};
        Selected2 = "Five";

        Items3 = new List<string> {"Seven", "Eight", "Nine", "Ten"};
        Selected3 = "Ten";
    }

    public IEnumerable<string> Items1 { get; private set; }
    public string Selected1 { get; set; }

    public IEnumerable<string> Items2 { get; private set; }
    public string Selected2 { get; set; }

    public IEnumerable<string> Items3 { get; private set; }
    public string Selected3 { get; set; }
}

Xaml
xmlns:theme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"

  <Page.Resources>
    <Style x:Key="RadioButtonListBoxStyle" TargetType="ListBox">
      <Setter Property="BorderThickness" Value="0" />
      <Setter Property="ItemContainerStyle">
        <Setter.Value>
          <Style TargetType="ListBoxItem">
            <Setter Property="SnapsToDevicePixels" Value="true" />
            <Setter Property="OverridesDefaultStyle" Value="true" />
            <Setter Property="Template">
              <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <RadioButton
                        IsTabStop="False"
                        GroupName=""
                        IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}}" >
                        <RadioButton.Content>
                            <Border VerticalAlignment=
                                    "{TemplateBinding Control.VerticalContentAlignment}" Padding="2">
                                <ContentPresenter
                                    Margin="{TemplateBinding Control.Padding}"
                                    VerticalAlignment=
                                      "{TemplateBinding Control.VerticalContentAlignment}"
                                    HorizontalAlignment=
                                      "{TemplateBinding Control.HorizontalContentAlignment}"
                                    RecognizesAccessKey="True" />
                            </Border>
                        </RadioButton.Content>
                    </RadioButton>
                </ControlTemplate>
              </Setter.Value>
            </Setter>
          </Style>
        </Setter.Value>
      </Setter>
    </Style>
  </Page.Resources>

  <Page.DataContext>
    <Samples:RadioButtonGroupsViewModel />
  </Page.DataContext>

  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="auto" />
      <RowDefinition Height="auto" />
      <RowDefinition Height="auto" />
      <RowDefinition />
    </Grid.RowDefinitions>

    <ListBox Style="{StaticResource RadioButtonListBoxStyle}"
             ItemsSource="{Binding Items1}"
             SelectedItem="{Binding Selected1}">
      <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal"
                      KeyboardNavigation.DirectionalNavigation="Cycle" />
        </ItemsPanelTemplate>
      </ListBox.ItemsPanel>
    </ListBox>

    <ListBox Grid.Row="1"
             Style="{StaticResource RadioButtonListBoxStyle}"
             ItemsSource="{Binding Items2}"
             SelectedItem="{Binding Selected2}">
      <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal"
                      KeyboardNavigation.DirectionalNavigation="Cycle" />
        </ItemsPanelTemplate>
      </ListBox.ItemsPanel>
    </ListBox>

    <ListBox Grid.Row="2"
             Style="{StaticResource RadioButtonListBoxStyle}"
             ItemsSource="{Binding Items3}"
             SelectedItem="{Binding Selected3}">
      <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal"
                      KeyboardNavigation.DirectionalNavigation="Cycle" />
        </ItemsPanelTemplate>
      </ListBox.ItemsPanel>
    </ListBox>
  </Grid>

A: To change the orientation from left to right use the FlowDirection property to RightToLeft.
RadioButton is used in the group so that user can select only one option from the available options (No extra coding is required to uncheck others). Use same GroupName of the radiobuttons to mark in a group so that only one option can be selected as follows.

    <RadioButton Height="16" Margin="26,18,132,0" Name="RadioButton_Option1" VerticalAlignment="Top" Background="Snow" BorderBrush="Black"  GroupName="Visit_eggHeadcafe.com" Foreground="DarkBlue">ASP.net Articles </RadioButton>

    <RadioButton Height="16" Margin="26,18,132,0" Name="RadioButton_Option2" VerticalAlignment="Top" Background="Snow" BorderBrush="Black"  GroupName="Visit_eggHeadcafe.com" Foreground="DarkBlue">C# Articles</RadioButton>

    <RadioButton Height="16" Margin="26,18,132,0" Name="RadioButton_Option3" VerticalAlignment="Top" Background="Snow" BorderBrush="Black"  GroupName="Visit_eggHeadcafe.com" Foreground="DarkBlue">ADO.net Articles</RadioButton>

    <RadioButton Height="17" Margin="26,18,115,0" Name="RadioButton_Option4" VerticalAlignment="Top" Background="Snow" BorderBrush="Black"  GroupName="Visit_eggHeadcafe.com" Foreground="DarkBlue" Width="164">SQL Server 2005 Articles</RadioButton>

    <Button  Margin="26,18,132,0" Width="75" Height="20" Click="Button_Click">Open Articles</Button>

    </StackPanel >


text:
Q: Virtually squash commits for code review GitLab allows to add comments / discussions to individual commits, which is very useful e.g. to ping someone with a quick question or ask for a review:

Is there any way to get a similar view for multiple commits?
Something like
https://myGitlabserver/myProject/myRepo/commit/12345+6789a+bcdef+13567
(^ doesn't work...)
I guess one possible workaround would be to git cherry-pick those commits to a temporary branch, temporarily revert them in the master branch, and then create a merge request... nasty.
What I'm looking for is an easy way to start a comment thread on a set of changes which already are in the master branch. So basically, I would like GitLab to virtually, but not physically, squash those commits together just for the sake of starting a comment thread on them.
Possible?


text:
Q: Deleting every second row in a csv-file I am new to d3.js. Right now i am working on a linechart with d3.js and would like to delete/ignore every second row of my original csv-file. The amount of data is very high and I want to try, if Zoom and Pan will get less laggy with less data. Since the original has very small data steps the end result would be the same.
I'm getting my data with
d3.csv("data.csv", type, function(error, data) {
  if (error) throw error;...
and
function type(d) {
d.x = +d.Time_seconds;
d.y1 = +d.Temp2_C;
d.y2 = +d.Temp3_C;
I think a possible solution could be deleting the rows, before loading them with d3.csv()
I have already tried something with d3.xhr, but didnt get anything useful of it. I dont even know, if its the right way to start.
Thank you!

A: after you get the data in the load callback use Array.filter and use the index to determine if the row is accepted
d3.csv("data.csv", type, function(error, data) {
    if (error) throw error;

    data = data.filter( (e, i) => i % 2 === 0 );

    ...


text:
Q: App Store Connect issue ITMS-90129 keeps blocking upload App Store Connect keeps blocking App upload by issuing
ITMS-90129: The bundle uses a bundle name or display name that is already taken.

So far I tried:

*

*Changing the Display Name, Bundle Identifier (even with generated Hashcodes to make sure that the names really are not taken already)

*Created alternative Profiles, Identifier and App in App Store Connect (also using the same mentioned hashcode)

*Tried these changes in the Xcode input fields (under 'General') and also directly modifiyng the Info.Plist

*Re-Exporting the project from Unity to XCode with the new naming (to make sure Unity is not writing some bundle id somewhere which is not visible in XCode)

*(Update) Tried to Clean the build folder based on
minchaej suggestion

Additional information: The XCode project is exported from Unity and we're using Firebase which is installed via Pods.
I'm grateful for any hint where to continue looking - because I'm really running out of ideas. Thanks a lot for taking the time.
Cheers
vik

A: The solution for this (probably very Unity-to-XCode specific) issue was localization related:
I had to remove all but the English localization entry in the Localization section.
I'm not sure why there were other loca resources before (since we didn't set them up) but I assume these included an alternative app name which was causing the ITMS-90129 to pop up.

A: My salvation for ITMS-90129 is the next:

*

*Remove definitions for
CFBundleName
CFBundleDisplayName
CFBundleSpokenName
for base(en) localisation InfoPlist.strings.

*Setup this variables with single value $(PRODUCT_NAME) directly in Info.plist

*Variable $(PRODUCT_NAME) define via root project Build Settings/Packaging/Product Name

*Setup variable LSHasLocalizedDisplayName in YES value in Info.plist

*Setup Russian (or other) localisation for variables
CFBundleName
CFBundleDisplayName
CFBundleSpokenName
via InfoPlist.strings
As I am personally assume, setup this variables via base localisation is the key of problems in which I am faced with


text:
Q: How do you send the contents of a fieldset to an email address? I have a fieldset:

            <form id="contact-form" action="mailto:xyz@email.com" method="post">
                <fieldset form="#contact-form">
                    <legend>Contact Form</legend>
                    Name:

                        <input class="input-field" type="text" name="Name"/>

                    Email:

                        <input class="input-field" type="text" name="Email"/>

                    Message Title:

                        <input class="input-field" type="text" name="Message Title"/>

                    Message:

                        <textarea class="message-field" type="text" name="Message"></textarea>

                    <button id="submit-button" type="submit">Submit</button>
                </fieldset>
            </form>

I want to set it up so that the person who wants to contact me can enter their details and then when the 'Submit' button is clicked I receive an email with the Message Title as the header and the persons Name, Email and Message in the body of the email.
At the moment the mailto:xyz@email.com section will open up an email client successfully but I want it to just send automatically. I have some understanding of js and php but this is the first time I've tried something like this so was looking to be pointed in the right direction. I'm not asking for all the code, just what I need to do then I can work it out for myself.

A:
At the moment the mailto:xyz@email.com section will open up an email client successfully but I want it to just send automatically.

You can't, at least not client-side.  The mailto: protocol handler is intended to simply launch the registered e-mail client for the user.  Nothing more.

I have some understanding of js and php but this is the first time I've tried something like this so was hoping someone could point me in the right direction

You can send the e-mail server-side with PHP.  Don't bother with mail(), which is just a utility function for basic debugging and such.  Consider a robust e-mail class like PHPMailer.  That way, you can use secured SMTP servers, and also send HTML e-mails with proper multipart MIME encoding.


text:
Q: Spring Security/SPNEGO authentication issue: Checksum failed i'm using, for a Java project, Spring Security with SPNEGO for authentication.
I followed every step illustrated at the link http://anmoljains.wordpress.com/2014/01/19/java-single-sign-on-using-spnego-and-jboss-eap-6-1-0/, but, when I try to authenticate with IE from a machine different from server, I get the following error:
Negotiate Header was invalid: Negotiate YIGeBgYrBgEFBQKggZMwgZCgGjAYBgorBgEEAYI3AgIeBgorBgEEAYI3AgIKonIEcE5FR09FWFRTAAAAAAAAAABgAAAAcAAAAEu8iH+9PA/ykFHFoL0fcG4pSiUY/1uV4d6rsrMhDt1gQWYkR7WJ+/z5C7xHvZptngAAAAAAAAAAYAAAAAEAAAAAAAAAAAAAAEVyfDIyRYtIv9kqa6BepAo=: org.springframework.security.authentication.BadCredentialsException: Kerberos validation not succesfull... Caused by: java.security.GeneralSecurityException: Checksum failed
Here's my applicationContext-security.xml:
<http entry-point-ref="spnegoEntryPoint" use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()"/>
<intercept-url pattern="/report" filters="none"/>
<custom-filter ref="spnegoAuthenticationProcessingFilter" position="BASIC_AUTH_FILTER"/>
<intercept-url pattern="/css/**" filters="none"/>
<intercept-url pattern="/resources/**" filters="none"/>
<intercept-url pattern="/js/**" filters="none"/>
<form-login login-page="/login" default-target-url="/report" authentication-failure-url="/accessDenied"/>
<logout logout-url=""/>
</http>
<beans:bean id="spnegoEntryPoint" class="org.springframework.security.extensions.kerberos.web.SpnegoEntryPoint"/>
<beans:bean id="spnegoAuthenticationProcessingFilter" class="org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="kerberosServiceAuthenticationProvider"/>
<authentication-provider ref="kerberosAuthenticationProvider" />
</authentication-manager>
<beans:bean id="kerberosServiceAuthenticationProvider" class="org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider">
<beans:property name="ticketValidator">
<beans:bean class="org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator">
<beans:property name="servicePrincipal" value="HTTP/web.team.it@team.it/>

where userDetailsService is my implementation of org.springframework.security.core.userdetails.UserDetailsService.
And here's how I generated the keytab.pass:

C:\Windows\System32>ktpass /out http-web.keytab /mapuser http-web.team.it@team.it /princ HTTP/pc-web.team.it@team.it /crypto AES256-SHA1 /pType KR
  B5_NT_PRINCIPAL -kvno 0 /pass Password01

Using Wireshark, i get the following infos:

Accept: text/html, application/xhtml+xml, /
  Accept-Language: it-IT
  User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
  Accept-Encoding: gzip, deflate
  Host: web.team.it:8080
  DNT: 1
  Connection: Keep-Alive
  Cookie: JSESSIONID=PDY3d6UIDOARlxk92scldt8Z.undefined
  Authorization: Negotiate YIGeBgYrBgEFBQKggZMwgZCgGjAYBgorBgEEAYI3AgIeBgorBgEEAYI3AgIKonIEcE5FR09FWFRTAAAAAAAAAABgAAAAcAAAAEu8iH+9PA/ykFHFoL0fcG4pSiUY/1uV4d6rsrMhDt1gQWYkR7WJ+/z5C7xHvZptngAAAAAAAAAAYAAAAAEAAAAAAAAAAAAAAEVyfDIyRYtIv9kqa6BepAo=

Trying to change the principal using only short machine name (web instead of web.team.it), i get the error:
Cannot find key of appropriate type to decrypt AP REP - AES256 CTS mode with HMAC SHA1-96
I'm using Spring Security 3.0.5 and spring-security-kerberos-core-1.0.0.M2.jar.
Also would be useful to have some full sample of this kind of authentication.
Thanks to all.

A: Add to your krb5.conf
    default_tkt_enctypes = aes256-cts-hmac-sha1-96
    default_tgs_enctypes = aes256-cts-hmac-sha1-96


text:
Q: NVidia or Radeon GPUs that support more than 4 active displays Are there any recent Nvidia or Radeon GPUs that support more than 4 active displays using one card? I've tried a few that have 5 ports but they usually only allow 3 or 4 active displays at one time. On Linux this is easy to detect using the xrandr --listproviders command, which for my GeForce FTX 970 shows crtcs: 4 meaning it only allows 4 active displays.
Provider 1: id: 0x3f cap: 0x4, Source Offload crtcs: 4 outputs: 8 associated providers: 1 name:nouveau

Which GPUs allow more than 4 displays when using DisplayPort Multi Stream Transport (MST) or other methods of splitting a single port into multiple active displays? All of the Nvidia GPUs that I've checked look like they only support 4 active displays even if they have 5 or 6 different ports.

A: I saw a footnote on the (now dated) AMD FirePro w7100 data sheet stating:

Three 4K displays at 60Hz requires displays with DisplayPort 1.2 interfaces with support for HBR2 ( for SST ) or HBR2 with MST. Four 4K displays at 30Hz requires displays with at least one
  DisplayPort interface. Four 4K displays at 30Hz with HDMI 1.4a interface can also be supported via DisplayPort to HDMI adapters that support HDMI 4K output. Six full-HD displays requires DP 1.2 MST hub or at least two monitors capable of DP 1.2 daisy-chaining.

Meaning when using MST you could get up to 6 active displays. I checked the data sheet for the newer AMD Radeon Pro WX 5100 and Pro WX 7100 which state:
Display Output Support (@ 60Hz)
4 @ 1920x1080
4 @ 3840x2160
2 @ 5120x2880
1 @ 7680x4320

But they don't state anything about how many total active displays are supported when using MST. I ended up buying the AMD Radeon Pro WX 5100 and can confirm it supports up to 6 active display engines when two of the inputs use Display Port MST:
xrandr --listproviders
Providers: number : 1
Provider 0: id: 0x5d cap: 0x9, Source Output, Sink Offload crtcs: 6 outputs: 8 associated providers: 0 name:AMD Radeon (TM) Pro WX 5100 Graphics @ pci:0000:01:00.0

The Radeon Pro WX Series Quick Start Guide (which I cannot find an online copy of) also includes more details about the supported display configurations:


text:
Q: Powershell resume script after reboot using workflow I'm trying to make a script that continues after a reboot. In short the script is there to deploy a PC for in the field use so the script runs local on a local machine, ideally from a thumb drive. A user inserts the drive and runs the script, from there it should not require any actions by the user. The script should then reconfigure the network adapters and enable the Hyper-V Windows feature (this bit is working). After this the PC needs to restart and continue with importing a VM (this bit is working as well).
Since the user will not have any IT related knowledge the script needs to show a PowerShell window after it has rebooted where it outputs the result of the VM import. Ideally I would like to have the script log itself on automatically as all PC come default with the same password.
workflow Reboot-Resume {
    "Hello World, I'm going to reboot!"
    Restart-Computer -Wait
    "This should be printed to a PowerShell window"
}

Unfortunately the above snippet is not working as when the PC is rebooted the workflow job is suspended. Execution policy is set to "unrestricted". Manually resume the job will not pop-up a shell with "This should be printed to a PowerShell window" printed.


text:
Q: x86 checking for protected and long mode in real mode So I want to check if protected and long mode is supported while being in real mode.
I know that I can check for support of long mode while being in protected mode, but that requires cpuid instruction which I don't think we have in real mode (at least in old processors).
I didn't found any information about that.

A: A full sequence might be:
1.1) Determine if the CPU is an actual 8086 chip by testing if bit 15 of the flags register is set. If you don't do this the next step can cause the CPU to crash.
1.2) Determine if the CPU supports 32 bit by testing if the IOPL flags (bits 12 and 13 of FLAGS register) can be modified. If you don't do this the next step can cause the CPU to crash
1.3) Check if the ID flag (bit 21 of eflags register) can be modified. If it can be modified the CPU supports the CPUID instruction. Note that it's fine to use 32-bit instructions in real mode (to push and pop eflags) if the CPU supports 32-bit instructions.
Note 1: From memory; there were some CPUs (NexGen from National Semiconductor) that support CPUID but don't support Intel's "ID flag" method; and there are some CPUs (from Cyrix and IBM) where the CPUID instruction needs to be enabled before it can be used (via. special IO ports). Dealing with these CPUs is possible, but beyond the scope of my answer.
Note 2: As an alternative; if you know it isn't an 8086, you can install an invalid opcode exception handler and try to execute a CPUID instruction. If your invalid opcode exception handler is called then CPUID currently isn't supported.
2.1) Use "CPUID with EAX=0x80000000" to determine if CPUID supports "CPUID with EAX=0x80000001". This step is just a sanity check in case the CPU returns unknown information (e.g. from the highest CPUID function supported) from unsupported CPUID functions.
2.2) Use "CPUID with EAX=0x80000001" to get (AMD's) extended feature flags. Test bit 29 in EDX to determine if long mode is supported.
Note 3: For UEFI boot loaders you can always assume CPUID is supported (e.g. for 32-bit UEFI). For 64-bit UEFI you can skip all of it (you're already using long mode so it must be supported).


text:
Q: Why is my login error message not displaying in Python Flask I have created a login page with Python flask , that is connected to an SQLite3 database. When I enter the correct user details , I login into the system as expected. But when I enter incorrect details , the login page just refreshes without showing the error message.
Here is my code
@app.route('/', methods=['GET', 'POST'])
def login():

r = ""
msg = ""
if (request.method == "POST"):
    usertype = request.form["UserType"]
    username = request.form["Username"]
    password = request.form["Password"]
    conn = sqlite3.connect("database.db")
    c = conn.cursor()
    c.execute("SELECT UserType,Username,Password FROM users WHERE UserType='" + usertype + "' and Username= '" + username + "' and Password='" + password + "'")
    r = c.fetchall()
    for i in r:
        if (usertype == i[0] and username == i[1] and password == i[2]):
            session["loginsuccess"] = True
            session["username"] = username
            return redirect(url_for("navigate"))
        else:
            msg = "Please enter correct login details"

return render_template("Login.html", msg=msg)

Html code
`Username

<input name="Username" type=Username placeholder="Enter username" required
 oninvalid="this.setCustomValidity('Username is required')"
 oninput="this.setCustomValidity('')"/>

Password

<input name="Password" type=Password placeholder="Enter password" required
 oninvalid="this.setCustomValidity('Password is required')"
 oninput="this.setCustomValidity('')">

<input type="submit" value="Login">

{{msg}}

A: In your code base if query return at least one result then only your msg will be displayed else it won't. So try this code.
@app.route('/', methods=['GET', 'POST'])
def login():
    msg = ""
    if (request.method == "POST"):
        usertype = request.form["UserType"]
        username = request.form["Username"]
        password = request.form["Password"]
        conn = sqlite3.connect("database.db")
        cur = conn.cursor()
        cur.execute("SELECT UserType,Username,Password FROM users "
                    "WHERE UserType='" + usertype + "' and Username= '" + username + "' and Password='" + password + "'")
        result = cur.fetchall()
        if result:
            for i in result:
                if usertype == i[0] and username == i[1] and password == i[2]:
                    session["loginsuccess"] = True
                    session["username"] = username
                    return redirect(url_for("navigate"))
        else:
            msg = "Please enter correct login details"
    return render_template("Login.html", msg=msg)


text:
Q: Why is make complaining about circular dependencies? I have built a make file for my project, and it works (everything compiles) but it gives these irritating error messages:
make: Circular zpr.c <- zpr.o dependency dropped.
gcc -Wall   -c -o zpr.o zpr.c
make: Circular readjpeg.c <- readjpeg.o dependency dropped.
gcc -Wall   -c -o readjpeg.o readjpeg.c
make: Circular readppm.c <- readppm.o dependency dropped.
gcc -Wall   -c -o readppm.o readppm.c
make: Circular SceneNode.cpp <- SceneNode.o dependency dropped.
g++    -c -o SceneNode.o SceneNode.cpp
make: Circular BoundingBoxNode.cpp <- BoundingBoxNode.o dependency dropped.
g++    -c -o BoundingBoxNode.o BoundingBoxNode.cpp
make: Circular GeometryNode.cpp <- GeometryNode.o dependency dropped.
g++    -c -o GeometryNode.o GeometryNode.cpp
make: Circular SceneGraph.cpp <- SceneGraph.o dependency dropped.
g++    -c -o SceneGraph.o SceneGraph.cpp
make: Circular testgraph.cpp <- testgraph.o dependency dropped.
g++    -c -o testgraph.o testgraph.cpp

My makefile is not complicated at all so hopefully someone can spot the error.
GXX=g++
CC=gcc
CFLAGS=-Wall

LIBS=-lGL -lglut -ljpeg

OBJS=helpers.o loadobj.o zpr.o readjpeg.o readppm.o SceneNode.o BoundingBoxNode.o GeometryNode.o SceneGraph.o  testgraph.o
OBJS2=testgraph.o SceneGraph.o GeometryNode.o BoundingBox.o SceneNode.o readppm.o readjpeg.o zpr.o loadobj.o helpers.o
SRCS=testgraph.cpp SceneGraph.cpp SceneNode.cpp

.o.cpp:
    $(GXX) $(CFLAGS) -c $<

.o.c:
    $(CC) $(CFLAGS) -c $<

testgraph: $(OBJS)
    $(GXX) $(LIBS) $(OBJS) -o testgraph

clean:
    rm *.o

A: Your implicit rules are the culprit. They have the extensions listed in the reverse order of how they are understood by make.
.o.c:

tells make that .c files are created from .o files. Since there is already a rule that says that .o files are created from .c files, you have a circular dependencies and therefore the errors.
The solution is (or should be, assuming a reasonably configured make) simple.
You don't (usually) need to specify your own rules for compilation in really common cases, such as C++ sources. It would be simpler to just specify something like:
CFLAGS=-Wall
LOADLIBES=-lGL -lglut -ljpeg

OBJS=helpers.o loadobj.o zpr.o readjpeg.o readppm.o SceneNode.o \
   BoundingBoxNode.o GeometryNode.o SceneGraph.o  testgraph.o

all: testgraph

testgraph: $(OBJS)

This is likely to also help you avoid two errors.

*

*The rules you wrote say that .o files are created from .c files, which is backwards. But the correct rules already exist in nearly all versions of make.

*You have listed the libraries ahead of the object files. This works by accident on some platforms that use ELF format objects. But it is still wrong. List libraries after objects because libraries are only loaded to satisfy undefined externals.


text:
Q: I'm not getting the expected result of the variable I'm calling I came across something strange. Here two variables which store two differents results:
const membersSortedByCurrentStageTotalPoints = teamMembers.sort((a, b) => compareRanking(a,b,currentIndex));

const membersSortedByRankingType = teamMembers.sort((a, b) => compare(a, b, "points"))

But when I'm using the variable membersSortedByCurrentStageTotalPoints I get the results of the variable membersSortedByRankingType.
Anyone would know why ?

A: From the MDN documentation for sort:

Return value
The sorted array. Note that the array is sorted in place, and no copy
is made.

The two variables both have the same value: A reference to the same array.


text:
Q: Python serial.read() split error I have an Arduino connected to my PC. The Arduino sends this over serial:
xx,yyy\n and I want to split it into two variables ... xx to tep and yyy to tlak, so I have written the following but it is giving me an error:
print("A list of the serial ports available on the system:")
print(serial_ports())
port = "COM" + input("Please enter the port number...")
# Setup
ser = serial.Serial(port, 9600, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)

while True:
    sercan = ser.read()
    can = sercan.decode("utf-8")
    tep, tlak = can.split(",")
    print("T:", tep, " Tl:", tlak)
    #print(can)

And result:
tep, tlak = can.split(",")
ValueError: not enough values to unpack (expected 2, got 1)

Why do I get this error?

A: The problem is in using sercan = ser.read() where read reads by default only 1 byte according to pySerial documentation.
Workaround is to read until '\n' is received or to use readline or to specify number of bytes to read.


text:
Q: EMR 6.3 Spark 3.1.1 resource file MalformedInputException I have a maven project with a category.txt file in src/main/resources.
I have a simple job:
package com.test.utilityjobs

import scala.io.Source

object CategoriesLoadingTestJob {

  def main(args: Array[String]): Unit = {
    val categoryListSource = Source.fromInputStream(getClass.getResourceAsStream("/categories.txt"))
    categoryListSource.getLines().toList.foreach(println)
  }
}

Which works fine if launched on my local machine or in emr 5.*
However, in emr 6.3, whenever I launch this simple job, I get this error:
java.nio.charset.MalformedInputException: Input length = 1

I've also tried
val categoryListSource: BufferedSource = Source.fromResource("cat2.txt")

but this gives me the same error.
I've checked the file encoding, it is UTF-8. The compiler encoding is UTF-8. I've tried with other files and everything works fine

A: It is possible to specify the encoding while reading a property file in scala, so I tried
val categoryListSource = Source.fromInputStream(getClass.getResourceAsStream("/categories.txt"))("UTF-8")

and it worked. It still complains about files with BOM so I removed the BOM from the existing file.


text:
Q: Regex to match xml tag with multiple attributes I'm trying to find a regular expression that can match the tag <w:proofErr .... />.
The regex101 link: regex101
The original string is:
<w:pPr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:autoSpaceDE w:val="0"/><w:autoSpaceDN w:val="0"/><w:adjustRightInd w:val="0"/><w:spacing w:after="0" w:line="240" w:lineRule="auto"/><w:rPr><w:rFonts w:cs="SerifGothicStd-Bold"/><w:b/><w:bCs/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr></w:pPr><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="spellStart"/><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="gramStart"/><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:rsidRPr="008D22B1"><w:rPr><w:rFonts w:cs="SerifGothicStd-Bold"/><w:b/><w:bCs/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t>student</w:t></w:r><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="spellEnd"/><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="gramEnd"/><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:rsidRPr="008D22B1"><w:rPr><w:rFonts w:cs="SerifGothicStd-Bold"/><w:b/><w:bCs/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="spellStart"/><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:rsidRPr="008D22B1"><w:rPr><w:rFonts w:cs="SerifGothicStd-Bold"/><w:b/><w:bCs/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t>learning</w:t></w:r><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="spellEnd"/><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:rsidRPr="008D22B1"><w:rPr><w:rFonts w:cs="SerifGothicStd-Bold"/><w:b/><w:bCs/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="spellStart"/><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:rsidRPr="008D22B1"><w:rPr><w:rFonts w:cs="SerifGothicStd-Bold"/><w:b/><w:bCs/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t>outcomes</w:t></w:r><w:proofErr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:type="spellEnd"/><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:rsidRPr="008D22B1"><w:rPr><w:rFonts w:cs="SerifGothicStd-Bold"/><w:b/><w:bCs/><w:sz w:val="24"/><w:szCs w:val="24"/></w:rPr><w:t>*</w:t></w:r><w:autoSpaceDE xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:val="0"/><w:autoSpaceDN xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:val="0"/>

And I'm trying with the following regex:
/<w:proofErr.+(?:\/>)/g

But when I run it there's only one big match with all the text starting in the first <w:prrofErr and finishing at the end of the string.
How can I use a regex to match every <w:proofErr .... />?

A: Your regex works, but it greedily matches the start of your tag with any string representing the end of the tag. Basically, that big blue group is one big "tag" as far as regex is concerned.
Here's one way to solve this. Try this regex:
<w:proofErr[^>]+(?:"\/>)

It replaces .* with [^>]*, which tells it to match any character except a closing bracket.


text:
Q: How to create a Union type in F# that is a value type? Normal F# Discriminated Unions are reference types. How can I create a simple (non-recursive and with only value-type fields) union type in F# that is a value type?
Based on some internet searching my current (non-working) attempt looks as follows:
[<StructLayout(LayoutKind.Explicit)>]
type Float =
    [<DefaultValue>] [<FieldOffset 0>] val mutable Val1 : float
    [<DefaultValue>] [<FieldOffset 0>] val mutable Int1 : int
    new (a:float) = {Val1 = a}

The following blog post appears to show what is possible via C#
I'm aware that the above is NOT idiomatic use of F# but I am trying to optimize the performance of a portion of my application and profiling has clearly shown that the cost of heap allocations (JIT_new) is what is causing my performance bottleneck... A simple union type is the perfect data structure for my needs, just not a heap allocated one.

A: First of all, I would probably not do this, unless I had very good reasons. In most cases, the difference between structs and reference types is not really that big - in my experience, it only matters when you have a very large array of them (then structs let you allocate one big memory chunk).
That said, it looks like F# does not like the constructor code in your example. I'm really not sure why (it seems to be doing some check that does not quite work for overlapping structs), but the following does the trick:
[<Struct; StructLayout(LayoutKind.Explicit)>]
type MyStruct =
    [<DefaultValue; FieldOffset 0>]
    val mutable Val1 : float
    [<DefaultValue; FieldOffset 0>]
    val mutable Int1 : int
    static member Int(a:int) = MyStruct(Int1=a)
    static member Float(f:float) = MyStruct(Val1=f)

If I actually wanted to use this, I would add another field Tag containing 1 or 0 depending on which case your struct represents. Then you could pattern match on it using an active pattern and get some of the safety of discriminated unions back:
let (|Float|Int|) (s:MyStruct) =
  if s.Tag = 0 then Float(s.Val1) else Int(s.Int1)

A: Struct unions are now supported by F#, see F# RFC FS-1014 for details. In short:

// Single case:

[<Struct>]
type UnionExample = U of int * int * bool

// Multi-case:

[<Struct>]
type Shape =
   | Circle of radius: double
   | Square of side: int

Key differences in struct records:

*

*You cannot have cyclic references to the same type being defined. ex: type T = U of T

*You also cannot call the default ctor, like you could with normal F# structs.

*For multi-case struct unions, each case must have a unique name.


text:
Q: Format Unix time using Get-Date -UFormat I'm trying to convert Unix Epoch time to a readable format. See example code:
# First convert time to Unix time seconds.
$time = Get-Date -Hour 12 - Minute 30 -Second 0
([datetimeoffset]$time).ToUnixTimeSeconds()
1552912200

All OK. Now I'm trying to format the time in reverse:
Get-Date 1552912200 -UFormat %R
00:02

This is not correct. Why is 00:02 output? When I am expecting 12:30

A: Because Get-Date expects a DateTime object:
Get-Help Get-Date
# Get-Date [[-Date] <DateTime>] ...

So the value 1552912200 is implicitly converted to DateTime, which results in 01.01.0001 00:02:35. That's why you get 00:02
You need to pass a DateTime object:
$datetime = [DateTimeOffset]::FromUnixTimeSeconds(1552912200).DateTime
Get-Date $datetime -UFormat '%R'


text:
Q: spa upshot how to access grandparent entity? I'm trying to get an SPA working with the following basic models:
public class Owner
{
    public int OwnerId { get; set; }
    [Required]
    public string Name { get; set; }

    public virtual ICollection<TodoItem> TodoItems { get; set; }
}

public class TodoItem
{
    public int TodoItemId { get; set; }
    [Required]
    public string Title { get; set; }
    public bool IsDone { get; set; }

    public int OwnerId { get; private set; }
    public virtual Owner Owner { get; set; }
    public virtual ICollection<ActionItem> ActionItems { get; set; }
}

public class ActionItem
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int TodoItemId { get; private set; }
    public virtual TodoItem TodoItem { get; private set; }
}

and in my view I tried this:

I also tried adding a computed property to ActionItem containing the owner name:
public string OwnerName
{
get { return this.TodoItem.Owner.Name; }
}

and calling:

but if I add a different static string and set the value manually:
public string SomethingElse { get; set; }

then this works fine:

What am I doing wrong?
Cheers

A: As suggested by Obiwan007, you case solve the serialization issues by setting the back reference to NULL. You can also apply the [IgnoreDataMember] attribute if you are using Code First.
Upshot only makes the parent entities observable and not their child entities. So when using the built-in mapping functionality, data-binding to child entities will not work.
The solution is to manually create your client-side entities in Javascript and map them yourself. I posted a working solution in response to a different question: https://stackoverflow.com/a/10010695/1226140

A: Try to use the $parent variable:


text:
Q: Passing derived class pointer to function expecting base pointer by reference I have a key-value container class that holds pointers to heap-allocated objects of a base type. The insert method of the container instantiates one of 2 derived class objects (based on a runtime flag) and inserts it into itself.
I have a Find method with the following signature:
bool Find(int key, Base *&result);

The classes that use of this container know which derived class is actually being stored, because there is a one-to-one mapping between a user of the class and one of the derived types.
So when a user tries to call the Find method as follows:
DerivedA *a = nullptr;
bool found = container.Find(10, a);

I get a compiler error saying that there is no matching function.
So it seems that implicit conversion isn't happening between the base and derived classes. I suspect it has to do with the fact that I'm passing the pointer by reference, but I'm not sure.
What is the "correct" way to achieve what I'm after here?
Thanks!

A:
I suspect it has to do with the fact that I'm passing the pointer by reference

Imagine that Find updates the passed pointer and now it points at a new instance of Base. But the caller still interprets it as a pointer to DerivedA.
Basically the issue is that you can assign
Base* basePtr = &derived;

but not the way around. So if the only guarantee of your Find method is that it finds an instance of Base type, we cannot just assign the pointer to it to DerivedA.
If you do know that your Base class pointer points at DerivedA, you could consider dynamic_cast:
Base* Find(int key);
....
DerivedA* a = dynamic_cast<DerivedA*>(Find(key));

(Returning the pointer might be better, as @juanchopanza comment suggests.)

A: Add an overload of Find
Base *pi=result;
bool r=Find(key,pi);
result=dynamic_cast<DerivedA *>(pi);
return r;


text:
Q: Rails 5: ActiveRecord AND followed by OR condition: A && (B || C) My below active record statements are working fine:
Requirement.where(no: 0)

Requirement.yes_no.or(Requirement.where.not(parent_req: nil))

In Requirement model I have an enum field, which is working fine too:
enum response_type: { yes_no: 0, document: 1, interviewee: 2, sample_set: 3, brief_desc: 4 }

But when I combine above two statements:
Requirement.where(no: 0).where(Requirement.yes_no.or(Requirement.where.not(parent_req: nil)))

It is giving me error:
ArgumentError: Unsupported argument type: #<Requirement::ActiveRecord_Relation:0x005567c7c9bf88> (Requirement::ActiveRecord_Relation)

I expect the following query to be run:
SELECT `requirements`.*
  FROM `requirements`
 WHERE `requirements`.`no` = 0
   AND (`requirements`.`response_type` = 0
    OR (`requirements`.`parent_req` IS NOT NULL))

A: Rails 5: ActiveRecord OR query
Requirement.yes_no.or(Requirement.where.not(parent_req: nil)).where(no: 0)
put where(no: 0) at the end of ar query

A: To combine using AND (intersection), merge as mentioned by Tom Lord worked.
Requirement.where(no: 0).merge(Requirement.yes_no.or(Requirement.where.not(parent_req: nil)))


text:
Q: Displaying Banner Ad in bottom of RecyclerView? I want to display a simple banner ad in RecyclerView which loads a list of images. just a simple bottom banner ad.
This is my RecyclerViewXML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/list"
android:name="com.example.fragmentactivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FAC873"
app:layoutManager="StaggeredGridLayoutManager"
tools:context="com.example.fragmentactivity"
tools:listitem="@layout/fragment_image" />

if I try to put to the recyclerView inside RelativeLayout or any other so i could include banner in the bottom, but then it wont display any images.
How can I display banner in that view?
I tried almost all the available solution to dynamically add the banner but nothing worked

A: You should add the banner to the bottom and in the front of the  RecyclerView. For do that this will help you:
Usage: Replace the RelativeLayout for your AdMobView
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list"
            android:name="com.example.fragmentactivity"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FAC873"
            app:layoutManager="StaggeredGridLayoutManager"
            tools:context="com.example.fragmentactivity" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="52dp"
            android:background="#fff"
            android:layout_alignParentBottom="true" />
    </RelativeLayout>

Explanation: . The RelativeLayout is bellow RecyclerView and it is  android:layout_alignParentBottom="true" overlaying the RecyclerView.

A: I have it working perfectly well by first adding the adview at the bottom and then adding the recycler view above it (leaving a margin at the bottom for the adview that was placed earlier and then filling the parent with the recycler view). My layout is as follows:
Note: In my case it is MoPubView Replace it with your Adview from Admob.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:background="@color/color_green"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_category_list"
    tools:context=".CategoryListActivity">

    <!-- I'm using Mopub, replace the MoPubView with AdView in your case -->
    <com.mopub.mobileads.MoPubView
        android:id="@+id/adview"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:scrollbars="vertical"
        android:layout_marginBottom="60dp" />

</RelativeLayout>


text:
Q: How to add an application as a login item for all users in Mac OSX I am trying to add an application as login item for all users by creating an launchd plist and copying it in /Library/LaunchAgents and also by loading it.
Plist is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>com.testapp.UserAgent</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Applications/TestAgent.app/Contents/MacOS/TestAgent</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>KeepAlive</key>
        <false/>
</dict>
</plist>

RunAtLoad will launch the application at every login.
It is working for me when I login in to all different user accounts in my machine but if I quit it manually then also it is launching by itself.
How can I make it to launch only once for each login and if I quit it then it should not be launched by itself.

A: The best resource to know how to use launchd, the daemon that launches processes on macOS is here:
https://www.launchd.info
In here, it is well explained what other settings you can use apart from RunAtLoad or together with it.
For example, in your case, you could use the key KeepAlive as follows:
 <key>KeepAlive</key>
 <dict>
    <key>SuccessfulExit</key>
    <false/>
 </dict>

This would only relaunch your process if it exited with a code different than 0, which normally denotes some abnormal situation or error. If the exit is normal then your process will not be relaunched by launchd.
Check the tab Configuration on this site to know which other configurations you could use.


text:
Q: "Join Attributes By Nearest" in QGIS Graphical Modeler Shifts Attribute Field Order I am using the QGIS Graphical Modeler to sample a DEM using two created point features (road & pipeline) then use a spatial join to find the three closest road locations to a pipe location.  The output of the sampled features are as expected, but when I try and use the 'Join By Nearest' tool in the Graphical Modeler to find the closest sampled road locations to sampled pipeline points, it shifts the joined column data of input layer 2 (road) to the right one spot.
However, when I do this same process manually it works out ok.